Update BoringSSL to 8eb25be6fa18d475291122887a7bccd3762ff236 (#607)

As a standard pattern, the vendoring script needed some changes, as did
our internal code.

The biggest change here is that BoringSSL has changed its name mangling
scheme. This causes us to no longer need to explicitly write the prefix
out anymore: in fact, doing that causes compiler errors. So this patch
rewrites the code to resolve that issue.

Along the way, I've also added some checks for making sure the name
mangling is correct.
This commit is contained in:
Cory Benfield authored and GitHub committed 2026-10-09 17:19:47 +00:00
1 parent 223204805d
commit 86458a336b
717 files changed
+110173 -91954

No files matched your search

@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 201953
"mallocCountTotal" : 201700
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 641893
"mallocCountTotal" : 423833
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 201954
"mallocCountTotal" : 201685
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 642876
"mallocCountTotal" : 424806
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 201954
"mallocCountTotal" : 201649
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 641884
"mallocCountTotal" : 423800
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 201954
"mallocCountTotal" : 201649
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 641871
"mallocCountTotal" : 423793
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 201954
"mallocCountTotal" : 201649
}
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 641894
"mallocCountTotal" : 423799
}
+1 -4
View File
@@ -22,7 +22,7 @@ import PackageDescription
// Sources/CNIOBoringSSL directory. The source repository is at
// https://boringssl.googlesource.com/boringssl.
//
// BoringSSL Commit: 817ab07ebb53da35afea409ab9328f578492832d
// BoringSSL Commit: 8eb25be6fa18d475291122887a7bccd3762ff236
/// This function generates the dependencies we want to express.
///
@@ -73,9 +73,6 @@ let package = Package(
.library(name: "NIOSSL", targets: ["NIOSSL"]),
.executable(name: "NIOTLSServer", targets: ["NIOTLSServer"]),
.executable(name: "NIOSSLHTTP1Client", targets: ["NIOSSLHTTP1Client"]),
/* This target is used only for symbol mangling. It's added and removed automatically because it emits build warnings. MANGLE_START
.library(name: "CNIOBoringSSL", type: .static, targets: ["CNIOBoringSSL"]),
MANGLE_END */
],
dependencies: generateDependencies(),
targets: [
+44
View File
@@ -0,0 +1,44 @@
// Copyright 2025 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <assert.h>
#include <CNIOBoringSSL_aes.h>
#include "../fipsmodule/bcm_interface.h"
using namespace bssl;
void AES_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) {
BCM_aes_encrypt(in, out, key);
}
void AES_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) {
BCM_aes_decrypt(in, out, key);
}
int AES_set_encrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey) {
if (bits != 128 && bits != 192 && bits != 256) {
return -2;
}
return bcm_success(BCM_aes_set_encrypt_key(key, bits, aeskey)) ? 0 : -1;
}
int AES_set_decrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey) {
if (bits != 128 && bits != 192 && bits != 256) {
return -2;
}
return bcm_success(BCM_aes_set_decrypt_key(key, bits, aeskey)) ? 0 : -1;
}
@@ -0,0 +1,67 @@
#ifndef OPENSSL_CRYPTO_CPU_ARMV8_FEATURE_PARSING_H
#define OPENSSL_CRYPTO_CPU_ARMV8_FEATURE_PARSING_H
#include <CNIOBoringSSL_cpu.h>
#include <stdint.h>
#include "internal.h"
#if defined(OPENSSL_AARCH64)
BSSL_NAMESPACE_BEGIN
namespace armcap {
// Common field indices based on ARM architecture specification for
// ID_AA64ISAR0_EL1. These are indices (multiplied by 4 for the bit shift).
// Note: SHA3_FIELD_IDX 8 * 4 = 32 (ID_AA64ISAR0_EL1_SHA3_SHIFT value)
#define ID_AA64ISAR0_AES_FIELD_IDX 1 // Bits [7:4]
#define ID_AA64ISAR0_SHA1_FIELD_IDX 2 // Bits [11:8]
#define ID_AA64ISAR0_SHA2_FIELD_IDX 3 // Bits [15:12]
#define ID_AA64ISAR0_SHA3_FIELD_IDX 8 // Bits [35:32]
#define NBITS_ID_FIELD 4
// Helper function to extract a 4-bit field based on its index.
inline unsigned GetIDField(uint64_t reg, unsigned field_idx) {
// We mask with 0xf to ensure only the 4 relevant bits are returned.
return (reg >> (field_idx * NBITS_ID_FIELD)) & 0xf;
}
// The core function that converts the raw ID_AA64ISAR0 register value
// into the OR'd capability flags (ARMV8_AES, ARMV8_SHA3, etc.).
inline uint32_t ParseISAR0Flags(uint64_t isar0) {
uint32_t armcap = 0;
// AES and PMULL check
unsigned aes = GetIDField(isar0, ID_AA64ISAR0_AES_FIELD_IDX);
if (aes > 0) {
armcap |= ARMV8_AES;
}
if (aes > 1) {
armcap |= ARMV8_PMULL;
}
// SHA1 check
unsigned sha1 = GetIDField(isar0, ID_AA64ISAR0_SHA1_FIELD_IDX);
if (sha1 > 0) {
armcap |= ARMV8_SHA1;
}
// SHA256 and SHA512 check
unsigned sha2 = GetIDField(isar0, ID_AA64ISAR0_SHA2_FIELD_IDX);
if (sha2 > 0) {
armcap |= ARMV8_SHA256;
}
if (sha2 > 1) {
armcap |= ARMV8_SHA512;
}
// SHA3 (EOR3) check
unsigned sha3 = GetIDField(isar0, ID_AA64ISAR0_SHA3_FIELD_IDX);
if (sha3 > 0) {
armcap |= ARMV8_SHA3;
}
return armcap;
}
} // namespace armcap
BSSL_NAMESPACE_END
#endif // OPENSSL_AARCH64
#endif // OPENSSL_CRYPTO_CPU_ARMV8_FEATURE_PARSING_H
+175 -116
View File
@@ -1,80 +1,93 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
#include <assert.h>
#include <limits.h>
#include <string.h>
#include <CNIOBoringSSL_bytestring.h>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_span.h>
#include "../internal.h"
#include "internal.h"
int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, const unsigned char *d,
ossl_ssize_t len) {
return ASN1_STRING_set(x, d, len);
using namespace bssl;
static void set_unused_bits(ASN1_BIT_STRING *str, uint8_t unused_bits) {
assert(unused_bits < 8);
assert(unused_bits == 0 || str->length > 0);
// `ASN1_STRING_FLAG_BITS_LEFT` and the bottom 3 bits encode `padding`.
str->flags &= ~0x07;
str->flags |= ASN1_STRING_FLAG_BITS_LEFT | unused_bits;
}
int asn1_bit_string_length(const ASN1_BIT_STRING *str,
uint8_t *out_padding_bits) {
int len = str->length;
if (str->flags & ASN1_STRING_FLAG_BITS_LEFT) {
// If the string is already empty, it cannot have padding bits.
*out_padding_bits = len == 0 ? 0 : str->flags & 0x07;
return len;
}
int ASN1_BIT_STRING_set(ASN1_BIT_STRING *str, const uint8_t *data,
ossl_ssize_t len) {
return ASN1_STRING_set(str, data, len);
}
// TODO(https://crbug.com/boringssl/447): If we move this logic to
// |ASN1_BIT_STRING_set_bit|, can we remove this representation?
while (len > 0 && str->data[len - 1] == 0) {
len--;
int ASN1_BIT_STRING_set1(ASN1_BIT_STRING *str, const uint8_t *data,
size_t length, int unused_bits) {
if (unused_bits < 0 || unused_bits > 7) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
return 0;
}
uint8_t padding_bits = 0;
if (len > 0) {
uint8_t last = str->data[len - 1];
assert(last != 0);
for (; padding_bits < 7; padding_bits++) {
if (last & (1 << padding_bits)) {
break;
}
}
const uint8_t unused_bits_mask = (1 << unused_bits) - 1;
if ((length > 0 && (data[length - 1] & unused_bits_mask) != 0) ||
(length == 0 && unused_bits != 0)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
return 0;
}
*out_padding_bits = padding_bits;
return len;
if (!ASN1_STRING_set(str, data, length)) {
return 0;
}
str->type = V_ASN1_BIT_STRING;
set_unused_bits(str, unused_bits);
return 1;
}
uint8_t ASN1_BIT_STRING_unused_bits(const ASN1_BIT_STRING *str) {
// If the string is already empty, it cannot have padding bits.
return str->length == 0 ? 0 : str->flags & 0x07;
}
int ASN1_BIT_STRING_num_bytes(const ASN1_BIT_STRING *str, size_t *out) {
uint8_t padding_bits;
int len = asn1_bit_string_length(str, &padding_bits);
if (padding_bits != 0) {
if (ASN1_BIT_STRING_unused_bits(str) != 0) {
return 0;
}
*out = len;
*out = str->length;
return 1;
}
int i2c_ASN1_BIT_STRING(const ASN1_BIT_STRING *a, unsigned char **pp) {
if (a == NULL) {
if (a == nullptr) {
return 0;
}
uint8_t bits;
int len = asn1_bit_string_length(a, &bits);
uint8_t bits = ASN1_BIT_STRING_unused_bits(a);
int len = ASN1_STRING_length(a);
if (len > INT_MAX - 1) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_OVERFLOW);
return 0;
}
int ret = 1 + len;
if (pp == NULL) {
if (pp == nullptr) {
return ret;
}
@@ -89,106 +102,154 @@ int i2c_ASN1_BIT_STRING(const ASN1_BIT_STRING *a, unsigned char **pp) {
return ret;
}
ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
const unsigned char **pp, long len) {
ASN1_BIT_STRING *ret = NULL;
const unsigned char *p;
unsigned char *s;
int padding;
uint8_t padding_mask;
int bssl::asn1_marshal_bit_string(CBB *out, const ASN1_BIT_STRING *in,
CBS_ASN1_TAG tag) {
int len = i2c_ASN1_BIT_STRING(in, nullptr);
if (len <= 0) {
return 0;
}
tag = tag == 0 ? CBS_ASN1_BITSTRING : tag;
CBB child;
uint8_t *ptr;
return CBB_add_asn1(out, &child, tag) && //
CBB_add_space(&child, &ptr, static_cast<size_t>(len)) && //
i2c_ASN1_BIT_STRING(in, &ptr) == len && //
CBB_flush(out);
}
if (len < 1) {
static int asn1_parse_bit_string_contents(Span<const uint8_t> in,
ASN1_BIT_STRING *out) {
CBS cbs = in;
uint8_t padding;
if (!CBS_get_u8(&cbs, &padding)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_SHORT);
goto err;
return 0;
}
if (len > INT_MAX) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_LONG);
goto err;
}
if ((a == NULL) || ((*a) == NULL)) {
if ((ret = ASN1_BIT_STRING_new()) == NULL) {
return NULL;
}
} else {
ret = (*a);
}
p = *pp;
padding = *(p++);
len--;
if (padding > 7) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
goto err;
return 0;
}
// Unused bits in a BIT STRING must be zero.
padding_mask = (1 << padding) - 1;
if (padding != 0 && (len < 1 || (p[len - 1] & padding_mask) != 0)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_PADDING);
goto err;
}
// We do this to preserve the settings. If we modify the settings, via
// the _set_bit function, we will recalculate on output
ret->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); // clear
ret->flags |= (ASN1_STRING_FLAG_BITS_LEFT | padding); // set
if (len > 0) {
s = reinterpret_cast<uint8_t *>(OPENSSL_memdup(p, len));
if (s == NULL) {
goto err;
uint8_t padding_mask = (1 << padding) - 1;
if (padding != 0) {
CBS copy = cbs;
uint8_t last;
if (!CBS_get_last_u8(&copy, &last) || (last & padding_mask) != 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_PADDING);
return 0;
}
p += len;
} else {
s = NULL;
}
ret->length = (int)len;
OPENSSL_free(ret->data);
ret->data = s;
ret->type = V_ASN1_BIT_STRING;
if (a != NULL) {
(*a) = ret;
return ASN1_BIT_STRING_set1(out, CBS_data(&cbs), CBS_len(&cbs), padding);
}
ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
const unsigned char **pp, long len) {
if (len < 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_SHORT);
return nullptr;
}
*pp = p;
ASN1_BIT_STRING *ret = nullptr;
if (a == nullptr || *a == nullptr) {
if ((ret = ASN1_BIT_STRING_new()) == nullptr) {
return nullptr;
}
} else {
ret = *a;
}
if (!asn1_parse_bit_string_contents(Span(*pp, len), ret)) {
if (ret != nullptr && (a == nullptr || *a != ret)) {
ASN1_BIT_STRING_free(ret);
}
return nullptr;
}
if (a != nullptr) {
*a = ret;
}
*pp += len;
return ret;
err:
if ((ret != NULL) && ((a == NULL) || (*a != ret))) {
ASN1_BIT_STRING_free(ret);
}
int bssl::asn1_parse_bit_string(CBS *cbs, ASN1_BIT_STRING *out,
CBS_ASN1_TAG tag) {
tag = tag == 0 ? CBS_ASN1_BITSTRING : tag;
CBS child;
if (!CBS_get_asn1(cbs, &child, tag)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
return NULL;
return asn1_parse_bit_string_contents(child, out);
}
int bssl::asn1_parse_bit_string_with_bad_length(CBS *cbs,
ASN1_BIT_STRING *out) {
CBS child;
CBS_ASN1_TAG tag;
size_t header_len;
int indefinite;
if (!CBS_get_any_ber_asn1_element(cbs, &child, &tag, &header_len,
/*out_ber_found=*/nullptr,
&indefinite) ||
tag != CBS_ASN1_BITSTRING || indefinite || //
!CBS_skip(&child, header_len)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
return asn1_parse_bit_string_contents(child, out);
}
static void trim_trailing_zeros(ASN1_BIT_STRING *a) {
while (a->length > 0 && a->data[a->length - 1] == 0) {
a->length--;
}
uint8_t padding_bits = 0;
if (a->length > 0) {
uint8_t last = a->data[a->length - 1];
assert(last != 0);
for (; padding_bits < 7; padding_bits++) {
if (last & (1 << padding_bits)) {
break;
}
}
}
set_unused_bits(a, padding_bits);
}
// These next 2 functions from Goetz Babin-Ebell <babinebell@trustcenter.de>
int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value) {
int w, v, iv;
unsigned char *c;
if (a == nullptr) {
return 0;
}
w = n / 8;
v = 1 << (7 - (n & 0x07));
iv = ~v;
if (n < 0) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
int w = n / 8;
int v = 1 << (7 - (n & 0x07));
int iv = ~v;
if (!value) {
v = 0;
}
if (a == NULL) {
return 0;
}
a->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); // clear, set on write
if ((a->length < (w + 1)) || (a->data == NULL)) {
if ((a->length < (w + 1)) || (a->data == nullptr)) {
if (!value) {
trim_trailing_zeros(a);
return 1; // Don't need to set
}
if (a->data == NULL) {
unsigned char *c;
if (a->data == nullptr) {
c = (unsigned char *)OPENSSL_malloc(w + 1);
} else {
c = (unsigned char *)OPENSSL_realloc(a->data, w + 1);
}
if (c == NULL) {
if (c == nullptr) {
return 0;
}
if (w + 1 - a->length > 0) {
@@ -197,10 +258,8 @@ int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value) {
a->data = c;
a->length = w + 1;
}
a->data[w] = ((a->data[w]) & iv) | v;
while ((a->length > 0) && (a->data[a->length - 1] == 0)) {
a->length--;
}
a->data[w] = (a->data[w] & iv) | v;
trim_trailing_zeros(a);
return 1;
}
@@ -209,7 +268,7 @@ int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n) {
w = n / 8;
v = 1 << (7 - (n & 0x07));
if ((a == NULL) || (a->length < (w + 1)) || (a->data == NULL)) {
if ((a == nullptr) || (a->length < (w + 1)) || (a->data == nullptr)) {
return 0;
}
return ((a->data[w] & v) != 0);
+18 -16
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -16,13 +21,10 @@
int i2d_ASN1_BOOLEAN(ASN1_BOOLEAN a, unsigned char **outp) {
CBB cbb;
if (!CBB_init(&cbb, 3) || //
!CBB_add_asn1_bool(&cbb, a != ASN1_BOOLEAN_FALSE)) {
CBB_cleanup(&cbb);
return -1;
}
return CBB_finish_i2d(&cbb, outp);
return bssl::I2DFromCBB(
/*initial_capacity=*/3, outp, [&](CBB *cbb) -> bool {
return CBB_add_asn1_bool(cbb, a != ASN1_BOOLEAN_FALSE);
});
}
ASN1_BOOLEAN d2i_ASN1_BOOLEAN(ASN1_BOOLEAN *out, const unsigned char **inp,
@@ -40,7 +42,7 @@ ASN1_BOOLEAN d2i_ASN1_BOOLEAN(ASN1_BOOLEAN *out, const unsigned char **inp,
}
ASN1_BOOLEAN ret = val ? ASN1_BOOLEAN_TRUE : ASN1_BOOLEAN_FALSE;
if (out != NULL) {
if (out != nullptr) {
*out = ret;
}
*inp = CBS_data(&cbs);
+16 -11
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -22,7 +27,7 @@ void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x) {
// Historically, this function did not impose a limit in OpenSSL and is used
// to read CRLs, so we leave this without an external bound.
if (!BIO_read_asn1(in, &data, &len, INT_MAX)) {
return NULL;
return nullptr;
}
const uint8_t *ptr = data;
void *ret = ASN1_item_d2i(reinterpret_cast<ASN1_VALUE **>(x), &ptr, len, it);
@@ -32,9 +37,9 @@ void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x) {
void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x) {
BIO *b = BIO_new_fp(in, BIO_NOCLOSE);
if (b == NULL) {
if (b == nullptr) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_BUF_LIB);
return NULL;
return nullptr;
}
void *ret = ASN1_item_d2i_bio(it, b, x);
BIO_free(b);
+19 -14
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -17,21 +22,21 @@
// directly dup the underlying structure instead of doing and encode and
// decode.
void *ASN1_item_dup(const ASN1_ITEM *it, void *x) {
unsigned char *b = NULL;
unsigned char *b = nullptr;
const unsigned char *p;
long i;
void *ret;
if (x == NULL) {
return NULL;
if (x == nullptr) {
return nullptr;
}
i = ASN1_item_i2d(reinterpret_cast<ASN1_VALUE *>(x), &b, it);
if (b == NULL) {
return NULL;
if (b == nullptr) {
return nullptr;
}
p = b;
ret = ASN1_item_d2i(NULL, &p, i, it);
ret = ASN1_item_d2i(nullptr, &p, i, it);
OPENSSL_free(b);
return ret;
}
+46 -20
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
#include <CNIOBoringSSL_bytestring.h>
@@ -19,7 +24,11 @@
#include "internal.h"
int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d) {
using namespace bssl;
int bssl::asn1_generalizedtime_to_tm(struct tm *tm,
const ASN1_GENERALIZEDTIME *d) {
if (d->type != V_ASN1_GENERALIZEDTIME) {
return 0;
}
@@ -31,19 +40,36 @@ int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d) {
return 1;
}
int bssl::asn1_parse_generalized_time(CBS *cbs, ASN1_GENERALIZEDTIME *out,
CBS_ASN1_TAG tag) {
tag = tag == 0 ? CBS_ASN1_GENERALIZEDTIME : tag;
CBS child;
if (!CBS_get_asn1(cbs, &child, tag) ||
!CBS_parse_generalized_time(&child, nullptr,
/*allow_timezone_offset=*/0)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
if (!ASN1_STRING_set(out, CBS_data(&child), CBS_len(&child))) {
return 0;
}
out->type = V_ASN1_GENERALIZEDTIME;
return 1;
}
int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *d) {
return asn1_generalizedtime_to_tm(NULL, d);
return asn1_generalizedtime_to_tm(nullptr, d);
}
int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str) {
size_t len = strlen(str);
CBS cbs;
CBS_init(&cbs, (const uint8_t *)str, len);
if (!CBS_parse_generalized_time(&cbs, /*out_tm=*/NULL,
if (!CBS_parse_generalized_time(&cbs, /*out_tm=*/nullptr,
/*allow_timezone_offset=*/0)) {
return 0;
}
if (s != NULL) {
if (s != nullptr) {
if (!ASN1_STRING_set(s, str, len)) {
return 0;
}
@@ -63,33 +89,33 @@ ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
long offset_sec) {
struct tm data;
if (!OPENSSL_posix_to_tm(posix_time, &data)) {
return NULL;
return nullptr;
}
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(&data, offset_day, offset_sec)) {
return NULL;
return nullptr;
}
}
if (data.tm_year < 0 - 1900 || data.tm_year > 9999 - 1900) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_TIME_VALUE);
return NULL;
return nullptr;
}
char buf[16];
int ret = snprintf(buf, sizeof(buf), "%04d%02d%02d%02d%02d%02dZ",
data.tm_year + 1900, data.tm_mon + 1, data.tm_mday,
data.tm_hour, data.tm_min, data.tm_sec);
// |snprintf| must write exactly 15 bytes (plus the NUL) to the buffer.
// `snprintf` must write exactly 15 bytes (plus the NUL) to the buffer.
BSSL_CHECK(ret == static_cast<int>(sizeof(buf) - 1));
int free_s = 0;
if (s == NULL) {
if (s == nullptr) {
free_s = 1;
s = ASN1_UTCTIME_new();
if (s == NULL) {
return NULL;
if (s == nullptr) {
return nullptr;
}
}
@@ -97,7 +123,7 @@ ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
if (free_s) {
ASN1_UTCTIME_free(s);
}
return NULL;
return nullptr;
}
s->type = V_ASN1_GENERALIZEDTIME;
return s;
+20 -14
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -14,9 +19,9 @@
#include <CNIOBoringSSL_mem.h>
int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x) {
int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, const void *x) {
BIO *b = BIO_new_fp(out, BIO_NOCLOSE);
if (b == NULL) {
if (b == nullptr) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_BUF_LIB);
return 0;
}
@@ -25,10 +30,11 @@ int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x) {
return ret;
}
int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, void *x) {
unsigned char *b = NULL;
int n = ASN1_item_i2d(reinterpret_cast<ASN1_VALUE *>(x), &b, it);
if (b == NULL) {
int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, const void *x) {
unsigned char *b = nullptr;
int n = ASN1_item_i2d(reinterpret_cast<ASN1_VALUE *>(const_cast<void *>(x)),
&b, it);
if (b == nullptr) {
return 0;
}
+107 -59
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -16,10 +21,14 @@
#include <CNIOBoringSSL_bytestring.h>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_span.h>
#include "../internal.h"
#include "internal.h"
using namespace bssl;
ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x) {
return ASN1_STRING_dup(x);
}
@@ -33,8 +42,8 @@ int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y) {
int ret = ASN1_STRING_cmp(x, y);
if (neg) {
// This could be |-ret|, but |ASN1_STRING_cmp| is not forbidden from
// returning |INT_MIN|.
// This could be `-ret`, but `ASN1_STRING_cmp` is not forbidden from
// returning `INT_MIN`.
if (ret < 0) {
return 1;
} else if (ret > 0) {
@@ -47,7 +56,7 @@ int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y) {
return ret;
}
// negate_twos_complement negates |len| bytes from |buf| in-place, interpreted
// negate_twos_complement negates `len` bytes from `buf` in-place, interpreted
// as a signed, big-endian two's complement value.
static void negate_twos_complement(uint8_t *buf, size_t len) {
uint8_t borrow = 0;
@@ -67,12 +76,27 @@ static int is_all_zeros(const uint8_t *in, size_t len) {
return 1;
}
int bssl::asn1_marshal_integer(CBB *out, const ASN1_INTEGER *in,
CBS_ASN1_TAG tag) {
int len = i2c_ASN1_INTEGER(in, nullptr);
if (len <= 0) {
return 0;
}
tag = tag == 0 ? CBS_ASN1_INTEGER : tag;
CBB child;
uint8_t *ptr;
return CBB_add_asn1(out, &child, tag) && //
CBB_add_space(&child, &ptr, static_cast<size_t>(len)) && //
i2c_ASN1_INTEGER(in, &ptr) == len && //
CBB_flush(out);
}
int i2c_ASN1_INTEGER(const ASN1_INTEGER *in, unsigned char **outp) {
if (in == NULL) {
if (in == nullptr) {
return 0;
}
// |ASN1_INTEGER|s should be represented minimally, but it is possible to
// `ASN1_INTEGER`s should be represented minimally, but it is possible to
// construct invalid ones. Skip leading zeros so this does not produce an
// invalid encoding or break invariants.
CBS cbs;
@@ -108,7 +132,7 @@ int i2c_ASN1_INTEGER(const ASN1_INTEGER *in, unsigned char **outp) {
}
int len = (int)(pad + CBS_len(&cbs));
assert(len > 0);
if (outp == NULL) {
if (outp == nullptr) {
return len;
}
@@ -126,35 +150,16 @@ int i2c_ASN1_INTEGER(const ASN1_INTEGER *in, unsigned char **outp) {
return len;
}
ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **out, const unsigned char **inp,
long len) {
// This function can handle lengths up to INT_MAX - 1, but the rest of the
// legacy ASN.1 code mixes integer types, so avoid exposing it to
// ASN1_INTEGERS with larger lengths.
if (len < 0 || len > INT_MAX / 2) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TOO_LONG);
return NULL;
}
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
static int asn1_parse_integer_contents(Span<const uint8_t> in,
ASN1_INTEGER *out) {
CBS cbs = in;
int is_negative;
if (!CBS_is_valid_asn1_integer(&cbs, &is_negative)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_INTEGER);
return NULL;
return 0;
}
ASN1_INTEGER *ret = NULL;
if (out == NULL || *out == NULL) {
ret = ASN1_INTEGER_new();
if (ret == NULL) {
return NULL;
}
} else {
ret = *out;
}
// Convert to |ASN1_INTEGER|'s sign-and-magnitude representation. First,
// Convert to `ASN1_INTEGER`'s sign-and-magnitude representation. First,
// determine the size needed for a minimal result.
if (is_negative) {
// 0xff00...01 through 0xff7f..ff have a two's complement of 0x00ff...ff
@@ -172,33 +177,76 @@ ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **out, const unsigned char **inp,
}
}
if (!ASN1_STRING_set(ret, CBS_data(&cbs), CBS_len(&cbs))) {
goto err;
if (!ASN1_STRING_set(out, CBS_data(&cbs), CBS_len(&cbs))) {
return 0;
}
if (is_negative) {
ret->type = V_ASN1_NEG_INTEGER;
negate_twos_complement(ret->data, ret->length);
out->type = V_ASN1_NEG_INTEGER;
negate_twos_complement(out->data, out->length);
} else {
ret->type = V_ASN1_INTEGER;
out->type = V_ASN1_INTEGER;
}
// The value should be minimally-encoded.
assert(ret->length == 0 || ret->data[0] != 0);
assert(out->length == 0 || out->data[0] != 0);
// Zero is not negative.
assert(!is_negative || ret->length > 0);
assert(!is_negative || out->length > 0);
return 1;
}
int bssl::asn1_parse_integer(CBS *cbs, ASN1_INTEGER *out, CBS_ASN1_TAG tag) {
tag = tag == 0 ? CBS_ASN1_INTEGER : tag;
CBS child;
if (!CBS_get_asn1(cbs, &child, tag)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
return asn1_parse_integer_contents(child, out);
}
int bssl::asn1_parse_enumerated(CBS *cbs, ASN1_ENUMERATED *out,
CBS_ASN1_TAG tag) {
tag = tag == 0 ? CBS_ASN1_ENUMERATED : tag;
if (!asn1_parse_integer(cbs, out, tag)) {
return 0;
}
// Fix the type value.
out->type =
(out->type & V_ASN1_NEG) ? V_ASN1_NEG_ENUMERATED : V_ASN1_ENUMERATED;
return 1;
}
ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **out, const unsigned char **inp,
long len) {
if (len < 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_SHORT);
return nullptr;
}
ASN1_INTEGER *ret = nullptr;
if (out == nullptr || *out == nullptr) {
ret = ASN1_INTEGER_new();
if (ret == nullptr) {
return nullptr;
}
} else {
ret = *out;
}
if (!asn1_parse_integer_contents(Span(*inp, len), ret)) {
if (ret != nullptr && (out == nullptr || *out != ret)) {
ASN1_INTEGER_free(ret);
}
return nullptr;
}
*inp += len;
if (out != NULL) {
if (out != nullptr) {
*out = ret;
}
return ret;
err:
if (ret != NULL && (out == NULL || *out != ret)) {
ASN1_INTEGER_free(ret);
}
return NULL;
}
int ASN1_INTEGER_set_int64(ASN1_INTEGER *a, int64_t v) {
@@ -305,7 +353,7 @@ static int asn1_string_get_int64(int64_t *out, const ASN1_STRING *a, int type) {
}
int64_t i64;
int fits_in_i64;
// Check |v != 0| to handle manually-constructed negative zeros.
// Check `v != 0` to handle manually-constructed negative zeros.
if ((a->type & V_ASN1_NEG) && v != 0) {
i64 = (int64_t)(0u - v);
fits_in_i64 = i64 < 0;
@@ -330,7 +378,7 @@ int ASN1_ENUMERATED_get_int64(int64_t *out, const ASN1_ENUMERATED *a) {
}
static long asn1_string_get_long(const ASN1_STRING *a, int type) {
if (a == NULL) {
if (a == nullptr) {
return 0;
}
@@ -356,13 +404,13 @@ long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a) {
static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai,
int type) {
ASN1_INTEGER *ret;
if (ai == NULL) {
if (ai == nullptr) {
ret = ASN1_STRING_type_new(type);
} else {
ret = ai;
}
int len;
if (ret == NULL) {
if (ret == nullptr) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
}
@@ -374,7 +422,7 @@ static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai,
}
len = BN_num_bytes(bn);
if (!ASN1_STRING_set(ret, NULL, len) ||
if (!ASN1_STRING_set(ret, nullptr, len) ||
!BN_bn2bin_padded(ret->data, len, bn)) {
goto err;
}
@@ -384,7 +432,7 @@ err:
if (ret != ai) {
ASN1_STRING_free(ret);
}
return NULL;
return nullptr;
}
ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai) {
@@ -398,11 +446,11 @@ ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai) {
static BIGNUM *asn1_string_to_bn(const ASN1_STRING *ai, BIGNUM *bn, int type) {
if ((ai->type & ~V_ASN1_NEG) != type) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_INTEGER_TYPE);
return NULL;
return nullptr;
}
BIGNUM *ret;
if ((ret = BN_bin2bn(ai->data, ai->length, bn)) == NULL) {
if ((ret = BN_bin2bn(ai->data, ai->length, bn)) == nullptr) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BN_LIB);
} else if (ai->type & V_ASN1_NEG) {
BN_set_negative(ret, 1);
+20 -12
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -19,6 +24,9 @@
#include "../bytestring/internal.h"
#include "internal.h"
using namespace bssl;
// These functions take a string in UTF8, ASCII or multibyte form and a mask
// of permissible ASN1 string types. It then works out the minimal type
// (using the order Printable < IA5 < T61 < BMP < Universal < UTF8) and
@@ -74,7 +82,7 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in,
return -1;
}
// Check |minsize| and |maxsize| and work out the minimal type, if any.
// Check `minsize` and `maxsize` and work out the minimal type, if any.
CBS cbs;
CBS_init(&cbs, in, len);
size_t utf8_len = 0, nchar = 0;
@@ -179,7 +187,7 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in,
CBB cbb;
CBB_zero(&cbb);
// If both the same type just copy across
uint8_t *data = NULL;
uint8_t *data = nullptr;
size_t data_len = 0;
if (inform == outform) {
if (!ASN1_STRING_set(dest, in, len)) {
@@ -201,7 +209,7 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in,
}
}
if (/* OpenSSL historically NUL-terminated this value with a single byte,
* even for |MBSTRING_BMP| and |MBSTRING_UNIV|. */
* even for `MBSTRING_BMP` and `MBSTRING_UNIV`. */
!CBB_add_u8(&cbb, 0) || //
!CBB_finish(&cbb, &data, &data_len) || //
data_len < 1 || //
@@ -223,7 +231,7 @@ err:
return -1;
}
int asn1_is_printable(uint32_t value) {
int bssl::asn1_is_printable(uint32_t value) {
if (value > 0x7f) {
return 0;
}
+85 -82
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -19,29 +24,34 @@
#include "../bytestring/internal.h"
#include "../internal.h"
#include "../mem_internal.h"
#include "internal.h"
int i2d_ASN1_OBJECT(const ASN1_OBJECT *in, unsigned char **outp) {
if (in == NULL) {
using namespace bssl;
int bssl::asn1_marshal_object(CBB *out, const ASN1_OBJECT *in,
CBS_ASN1_TAG tag) {
if (in == nullptr) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_PASSED_NULL_PARAMETER);
return -1;
return 0;
}
if (in->length <= 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OBJECT);
return -1;
return 0;
}
CBB cbb, child;
if (!CBB_init(&cbb, (size_t)in->length + 2) ||
!CBB_add_asn1(&cbb, &child, CBS_ASN1_OBJECT) ||
!CBB_add_bytes(&child, in->data, in->length)) {
CBB_cleanup(&cbb);
return -1;
}
tag = tag == 0 ? CBS_ASN1_OBJECT : tag;
return CBB_add_asn1_element(out, tag, in->data, in->length);
}
return CBB_finish_i2d(&cbb, outp);
int i2d_ASN1_OBJECT(const ASN1_OBJECT *in, unsigned char **outp) {
return I2DFromCBB(
/*initial_capacity=*/static_cast<size_t>(in->length) + 2, outp,
[&](CBB *cbb) -> bool {
return asn1_marshal_object(cbb, in, /*tag=*/0);
});
}
int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a) {
@@ -58,17 +68,17 @@ static int write_str(BIO *bp, const char *str) {
}
int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a) {
if (a == NULL || a->data == NULL) {
if (a == nullptr || a->data == nullptr) {
return write_str(bp, "NULL");
}
char buf[80], *allocated = NULL;
char buf[80], *allocated = nullptr;
const char *str = buf;
int len = i2t_ASN1_OBJECT(buf, sizeof(buf), a);
if (len > (int)sizeof(buf) - 1) {
// The input was truncated. Allocate a buffer that fits.
allocated = reinterpret_cast<char *>(OPENSSL_malloc(len + 1));
if (allocated == NULL) {
if (allocated == nullptr) {
return -1;
}
len = i2t_ASN1_OBJECT(allocated, len + 1, a);
@@ -85,87 +95,80 @@ int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a) {
ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **out, const unsigned char **inp,
long len) {
if (len < 0) {
return NULL;
}
CBS cbs, child;
CBS_init(&cbs, *inp, (size_t)len);
if (!CBS_get_asn1(&cbs, &child, CBS_ASN1_OBJECT)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return NULL;
}
const uint8_t *contents = CBS_data(&child);
ASN1_OBJECT *ret = c2i_ASN1_OBJECT(out, &contents, CBS_len(&child));
if (ret != NULL) {
// |c2i_ASN1_OBJECT| should have consumed the entire input.
assert(CBS_data(&cbs) == contents);
*inp = CBS_data(&cbs);
}
return ret;
return D2IFromCBS(out, inp, len, [](CBS *cbs) -> ASN1_OBJECT * {
CBS child;
if (!CBS_get_asn1(cbs, &child, CBS_ASN1_OBJECT)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return nullptr;
}
const uint8_t *contents = CBS_data(&child);
return c2i_ASN1_OBJECT(nullptr, &contents, CBS_len(&child));
});
}
ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **out, const unsigned char **inp,
long len) {
if (len < 0) {
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;
}
ASN1_OBJECT *ret = ASN1_OBJECT_create(NID_undef, *inp, (size_t)len,
/*sn=*/NULL, /*ln=*/NULL);
if (ret == NULL) {
return NULL;
}
if (out != NULL) {
ASN1_OBJECT_free(*out);
*out = ret;
}
*inp += len; // All bytes were consumed.
return ret;
return D2IFromCBS(out, inp, len, [](CBS *cbs) -> ASN1_OBJECT * {
if (!CBS_is_valid_asn1_oid(cbs)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING);
return nullptr;
}
ASN1_OBJECT *ret =
ASN1_OBJECT_create(NID_undef, CBS_data(cbs), CBS_len(cbs),
/*sn=*/nullptr, /*ln=*/nullptr);
if (ret != nullptr) {
// `c2i_ASN1_OBJECT` consumes its whole input on success.
BSSL_CHECK(CBS_skip(cbs, CBS_len(cbs)));
}
return ret;
});
}
ASN1_OBJECT *ASN1_OBJECT_new(void) {
ASN1_OBJECT *ret;
ASN1_OBJECT *bssl::asn1_parse_object(CBS *cbs, CBS_ASN1_TAG tag) {
tag = tag == 0 ? CBS_ASN1_OBJECT : tag;
CBS child;
if (!CBS_get_asn1(cbs, &child, tag)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return nullptr;
}
if (!CBS_is_valid_asn1_oid(&child)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING);
return nullptr;
}
return ASN1_OBJECT_create(NID_undef, CBS_data(&child), CBS_len(&child),
/*sn=*/nullptr, /*ln=*/nullptr);
}
ret = (ASN1_OBJECT *)OPENSSL_malloc(sizeof(ASN1_OBJECT));
if (ret == NULL) {
return NULL;
ASN1_OBJECT *bssl::ASN1_OBJECT_new() {
ASN1_OBJECT *ret = New<ASN1_OBJECT>();
if (ret == nullptr) {
return nullptr;
}
ret->length = 0;
ret->data = NULL;
ret->data = nullptr;
ret->nid = 0;
ret->sn = NULL;
ret->ln = NULL;
ret->sn = nullptr;
ret->ln = nullptr;
ret->flags = ASN1_OBJECT_FLAG_DYNAMIC;
return ret;
}
void ASN1_OBJECT_free(ASN1_OBJECT *a) {
if (a == NULL) {
if (a == nullptr) {
return;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) {
OPENSSL_free((void *)a->sn);
OPENSSL_free((void *)a->ln);
a->sn = a->ln = NULL;
OPENSSL_free(const_cast<char *>(a->sn));
OPENSSL_free(const_cast<char *>(a->ln));
a->sn = a->ln = nullptr;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_DATA) {
OPENSSL_free((void *)a->data);
a->data = NULL;
OPENSSL_free(const_cast<uint8_t *>(a->data));
a->data = nullptr;
a->length = 0;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC) {
OPENSSL_free(a);
Delete(a);
}
}
@@ -173,7 +176,7 @@ ASN1_OBJECT *ASN1_OBJECT_create(int nid, const unsigned char *data, size_t len,
const char *sn, const char *ln) {
if (len > INT_MAX) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_LONG);
return NULL;
return nullptr;
}
ASN1_OBJECT o;
+13 -8
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
+51 -50
View File
@@ -1,11 +1,16 @@
/*
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -19,26 +24,29 @@
#include <CNIOBoringSSL_bio.h>
#include <CNIOBoringSSL_bytestring.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_span.h>
#include "../bytestring/internal.h"
#include "../internal.h"
#include "internal.h"
using namespace bssl;
#define ESC_FLAGS \
(ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_QUOTE | ASN1_STRFLGS_ESC_CTRL | \
ASN1_STRFLGS_ESC_MSB)
static int maybe_write(BIO *out, const void *buf, int len) {
// If |out| is NULL, ignore the output but report the length.
return out == NULL || BIO_write(out, buf, len) == len;
// If `out` is NULL, ignore the output but report the length.
return out == nullptr || BIO_write(out, buf, len) == len;
}
static int is_control_character(unsigned char c) { return c < 32 || c == 127; }
static int do_esc_char(uint32_t c, unsigned long flags, char *do_quotes,
BIO *out, int is_first, int is_last) {
// |c| is a |uint32_t| because, depending on |ASN1_STRFLGS_UTF8_CONVERT|,
// `c` is a `uint32_t` because, depending on `ASN1_STRFLGS_UTF8_CONVERT`,
// we may be escaping bytes or Unicode codepoints.
char buf[16]; // Large enough for "\\W01234567".
unsigned char u8 = (unsigned char)c;
@@ -60,7 +68,7 @@ static int do_esc_char(uint32_t c, unsigned long flags, char *do_quotes,
(is_last && (c == ' '))) {
if (flags & ASN1_STRFLGS_ESC_QUOTE) {
// No need to escape, just tell the caller to quote.
if (do_quotes != NULL) {
if (do_quotes != nullptr) {
*do_quotes = 1;
}
return maybe_write(out, &u8, 1) ? 1 : -1;
@@ -128,7 +136,7 @@ static int do_buf(const unsigned char *buf, int buflen, int encoding,
CBB_init_fixed(&utf8_cbb, utf8_buf, sizeof(utf8_buf));
if (!CBB_add_utf8(&utf8_cbb, c)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR);
return 1;
return -1;
}
size_t utf8_len = CBB_len(&utf8_cbb);
for (size_t i = 0; i < utf8_len; i++) {
@@ -150,25 +158,22 @@ static int do_buf(const unsigned char *buf, int buflen, int encoding,
return outlen;
}
// This function hex dumps a buffer of characters
static int do_hex_dump(BIO *out, unsigned char *buf, int buflen) {
static const char hexdig[] = "0123456789ABCDEF";
unsigned char *p, *q;
char hextmp[2];
static int do_hex_dump(BIO *out, Span<const uint8_t> in) {
if (in.size() > INT_MAX / 2) {
return -1;
}
if (out) {
p = buf;
q = buf + buflen;
while (p != q) {
hextmp[0] = hexdig[*p >> 4];
hextmp[1] = hexdig[*p & 0xf];
static const char kHexDigit[] = "0123456789ABCDEF";
for (uint8_t b : in) {
char hextmp[2];
hextmp[0] = kHexDigit[b >> 4];
hextmp[1] = kHexDigit[b & 0xf];
if (!maybe_write(out, hextmp, 2)) {
return -1;
}
p++;
}
}
return buflen << 1;
return static_cast<int>(in.size() * 2);
}
// "dump" a string. This is done when the type is unknown, or the flags
@@ -182,37 +187,33 @@ static int do_dump(unsigned long flags, BIO *out, const ASN1_STRING *str) {
// If we don't dump DER encoding just dump content octets
if (!(flags & ASN1_STRFLGS_DUMP_DER)) {
int outlen = do_hex_dump(out, str->data, str->length);
int outlen = do_hex_dump(out, Span(str->data, str->length));
if (outlen < 0) {
return -1;
}
return outlen + 1;
}
// Placing the ASN1_STRING in a temporary ASN1_TYPE allows the DER encoding
// to readily obtained.
ASN1_TYPE t;
OPENSSL_memset(&t, 0, sizeof(ASN1_TYPE));
asn1_type_set0_string(&t, (ASN1_STRING *)str);
unsigned char *der_buf = NULL;
int der_len = i2d_ASN1_TYPE(&t, &der_buf);
if (der_len < 0) {
ScopedCBB cbb;
// Roughly estimate the encoded size with `str->length` to reduce unnecessary
// reallocations. (Tag, length, miscellaneous type-dependent overhead.)
if (!CBB_init(cbb.get(), 4 + str->length) ||
!asn1_marshal_any_string(cbb.get(), str)) {
return -1;
}
int outlen = do_hex_dump(out, der_buf, der_len);
OPENSSL_free(der_buf);
int outlen = do_hex_dump(out, CBBAsSpan(cbb.get()));
if (outlen < 0) {
return -1;
}
return outlen + 1;
}
// string_type_to_encoding returns the |MBSTRING_*| constant for the encoding
// used by the |ASN1_STRING| type |type|, or -1 if |tag| is not a string
// string_type_to_encoding returns the `MBSTRING_*` constant for the encoding
// used by the `ASN1_STRING` type `type`, or -1 if `tag` is not a string
// type.
static int string_type_to_encoding(int type) {
// This function is sometimes passed ASN.1 universal types and sometimes
// passed |ASN1_STRING| type values
// passed `ASN1_STRING` type values
switch (type) {
case V_ASN1_UTF8STRING:
return MBSTRING_UTF8;
@@ -223,7 +224,7 @@ static int string_type_to_encoding(int type) {
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_ISO64STRING:
// |MBSTRING_ASC| refers to Latin-1, not ASCII.
// `MBSTRING_ASC` refers to Latin-1, not ASCII.
return MBSTRING_ASC;
case V_ASN1_UNIVERSALSTRING:
return MBSTRING_UNIV;
@@ -250,7 +251,7 @@ int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str,
outlen++;
}
// Decide what to do with |str|, either dump the contents or display it.
// Decide what to do with `str`, either dump the contents or display it.
int encoding;
if (flags & ASN1_STRFLGS_DUMP_ALL) {
// Dump everything.
@@ -276,7 +277,7 @@ int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str,
// Measure the length.
char quotes = 0;
int len = do_buf(str->data, str->length, encoding, flags, &quotes, NULL);
int len = do_buf(str->data, str->length, encoding, flags, &quotes, nullptr);
if (len < 0) {
return -1;
}
@@ -290,7 +291,7 @@ int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str,
// Encode the value.
if ((quotes && !maybe_write(out, "\"", 1)) ||
do_buf(str->data, str->length, encoding, flags, NULL, out) < 0 ||
do_buf(str->data, str->length, encoding, flags, nullptr, out) < 0 ||
(quotes && !maybe_write(out, "\"", 1))) {
return -1;
}
@@ -299,12 +300,12 @@ int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str,
int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str,
unsigned long flags) {
BIO *bio = NULL;
if (fp != NULL) {
// If |fp| is NULL, this function returns the number of bytes without
BIO *bio = nullptr;
if (fp != nullptr) {
// If `fp` is NULL, this function returns the number of bytes without
// writing.
bio = BIO_new_fp(fp, BIO_NOCLOSE);
if (bio == NULL) {
if (bio == nullptr) {
return -1;
}
}
@@ -323,7 +324,7 @@ int ASN1_STRING_to_UTF8(unsigned char **out, const ASN1_STRING *in) {
return -1;
}
ASN1_STRING stmp, *str = &stmp;
stmp.data = NULL;
stmp.data = nullptr;
stmp.length = 0;
stmp.flags = 0;
int ret =
@@ -340,7 +341,7 @@ int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v) {
char buf[80];
const char *p;
if (v == NULL) {
if (v == nullptr) {
return 0;
}
n = 0;
+54 -47
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -13,23 +18,32 @@
#include <stdlib.h>
#include <string.h>
#include <iterator>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_obj.h>
#include "../internal.h"
#include "../lhash/internal.h"
#include "../mem_internal.h"
#include "internal.h"
using namespace bssl;
BSSL_NAMESPACE_BEGIN
DEFINE_LHASH_OF(ASN1_STRING_TABLE)
static LHASH_OF(ASN1_STRING_TABLE) *string_tables = NULL;
static CRYPTO_MUTEX string_tables_lock = CRYPTO_MUTEX_INIT;
BSSL_NAMESPACE_END
static LHASH_OF(ASN1_STRING_TABLE) *string_tables = nullptr;
static StaticMutex string_tables_lock;
void ASN1_STRING_set_default_mask(unsigned long mask) {}
unsigned long ASN1_STRING_get_default_mask(void) { return B_ASN1_UTF8STRING; }
unsigned long ASN1_STRING_get_default_mask() { return B_ASN1_UTF8STRING; }
int ASN1_STRING_set_default_mask_asc(const char *p) { return 1; }
@@ -41,13 +55,13 @@ static const ASN1_STRING_TABLE *asn1_string_table_get(int nid);
ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const unsigned char *in,
ossl_ssize_t len, int inform, int nid) {
ASN1_STRING *str = NULL;
ASN1_STRING *str = nullptr;
int ret;
if (!out) {
out = &str;
}
const ASN1_STRING_TABLE *tbl = asn1_string_table_get(nid);
if (tbl != NULL) {
if (tbl != nullptr) {
unsigned long mask = tbl->mask;
if (!(tbl->flags & STABLE_NO_MASK)) {
mask &= B_ASN1_UTF8STRING;
@@ -58,7 +72,7 @@ ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const unsigned char *in,
ret = ASN1_mbstring_copy(out, in, len, inform, B_ASN1_UTF8STRING);
}
if (ret <= 0) {
return NULL;
return nullptr;
}
return *out;
}
@@ -124,19 +138,19 @@ static const ASN1_STRING_TABLE *asn1_string_table_get(int nid) {
ASN1_STRING_TABLE key;
key.nid = nid;
const ASN1_STRING_TABLE *tbl = reinterpret_cast<ASN1_STRING_TABLE *>(
bsearch(&key, tbl_standard, OPENSSL_ARRAY_SIZE(tbl_standard),
bsearch(&key, tbl_standard, std::size(tbl_standard),
sizeof(ASN1_STRING_TABLE), table_cmp_void));
if (tbl != NULL) {
if (tbl != nullptr) {
return tbl;
}
CRYPTO_MUTEX_lock_read(&string_tables_lock);
if (string_tables != NULL) {
string_tables_lock.LockRead();
if (string_tables != nullptr) {
tbl = lh_ASN1_STRING_TABLE_retrieve(string_tables, &key);
}
CRYPTO_MUTEX_unlock_read(&string_tables_lock);
// Note returning |tbl| without the lock is only safe because
// |ASN1_STRING_TABLE_add| cannot modify or delete existing entries. If we
string_tables_lock.UnlockRead();
// Note returning `tbl` without the lock is only safe because
// `ASN1_STRING_TABLE_add` cannot modify or delete existing entries. If we
// wish to support that, this function must copy the result under a lock.
return tbl;
}
@@ -144,35 +158,32 @@ static const ASN1_STRING_TABLE *asn1_string_table_get(int nid) {
int ASN1_STRING_TABLE_add(int nid, long minsize, long maxsize,
unsigned long mask, unsigned long flags) {
// Existing entries cannot be overwritten.
if (asn1_string_table_get(nid) != NULL) {
if (asn1_string_table_get(nid) != nullptr) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
int ret = 0;
CRYPTO_MUTEX_lock_write(&string_tables_lock);
ASN1_STRING_TABLE *tbl = NULL;
if (string_tables == NULL) {
MutexWriteLock lock(&string_tables_lock);
ASN1_STRING_TABLE *tbl = nullptr;
if (string_tables == nullptr) {
string_tables = lh_ASN1_STRING_TABLE_new(table_hash, table_cmp);
if (string_tables == NULL) {
goto err;
if (string_tables == nullptr) {
return 0;
}
} else {
// Check again for an existing entry. One may have been added while
// unlocked.
ASN1_STRING_TABLE key;
key.nid = nid;
if (lh_ASN1_STRING_TABLE_retrieve(string_tables, &key) != NULL) {
if (lh_ASN1_STRING_TABLE_retrieve(string_tables, &key) != nullptr) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
goto err;
return 0;
}
}
tbl = reinterpret_cast<ASN1_STRING_TABLE *>(
OPENSSL_malloc(sizeof(ASN1_STRING_TABLE)));
if (tbl == NULL) {
goto err;
tbl = New<ASN1_STRING_TABLE>();
if (tbl == nullptr) {
return 0;
}
tbl->nid = nid;
tbl->flags = flags;
@@ -181,21 +192,17 @@ int ASN1_STRING_TABLE_add(int nid, long minsize, long maxsize,
tbl->mask = mask;
ASN1_STRING_TABLE *old_tbl;
if (!lh_ASN1_STRING_TABLE_insert(string_tables, &old_tbl, tbl)) {
OPENSSL_free(tbl);
goto err;
Delete(tbl);
return 0;
}
assert(old_tbl == NULL);
ret = 1;
err:
CRYPTO_MUTEX_unlock_write(&string_tables_lock);
return ret;
assert(old_tbl == nullptr);
return 1;
}
void ASN1_STRING_TABLE_cleanup(void) {}
void ASN1_STRING_TABLE_cleanup() {}
void asn1_get_string_table_for_testing(const ASN1_STRING_TABLE **out_ptr,
size_t *out_len) {
void bssl::asn1_get_string_table_for_testing(const ASN1_STRING_TABLE **out_ptr,
size_t *out_len) {
*out_ptr = tbl_standard;
*out_len = OPENSSL_ARRAY_SIZE(tbl_standard);
*out_len = std::size(tbl_standard);
}
+72 -43
View File
@@ -1,15 +1,22 @@
/*
* Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
#include <CNIOBoringSSL_posix_time.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
@@ -20,12 +27,19 @@
#include "internal.h"
using namespace bssl;
// This is an implementation of the ASN1 Time structure which is: Time ::=
// CHOICE { utcTime UTCTime, generalTime GeneralizedTime } written by Steve
// Henson.
BSSL_NAMESPACE_BEGIN
IMPLEMENT_ASN1_MSTRING(ASN1_TIME, B_ASN1_TIME)
BSSL_NAMESPACE_END
IMPLEMENT_ASN1_FUNCTIONS_const(ASN1_TIME)
ASN1_TIME *ASN1_TIME_set_posix(ASN1_TIME *s, int64_t posix_time) {
@@ -46,11 +60,11 @@ ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, int64_t posix_time, int offset_day,
if (!OPENSSL_posix_to_tm(posix_time, &tm)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ERROR_GETTING_TIME);
return NULL;
return nullptr;
}
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(&tm, offset_day, offset_sec)) {
return NULL;
return nullptr;
}
}
if (fits_in_utc_time(&tm)) {
@@ -72,14 +86,17 @@ int ASN1_TIME_check(const ASN1_TIME *t) {
ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *in,
ASN1_GENERALIZEDTIME **out) {
if (!ASN1_TIME_check(in)) {
return NULL;
return nullptr;
}
ASN1_GENERALIZEDTIME *ret = NULL;
UniquePtr<ASN1_GENERALIZEDTIME> tmp;
ASN1_GENERALIZEDTIME *ret = nullptr;
if (!out || !*out) {
if (!(ret = ASN1_GENERALIZEDTIME_new())) {
goto err;
tmp.reset(ASN1_GENERALIZEDTIME_new());
if (tmp == nullptr) {
return nullptr;
}
ret = tmp.get();
} else {
ret = *out;
}
@@ -87,40 +104,35 @@ ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *in,
// If already GeneralizedTime just copy across
if (in->type == V_ASN1_GENERALIZEDTIME) {
if (!ASN1_STRING_set(ret, in->data, in->length)) {
goto err;
return nullptr;
}
goto done;
}
// Grow the string to accomodate the two-digit century.
if (!ASN1_STRING_set(ret, NULL, in->length + 2)) {
goto err;
}
{
char *const out_str = (char *)ret->data;
// |ASN1_STRING_set| also allocates an additional byte for a trailing NUL.
const size_t out_str_capacity = in->length + 2 + 1;
// Work out the century and prepend
} else {
assert(in->type == V_ASN1_UTCTIME);
// `ASN1_TIME_check` implies a bound on the string's lengths. In particular,
// the longest possible UTCTime is "YYMMDDHHMMSS+HHMM", with the (invalid)
// timezone offsets.
static constexpr size_t kMaxUTCTimeLength = 17;
BSSL_CHECK(in->length > 0 &&
static_cast<size_t>(in->length) <= kMaxUTCTimeLength);
char buf[2 /* century */ + kMaxUTCTimeLength + 1 /* NUL */];
// Work out the century and prepend.
if (in->data[0] >= '5') {
OPENSSL_strlcpy(out_str, "19", out_str_capacity);
snprintf(buf, sizeof(buf), "19%.*s", in->length,
reinterpret_cast<const char *>(in->data));
} else {
OPENSSL_strlcpy(out_str, "20", out_str_capacity);
snprintf(buf, sizeof(buf), "20%.*s", in->length,
reinterpret_cast<const char *>(in->data));
}
if (!ASN1_STRING_set(ret, buf, -1 /* use strlen */)) {
return nullptr;
}
OPENSSL_strlcat(out_str, (const char *)in->data, out_str_capacity);
}
done:
if (out != NULL && *out == NULL) {
if (out != nullptr && *out == nullptr) {
*out = ret;
}
tmp.release(); // Ownership passed to caller.
return ret;
err:
if (out == NULL || *out != ret) {
ASN1_GENERALIZEDTIME_free(ret);
}
return NULL;
}
int ASN1_TIME_set_string(ASN1_TIME *s, const char *str) {
@@ -133,7 +145,7 @@ int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str) {
CBS_init(&cbs, (const uint8_t *)str, strlen(str));
int type;
struct tm tm;
if (CBS_parse_utc_time(&cbs, /*out_tm=*/NULL,
if (CBS_parse_utc_time(&cbs, /*out_tm=*/nullptr,
/*allow_timezone_offset=*/0)) {
type = V_ASN1_UTCTIME;
} else if (CBS_parse_generalized_time(&cbs, &tm,
@@ -147,7 +159,7 @@ int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str) {
return 0;
}
if (s != NULL) {
if (s != nullptr) {
if (!ASN1_STRING_set(s, CBS_data(&cbs), CBS_len(&cbs))) {
return 0;
}
@@ -158,8 +170,8 @@ int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str) {
static int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *t,
int allow_timezone_offset) {
if (t == NULL) {
if (OPENSSL_posix_to_tm(time(NULL), tm)) {
if (t == nullptr) {
if (OPENSSL_posix_to_tm(time(nullptr), tm)) {
return 1;
}
return 0;
@@ -217,3 +229,20 @@ int ASN1_TIME_to_posix(const ASN1_TIME *t, int64_t *out_time) {
}
return OPENSSL_tm_to_posix(&tm, out_time);
}
int bssl::asn1_parse_time(CBS *cbs, ASN1_TIME *out,
int allow_utc_timezone_offset) {
if (CBS_peek_asn1_tag(cbs, CBS_ASN1_UTCTIME)) {
return asn1_parse_utc_time(cbs, out, /*tag=*/0, allow_utc_timezone_offset);
}
return asn1_parse_generalized_time(cbs, out, /*tag=*/0);
}
int bssl::asn1_marshal_time(CBB *cbb, const ASN1_TIME *in) {
if (in->type != V_ASN1_UTCTIME && in->type != V_ASN1_GENERALIZEDTIME) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE);
return 0;
}
return asn1_marshal_octet_string(cbb, in,
static_cast<CBS_ASN1_TAG>(in->type));
}
+338 -38
View File
@@ -1,41 +1,87 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
#include <assert.h>
#include <CNIOBoringSSL_bytestring.h>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_obj.h>
#include "../bytestring/internal.h"
#include "../internal.h"
#include "internal.h"
using namespace bssl;
ASN1_TYPE *ASN1_TYPE_new() {
ASN1_TYPE *ret = New<ASN1_TYPE>();
if (ret == nullptr) {
return nullptr;
}
OPENSSL_memset(ret, 0, sizeof(ASN1_TYPE));
ret->type = -1;
return ret;
}
static void asn1_type_cleanup(ASN1_TYPE *a) {
switch (a->type) {
case V_ASN1_NULL:
a->value.ptr = nullptr;
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 = nullptr;
break;
default:
ASN1_STRING_free(a->value.asn1_string);
a->value.asn1_string = nullptr;
break;
}
}
void ASN1_TYPE_free(ASN1_TYPE *a) {
if (a != nullptr) {
asn1_type_cleanup(a);
Delete(a);
}
}
int ASN1_TYPE_get(const ASN1_TYPE *a) {
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;
return a->value.object != nullptr ? a->type : 0;
default:
return a->value.asn1_string != NULL ? a->type : 0;
return a->value.asn1_string != nullptr ? a->type : 0;
}
}
const void *asn1_type_value_as_pointer(const ASN1_TYPE *a) {
const void *bssl::asn1_type_value_as_pointer(const ASN1_TYPE *a) {
switch (a->type) {
case V_ASN1_NULL:
return NULL;
return nullptr;
case V_ASN1_BOOLEAN:
return a->value.boolean ? (void *)0xff : NULL;
return a->value.boolean ? (void *)0xff : nullptr;
case V_ASN1_OBJECT:
return a->value.object;
default:
@@ -43,9 +89,9 @@ const void *asn1_type_value_as_pointer(const ASN1_TYPE *a) {
}
}
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|.
void bssl::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;
@@ -53,38 +99,19 @@ void asn1_type_set0_string(ASN1_TYPE *a, ASN1_STRING *str) {
type = V_ASN1_ENUMERATED;
}
// These types are not |ASN1_STRING| types and use a different
// representation when stored in |ASN1_TYPE|.
// These types are not `ASN1_STRING` types and use a different
// representation when stored in `ASN1_TYPE`.
assert(type != V_ASN1_NULL && type != V_ASN1_OBJECT &&
type != V_ASN1_BOOLEAN);
ASN1_TYPE_set(a, type, str);
}
void asn1_type_cleanup(ASN1_TYPE *a) {
switch (a->type) {
case V_ASN1_NULL:
a->value.ptr = NULL;
break;
case V_ASN1_BOOLEAN:
a->value.boolean = ASN1_BOOLEAN_NONE;
break;
case V_ASN1_OBJECT:
ASN1_OBJECT_free(a->value.object);
a->value.object = NULL;
break;
default:
ASN1_STRING_free(a->value.asn1_string);
a->value.asn1_string = NULL;
break;
}
}
void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value) {
asn1_type_cleanup(a);
a->type = type;
switch (type) {
case V_ASN1_NULL:
a->value.ptr = NULL;
a->value.ptr = nullptr;
break;
case V_ASN1_BOOLEAN:
a->value.boolean = value ? ASN1_BOOLEAN_TRUE : ASN1_BOOLEAN_FALSE;
@@ -165,3 +192,276 @@ int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) {
return result;
}
int bssl::asn1_parse_any(CBS *cbs, ASN1_TYPE *out) {
CBS_ASN1_TAG tag;
CBS elem;
size_t header_len;
if (!CBS_get_any_asn1_element(cbs, &elem, &tag, &header_len)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
// Handle the non-string types.
if (tag == CBS_ASN1_OBJECT) {
UniquePtr<ASN1_OBJECT> obj(asn1_parse_object(&elem, /*tag=*/0));
if (obj == nullptr) {
return 0;
}
ASN1_TYPE_set(out, V_ASN1_OBJECT, obj.release());
return 1;
}
if (tag == CBS_ASN1_NULL) {
if (CBS_len(&elem) != header_len) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
ASN1_TYPE_set(out, V_ASN1_NULL, nullptr);
return 1;
}
if (tag == CBS_ASN1_BOOLEAN) {
int b;
if (!CBS_get_asn1_bool(&elem, &b)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
// V_ASN1_BOOLEAN will interpret the pointer as null for false and any
// arbitrary non-null pointer for true.
ASN1_TYPE_set(out, V_ASN1_BOOLEAN, b ? out : nullptr);
return 1;
}
// All other cases are handled identically to the string-based ANY parser.
UniquePtr<ASN1_STRING> str(ASN1_STRING_new());
if (str == nullptr || !asn1_parse_any_as_string(&elem, str.get())) {
return 0;
}
asn1_type_set0_string(out, str.release());
return 1;
}
int bssl::asn1_parse_any_as_string(CBS *cbs, ASN1_STRING *out) {
CBS_ASN1_TAG tag;
CBS elem;
size_t header_len;
if (!CBS_get_any_asn1_element(cbs, &elem, &tag, &header_len)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
// Reject unexpectedly constructed or primitive universal types, rather than
// encoding them as an opaque `V_ASN1_OTHER`. As of X.680 (02/2021), tag
// numbers 0-36 have been allocated, except 15. Of these, only 8 (EXTERNAL),
// 11 (EMBEDDED PDV), 16 (SEQUENCE), 17 (SET), and 29 (CHARACTER STRING) are
// constructed.
const CBS_ASN1_TAG tag_class = (tag & CBS_ASN1_CLASS_MASK);
const CBS_ASN1_TAG number = tag & CBS_ASN1_TAG_NUMBER_MASK;
if (tag_class == CBS_ASN1_UNIVERSAL && number <= 36 && number != 15) {
const bool is_constructed = (tag & CBS_ASN1_CONSTRUCTED) != 0;
if (number == V_ASN1_EXTERNAL || number == 11 /* EMBEDDED PDV */ ||
number == V_ASN1_SEQUENCE || number == V_ASN1_SET ||
number == 29 /* CHARACTER STRING*/) {
if (!is_constructed) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_CONSTRUCTED);
return 0;
}
} else {
if (is_constructed) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE);
return 0;
}
}
}
// Historically, parsing high universal tag numbers made OpenSSL's
// `ASN1_STRING` representation ambiguous. We've since fixed this with
// `V_ASN1_OTHER` but, for now, continue to enforce the limit.
if (tag_class == CBS_ASN1_UNIVERSAL && number > V_ASN1_MAX_UNIVERSAL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
// These types are just parsed as `V_ASN1_OTHER` here. Check the contents
// before the generic `V_ASN1_OTHER` path.
CBS body = elem;
BSSL_CHECK(CBS_skip(&body, header_len));
switch (tag) {
case CBS_ASN1_OBJECT:
if (!CBS_is_valid_asn1_oid(&body)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING);
return 0;
}
break;
case CBS_ASN1_NULL:
if (CBS_len(&body) != 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NULL_IS_WRONG_LENGTH);
return 0;
}
break;
case CBS_ASN1_BOOLEAN: {
uint8_t v;
if (!CBS_get_u8(&body, &v) || CBS_len(&body) != 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
return 0;
}
if (v != 0 && v != 0xff) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
break;
}
}
switch (tag) {
case CBS_ASN1_INTEGER:
return asn1_parse_integer(&elem, out, tag);
case CBS_ASN1_ENUMERATED:
return asn1_parse_enumerated(&elem, out, tag);
case CBS_ASN1_BITSTRING:
return asn1_parse_bit_string(&elem, out, tag);
case CBS_ASN1_UNIVERSALSTRING:
return asn1_parse_universal_string(&elem, out, tag);
case CBS_ASN1_BMPSTRING:
return asn1_parse_bmp_string(&elem, out, tag);
case CBS_ASN1_UTF8STRING:
return asn1_parse_utf8_string(&elem, out, tag);
case CBS_ASN1_UTCTIME:
// TODO(crbug.com/42290221): Reject timezone offsets here. We have no
// known cases where UTCTime inside ANY needs accept invalid timezones.
return asn1_parse_utc_time(&elem, out, tag, /*allow_timezone_offset=*/1);
case CBS_ASN1_GENERALIZEDTIME:
return asn1_parse_generalized_time(&elem, out, tag);
case CBS_ASN1_OCTETSTRING:
return asn1_parse_octet_string(&elem, out, tag);
case CBS_ASN1_T61STRING:
return asn1_parse_t61_string(&elem, out, tag);
case CBS_ASN1_IA5STRING:
case CBS_ASN1_NUMERICSTRING:
case CBS_ASN1_PRINTABLESTRING:
case CBS_ASN1_VIDEOTEXSTRING:
case CBS_ASN1_GRAPHICSTRING:
case CBS_ASN1_VISIBLESTRING:
case CBS_ASN1_GENERALSTRING:
// |CBS_ASN1_*| and |V_ASN1_*| constants match for universal types.
static_assert(CBS_ASN1_IA5STRING == V_ASN1_IA5STRING);
// TODO(crbug.com/42290290): Enforce the encoding of these string types.
return asn1_parse_string_unchecked(&elem, out, static_cast<int>(tag),
tag);
default:
// All unrecognized types, or types that cannot be represented as
// `ASN1_STRING`, are represented as the whole element.
if (!ASN1_STRING_set(out, CBS_data(&elem), CBS_len(&elem))) {
return 0;
}
if (tag == CBS_ASN1_SEQUENCE) {
out->type = V_ASN1_SEQUENCE;
} else if (tag == CBS_ASN1_SET) {
out->type = V_ASN1_SET;
} else {
out->type = V_ASN1_OTHER;
}
return 1;
}
}
static int asn1_marshal_string_with_type(CBB *out, const ASN1_STRING *in,
int type);
int bssl::asn1_marshal_any(CBB *out, const ASN1_TYPE *in) {
switch (in->type) {
case V_ASN1_OBJECT:
return asn1_marshal_object(out, in->value.object, /*tag=*/0);
case V_ASN1_NULL:
return CBB_add_asn1_element(out, CBS_ASN1_NULL, nullptr, 0);
case V_ASN1_BOOLEAN:
return CBB_add_asn1_bool(out, in->value.boolean != ASN1_BOOLEAN_FALSE);
case V_ASN1_INTEGER:
case V_ASN1_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_OTHER:
// If `in->type` and the underlying `ASN1_STRING` type don't match, use
// `in->type`. See b/446993031.
return asn1_marshal_string_with_type(out, in->value.asn1_string,
in->type);
default:
// `ASN1_TYPE`s can have type -1 when default-constructed.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE);
return 0;
}
}
static int asn1_marshal_string_with_type(CBB *out, const ASN1_STRING *in,
int type) {
switch (type) {
case V_ASN1_INTEGER:
case V_ASN1_NEG_INTEGER:
return asn1_marshal_integer(out, in, CBS_ASN1_INTEGER);
case V_ASN1_ENUMERATED:
case V_ASN1_NEG_ENUMERATED:
return asn1_marshal_integer(out, in, CBS_ASN1_ENUMERATED);
case V_ASN1_BIT_STRING:
return asn1_marshal_bit_string(out, in, /*tag=*/0);
case V_ASN1_OCTET_STRING:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
return asn1_marshal_octet_string(out, in,
static_cast<CBS_ASN1_TAG>(type));
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_OTHER:
// These three types store the whole TLV as contents.
return CBB_add_bytes(out, ASN1_STRING_get0_data(in),
ASN1_STRING_length(in));
default:
// `ASN1_TYPE`s can have type -1 when default-constructed.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE);
return 0;
}
}
int bssl::asn1_marshal_any_string(CBB *out, const ASN1_STRING *in) {
return asn1_marshal_string_with_type(out, in, in->type);
}
ASN1_TYPE *d2i_ASN1_TYPE(ASN1_TYPE **out, const uint8_t **inp, long len) {
return D2IFromCBS(out, inp, len, [](CBS *cbs) -> UniquePtr<ASN1_TYPE> {
UniquePtr<ASN1_TYPE> ret(ASN1_TYPE_new());
if (ret == nullptr || !asn1_parse_any(cbs, ret.get())) {
return nullptr;
}
return ret;
});
}
int i2d_ASN1_TYPE(const ASN1_TYPE *in, uint8_t **outp) {
return I2DFromCBB(/*initial_capacity=*/16, outp, [&](CBB *cbb) -> bool {
return asn1_marshal_any(cbb, in);
});
}
+45 -21
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
#include <CNIOBoringSSL_bytestring.h>
@@ -19,8 +24,11 @@
#include "internal.h"
int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d,
int allow_timezone_offset) {
using namespace bssl;
int bssl::asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d,
int allow_timezone_offset) {
if (d->type != V_ASN1_UTCTIME) {
return 0;
}
@@ -32,8 +40,24 @@ int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d,
return 1;
}
int bssl::asn1_parse_utc_time(CBS *cbs, ASN1_UTCTIME *out, CBS_ASN1_TAG tag,
int allow_timezone_offset) {
tag = tag == 0 ? CBS_ASN1_UTCTIME : tag;
CBS child;
if (!CBS_get_asn1(cbs, &child, tag) ||
!CBS_parse_utc_time(&child, nullptr, allow_timezone_offset)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
if (!ASN1_STRING_set(out, CBS_data(&child), CBS_len(&child))) {
return 0;
}
out->type = V_ASN1_UTCTIME;
return 1;
}
int ASN1_UTCTIME_check(const ASN1_UTCTIME *d) {
return asn1_utctime_to_tm(NULL, d, /*allow_timezone_offset=*/1);
return asn1_utctime_to_tm(nullptr, d, /*allow_timezone_offset=*/1);
}
int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str) {
@@ -43,11 +67,11 @@ int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str) {
size_t len = strlen(str);
CBS cbs;
CBS_init(&cbs, (const uint8_t *)str, len);
if (!CBS_parse_utc_time(&cbs, /*out_tm=*/NULL,
if (!CBS_parse_utc_time(&cbs, /*out_tm=*/nullptr,
/*allow_timezone_offset=*/0)) {
return 0;
}
if (s != NULL) {
if (s != nullptr) {
if (!ASN1_STRING_set(s, str, len)) {
return 0;
}
@@ -64,32 +88,32 @@ ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, int64_t posix_time,
int offset_day, long offset_sec) {
struct tm data;
if (!OPENSSL_posix_to_tm(posix_time, &data)) {
return NULL;
return nullptr;
}
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(&data, offset_day, offset_sec)) {
return NULL;
return nullptr;
}
}
if (data.tm_year < 50 || data.tm_year >= 150) {
return NULL;
return nullptr;
}
char buf[14];
int ret = snprintf(buf, sizeof(buf), "%02d%02d%02d%02d%02d%02dZ",
data.tm_year % 100, data.tm_mon + 1, data.tm_mday,
data.tm_hour, data.tm_min, data.tm_sec);
// |snprintf| must write exactly 15 bytes (plus the NUL) to the buffer.
// `snprintf` must write exactly 15 bytes (plus the NUL) to the buffer.
BSSL_CHECK(ret == static_cast<int>(sizeof(buf) - 1));
int free_s = 0;
if (s == NULL) {
if (s == nullptr) {
free_s = 1;
s = ASN1_UTCTIME_new();
if (s == NULL) {
return NULL;
if (s == nullptr) {
return nullptr;
}
}
@@ -97,7 +121,7 @@ ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, int64_t posix_time,
if (free_s) {
ASN1_UTCTIME_free(s);
}
return NULL;
return nullptr;
}
s->type = V_ASN1_UTCTIME;
return s;
+142 -39
View File
@@ -1,14 +1,20 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
#include <assert.h>
#include <limits.h>
#include <string.h>
@@ -17,9 +23,12 @@
#include <CNIOBoringSSL_mem.h>
#include "../internal.h"
#include "../mem_internal.h"
#include "internal.h"
using namespace bssl;
// Cross-module errors from crypto/x509/i2d_pr.c.
OPENSSL_DECLARE_ERROR_REASON(ASN1, UNSUPPORTED_PUBLIC_KEY_TYPE)
@@ -55,13 +64,13 @@ 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
// 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
// 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.
// 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);
@@ -102,7 +111,7 @@ int ASN1_get_object(const unsigned char **inp, long *out_len, int *out_tag,
return constructed;
}
// class 0 is constructed constructed == 2 for indefinite length constructed
// class 0 is constructed, constructed == 2 for indefinite length constructed
void ASN1_put_object(unsigned char **pp, int constructed, int length, int tag,
int xclass) {
unsigned char *p = *pp;
@@ -196,9 +205,12 @@ int ASN1_object_size(int constructed, int length, int tag) {
}
int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str) {
if (str == NULL) {
if (str == nullptr) {
return 0;
}
if (dst == str) {
return 1;
}
if (!ASN1_STRING_set(dst, str->data, str->length)) {
return 0;
}
@@ -210,15 +222,15 @@ int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str) {
ASN1_STRING *ASN1_STRING_dup(const ASN1_STRING *str) {
ASN1_STRING *ret;
if (!str) {
return NULL;
return nullptr;
}
ret = ASN1_STRING_new();
if (!ret) {
return NULL;
return nullptr;
}
if (!ASN1_STRING_copy(ret, str)) {
ASN1_STRING_free(ret);
return NULL;
return nullptr;
}
return ret;
}
@@ -227,7 +239,7 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, ossl_ssize_t len_s) {
const char *data = reinterpret_cast<const char *>(_data);
size_t len;
if (len_s < 0) {
if (data == NULL) {
if (data == nullptr) {
return 0;
}
len = strlen(data);
@@ -241,24 +253,25 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, ossl_ssize_t len_s) {
return 0;
}
if (str->length <= (int)len || str->data == NULL) {
if (str->length <= (int)len || str->data == nullptr) {
unsigned char *c = str->data;
if (c == NULL) {
if (c == nullptr) {
str->data = reinterpret_cast<uint8_t *>(OPENSSL_malloc(len + 1));
} else {
str->data = reinterpret_cast<uint8_t *>(OPENSSL_realloc(c, len + 1));
}
if (str->data == NULL) {
if (str->data == nullptr) {
str->data = c;
return 0;
}
}
str->length = (int)len;
if (data != NULL) {
str->flags &= ~0x07; // Clear unused bits if this is a BIT STRING.
if (data != nullptr) {
OPENSSL_memcpy(str->data, data, len);
// Historically, OpenSSL would NUL-terminate most (but not all)
// |ASN1_STRING|s, in case anyone accidentally passed |str->data| into a
// `ASN1_STRING`s, in case anyone accidentally passed `str->data` into a
// function expecting a C string. We retain this behavior for compatibility,
// but code must not rely on this. See CVE-2021-3712.
str->data[len] = '\0';
@@ -270,49 +283,56 @@ void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len) {
OPENSSL_free(str->data);
str->data = reinterpret_cast<uint8_t *>(data);
str->length = len;
str->flags &= ~0x07; // Clear unused bits if this is a BIT STRING.
}
ASN1_STRING *ASN1_STRING_new(void) {
ASN1_STRING *ASN1_STRING_new() {
return (ASN1_STRING_type_new(V_ASN1_OCTET_STRING));
}
ASN1_STRING *ASN1_STRING_type_new(int type) {
ASN1_STRING *ret;
ret = (ASN1_STRING *)OPENSSL_malloc(sizeof(ASN1_STRING));
if (ret == NULL) {
return NULL;
ASN1_STRING *ret = New<ASN1_STRING>();
if (ret == nullptr) {
return nullptr;
}
ret->length = 0;
ret->type = type;
ret->data = NULL;
ret->data = nullptr;
ret->flags = 0;
return ret;
}
void bssl::asn1_string_init(ASN1_STRING *str, int type) {
OPENSSL_memset(str, 0, sizeof(ASN1_STRING));
str->type = type;
}
void bssl::asn1_string_cleanup(ASN1_STRING *str) {
OPENSSL_free(str->data);
str->data = nullptr;
}
void ASN1_STRING_free(ASN1_STRING *str) {
if (str == NULL) {
if (str == nullptr) {
return;
}
OPENSSL_free(str->data);
OPENSSL_free(str);
asn1_string_cleanup(str);
Delete(str);
}
int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b) {
// Capture padding bits and implicit truncation in BIT STRINGs.
int a_length = a->length, b_length = b->length;
uint8_t a_padding = 0, b_padding = 0;
if (a->type == V_ASN1_BIT_STRING) {
a_length = asn1_bit_string_length(a, &a_padding);
a_padding = ASN1_BIT_STRING_unused_bits(a);
}
if (b->type == V_ASN1_BIT_STRING) {
b_length = asn1_bit_string_length(b, &b_padding);
b_padding = ASN1_BIT_STRING_unused_bits(b);
}
if (a_length < b_length) {
if (a->length < b->length) {
return -1;
}
if (a_length > b_length) {
if (a->length > b->length) {
return 1;
}
// In a BIT STRING, the number of bits is 8 * length - padding. Invert this
@@ -324,7 +344,7 @@ int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b) {
return 1;
}
int ret = OPENSSL_memcmp(a->data, b->data, a_length);
int ret = OPENSSL_memcmp(a->data, b->data, a->length);
if (ret != 0) {
return ret;
}
@@ -348,3 +368,86 @@ unsigned char *ASN1_STRING_data(ASN1_STRING *str) { return str->data; }
const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *str) {
return str->data;
}
int bssl::asn1_parse_string_unchecked(CBS *cbs, ASN1_STRING *out, int str_type,
CBS_ASN1_TAG tag) {
assert(tag != 0);
CBS child;
if (!CBS_get_asn1(cbs, &child, tag)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
if (!ASN1_STRING_set(out, CBS_data(&child), CBS_len(&child))) {
return 0;
}
out->type = str_type;
return 1;
}
int bssl::asn1_parse_octet_string(CBS *cbs, ASN1_STRING *out,
CBS_ASN1_TAG tag) {
// Nothing to check for OCTET STRING.
tag = tag == 0 ? CBS_ASN1_OCTETSTRING : tag;
return asn1_parse_string_unchecked(cbs, out, V_ASN1_OCTET_STRING, tag);
}
int bssl::asn1_parse_t61_string(CBS *cbs, ASN1_STRING *out, CBS_ASN1_TAG tag) {
// Nothing to check for T61String. We parse it as Latin-1 and all byte strings
// are valid Latin-1.
tag = tag == 0 ? CBS_ASN1_T61STRING : tag;
return asn1_parse_string_unchecked(cbs, out, V_ASN1_T61STRING, tag);
}
int bssl::asn1_marshal_octet_string(CBB *out, const ASN1_STRING *in,
CBS_ASN1_TAG tag) {
tag = tag == 0 ? CBS_ASN1_OCTETSTRING : tag;
return CBB_add_asn1_element(out, tag, ASN1_STRING_get0_data(in),
ASN1_STRING_length(in));
}
static int asn1_parse_character_string(CBS *cbs, ASN1_STRING *out,
CBS_ASN1_TAG tag, int str_type,
int (*get_char)(CBS *cbs, uint32_t *),
int bad_char_err) {
CBS child;
if (!CBS_get_asn1(cbs, &child, tag)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
CBS copy = child;
while (CBS_len(&copy) != 0) {
uint32_t c;
if (!get_char(&copy, &c)) {
OPENSSL_PUT_ERROR(ASN1, bad_char_err);
return 0;
}
}
if (!ASN1_STRING_set(out, CBS_data(&child), CBS_len(&child))) {
return 0;
}
out->type = str_type;
return 1;
}
int bssl::asn1_parse_bmp_string(CBS *cbs, ASN1_BMPSTRING *out,
CBS_ASN1_TAG tag) {
tag = tag == 0 ? CBS_ASN1_BMPSTRING : tag;
return asn1_parse_character_string(cbs, out, tag, V_ASN1_BMPSTRING,
&CBS_get_ucs2_be,
ASN1_R_INVALID_BMPSTRING);
}
int bssl::asn1_parse_universal_string(CBS *cbs, ASN1_UNIVERSALSTRING *out,
CBS_ASN1_TAG tag) {
tag = tag == 0 ? CBS_ASN1_UNIVERSALSTRING : tag;
return asn1_parse_character_string(cbs, out, tag, V_ASN1_UNIVERSALSTRING,
&CBS_get_utf32_be,
ASN1_R_INVALID_UNIVERSALSTRING);
}
int bssl::asn1_parse_utf8_string(CBS *cbs, ASN1_UNIVERSALSTRING *out,
CBS_ASN1_TAG tag) {
tag = tag == 0 ? CBS_ASN1_UTF8STRING : tag;
return asn1_parse_character_string(cbs, out, tag, V_ASN1_UTF8STRING,
&CBS_get_utf8, ASN1_R_INVALID_UTF8STRING);
}
+13 -8
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
+23 -18
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -14,26 +19,26 @@
ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **out) {
uint8_t *new_data = NULL;
uint8_t *new_data = nullptr;
int len = ASN1_item_i2d(reinterpret_cast<ASN1_VALUE *>(obj), &new_data, it);
if (len <= 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ENCODE_ERROR);
return NULL;
return nullptr;
}
ASN1_STRING *ret = NULL;
if (out == NULL || *out == NULL) {
ASN1_STRING *ret = nullptr;
if (out == nullptr || *out == nullptr) {
ret = ASN1_STRING_new();
if (ret == NULL) {
if (ret == nullptr) {
OPENSSL_free(new_data);
return NULL;
return nullptr;
}
} else {
ret = *out;
}
ASN1_STRING_set0(ret, new_data, len);
if (out != NULL) {
if (out != nullptr) {
*out = ret;
}
return ret;
@@ -41,11 +46,11 @@ ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **out) {
void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it) {
const unsigned char *p = oct->data;
void *ret = ASN1_item_d2i(NULL, &p, oct->length, it);
if (ret == NULL || p != oct->data + oct->length) {
void *ret = ASN1_item_d2i(nullptr, &p, oct->length, it);
if (ret == nullptr || p != oct->data + oct->length) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
ASN1_item_free(reinterpret_cast<ASN1_VALUE *>(ret), it);
return NULL;
return nullptr;
}
return ret;
}
+14 -9
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -16,7 +21,7 @@ int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a) {
static const char *h = "0123456789ABCDEF";
char buf[2];
if (a == NULL) {
if (a == nullptr) {
return 0;
}
+14 -9
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -16,7 +21,7 @@ int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type) {
static const char *h = "0123456789ABCDEF";
char buf[2];
if (a == NULL) {
if (a == nullptr) {
return 0;
}
+323 -110
View File
@@ -1,49 +1,56 @@
/*
* Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSSL_HEADER_ASN1_INTERNAL_H
#define OPENSSL_HEADER_ASN1_INTERNAL_H
#ifndef OPENSSL_HEADER_CRYPTO_ASN1_INTERNAL_H
#define OPENSSL_HEADER_CRYPTO_ASN1_INTERNAL_H
#include <time.h>
#include <CNIOBoringSSL_asn1.h>
#include <CNIOBoringSSL_asn1t.h>
#include <CNIOBoringSSL_span.h>
#if defined(__cplusplus)
extern "C" {
#endif
#include "../internal.h"
BSSL_NAMESPACE_BEGIN
// Wrapper functions for time functions.
// OPENSSL_gmtime converts a time_t value in |time| which must be in the range
// of year 0000 to 9999 to a broken out time value in |tm|. On success |tm| is
// OPENSSL_gmtime converts a time_t value in `time` which must be in the range
// of year 0000 to 9999 to a broken out time value in `tm`. On success `tm` is
// returned. On failure NULL is returned.
OPENSSL_EXPORT struct tm *OPENSSL_gmtime(const time_t *time, struct tm *result);
// OPENSSL_gmtime_adj returns one on success, and updates |tm| by adding
// |offset_day| days and |offset_sec| seconds. It returns zero on failure. |tm|
// 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,
int64_t offset_sec);
// OPENSSL_gmtime_diff calculates the difference between |from| and |to|. It
// OPENSSL_gmtime_diff calculates the difference between `from` and `to`. It
// returns one, and outputs the difference as a number of days and seconds in
// |*out_days| and |*out_secs| on success. It returns zero on failure. Both
// |from| and |to| must be in the range of year 0000 to 9999 or a failure will
// `*out_days` and `*out_secs` on success. It returns zero on failure. Both
// `from` and `to` must be in the range of year 0000 to 9999 or a failure will
// be returned.
OPENSSL_EXPORT int OPENSSL_gmtime_diff(int *out_days, int *out_secs,
const struct tm *from,
const struct tm *to);
// Internal ASN1 structures and functions: not for application use
// Object identifiers.
// These are used internally in the ASN1_OBJECT to keep track of
// whether the names and data need to be free()ed
@@ -51,10 +58,12 @@ OPENSSL_EXPORT int OPENSSL_gmtime_diff(int *out_days, int *out_secs,
#define ASN1_OBJECT_FLAG_DYNAMIC_STRINGS 0x04 // internal use
#define ASN1_OBJECT_FLAG_DYNAMIC_DATA 0x08 // internal use
// An asn1_object_st (aka |ASN1_OBJECT|) represents an ASN.1 OBJECT IDENTIFIER.
// Note: Mutating an |ASN1_OBJECT| is only permitted when initializing it. The
// library maintains a table of static |ASN1_OBJECT|s, which may be referenced
// by non-const |ASN1_OBJECT| pointers. Code which receives an |ASN1_OBJECT|
BSSL_NAMESPACE_END
// An asn1_object_st (aka `ASN1_OBJECT`) represents an ASN.1 OBJECT IDENTIFIER.
// Note: Mutating an `ASN1_OBJECT` is only permitted when initializing it. The
// library maintains a table of static `ASN1_OBJECT`s, which may be referenced
// by non-const `ASN1_OBJECT` pointers. Code which receives an `ASN1_OBJECT`
// pointer externally must assume it is immutable, even if the pointer is not
// const.
struct asn1_object_st {
@@ -65,66 +74,206 @@ struct asn1_object_st {
int flags; // Should we free this one
};
ASN1_OBJECT *ASN1_OBJECT_new(void);
BSSL_NAMESPACE_BEGIN
// ASN1_ENCODING is used to save the received encoding of an ASN.1 type. This
// avoids problems with invalid encodings that break signatures.
typedef struct ASN1_ENCODING_st {
// enc is the saved DER encoding. Its ownership is determined by |buf|.
uint8_t *enc;
// len is the length of |enc|. If zero, there is no saved encoding.
size_t len;
// buf, if non-NULL, is the |CRYPTO_BUFFER| that |enc| points into. If NULL,
// |enc| must be released with |OPENSSL_free|.
CRYPTO_BUFFER *buf;
} ASN1_ENCODING;
ASN1_OBJECT *ASN1_OBJECT_new();
// asn1_parse_object parses a DER-encoded ASN.1 OBJECT IDENTIFIER from `cbs` and
// write the result to `out`. If `tag` is non-zero, the value is implicitly
// tagged with `tag`. On success, it returns a newly-allocated `ASN1_OBJECT`
// with the result and advances `cbs` past the parsed element.
//
// TODO(crbug.com/boringssl/414361735): This should return a bssl::UniquePtr,
// but cannot until it is made C++ linkage.
ASN1_OBJECT *asn1_parse_object(CBS *cbs, CBS_ASN1_TAG tag);
// asn1_marshal_object marshals `in` as a DER-encoded, ASN.1 OBJECT IDENTIFIER
// and writes the result to `out`. It returns one on success and zero on error.
// If `tag` is non-zero, the tag is replaced with `tag`.
int asn1_marshal_object(CBB *out, const ASN1_OBJECT *in, CBS_ASN1_TAG tag);
// Strings.
// asn1_is_printable returns one if `value` is a valid Unicode codepoint for an
// ASN.1 PrintableString, and zero otherwise.
int asn1_is_printable(uint32_t value);
// asn1_string_init initializes `str`, which may be uninitialized, with type
// `type`.
void asn1_string_init(ASN1_STRING *str, int type);
// asn1_string_cleanup releases memory associated with `str`'s value, without
// freeing `str` itself.
void asn1_string_cleanup(ASN1_STRING *str);
// A ScopedASN1String is a stack-allocatable `ASN1_STRING` with managed
// lifetime.
// TODO(crbug.com/443769299): Once `ASN1_STRING` is no longer public, this can
// instead use `DECLARE_OPAQUE_STRUCT`.
class ScopedASN1String {
public:
explicit ScopedASN1String(int type) { asn1_string_init(&str_, type); }
ScopedASN1String(const ScopedASN1String &) = delete;
ScopedASN1String &operator=(const ScopedASN1String &) = delete;
~ScopedASN1String() { asn1_string_cleanup(&str_); }
ASN1_STRING *get() { return &str_; }
const ASN1_STRING *get() const { return &str_; }
ASN1_STRING *operator->() { return &str_; }
const ASN1_STRING *operator->() const { return &str_; }
private:
ASN1_STRING str_;
};
// asn1_parse_string_unchecked parses a DER-encoded string of type `str_type`,
// tagged with `tag`. It does not check the contents.
int asn1_parse_string_unchecked(CBS *cbs, ASN1_STRING *out, int str_type,
CBS_ASN1_TAG tag);
// The following functions parse a DER-encoded ASN.1 value of the specified
// type from `cbs` and write the result to `*out`. If `tag` is non-zero, the
// value is implicitly tagged with `tag`. On success, they return one and
// advance `cbs` past the parsed element. On entry, `*out` must contain an
// `ASN1_STRING` in some valid state.
int asn1_parse_bit_string(CBS *cbs, ASN1_BIT_STRING *out, CBS_ASN1_TAG tag);
int asn1_parse_integer(CBS *cbs, ASN1_INTEGER *out, CBS_ASN1_TAG tag);
int asn1_parse_enumerated(CBS *cbs, ASN1_ENUMERATED *out, CBS_ASN1_TAG tag);
int asn1_parse_octet_string(CBS *cbs, ASN1_STRING *out, CBS_ASN1_TAG tag);
int asn1_parse_t61_string(CBS *cbs, ASN1_STRING *out, CBS_ASN1_TAG tag);
int asn1_parse_bmp_string(CBS *cbs, ASN1_BMPSTRING *out, CBS_ASN1_TAG tag);
int asn1_parse_universal_string(CBS *cbs, ASN1_UNIVERSALSTRING *out,
CBS_ASN1_TAG tag);
int asn1_parse_utf8_string(CBS *cbs, ASN1_UNIVERSALSTRING *out,
CBS_ASN1_TAG tag);
int asn1_parse_generalized_time(CBS *cbs, ASN1_GENERALIZEDTIME *out,
CBS_ASN1_TAG tag);
int asn1_parse_utc_time(CBS *cbs, ASN1_UTCTIME *out, CBS_ASN1_TAG tag,
int allow_timezone_offset);
// asn1_parse_bit_string_with_bad_length behaves like `asn1_parse_bit_string`
// but tolerates BER non-minimal, definite lengths.
int asn1_parse_bit_string_with_bad_length(CBS *cbs, ASN1_BIT_STRING *out);
// asn1_marshal_bit_string marshals `in` as a DER-encoded, ASN.1 BIT STRING and
// writes the result to `out`. It returns one on success and zero on error. If
// `tag` is non-zero, the tag is replaced with `tag`.
int asn1_marshal_bit_string(CBB *out, const ASN1_BIT_STRING *in,
CBS_ASN1_TAG tag);
// asn1_marshal_integer marshals `in` as a DER-encoded, ASN.1 INTEGER and writes
// the result to `out`. It returns one on success and zero on error. If `tag` is
// non-zero, the tag is replaced with `tag`. This can also be used to marshal an
// ASN.1 ENUMERATED value by overriding the tag.
int asn1_marshal_integer(CBB *out, const ASN1_INTEGER *in, CBS_ASN1_TAG tag);
// asn1_marshal_octet_string marshals `in` as a DER-encoded, ASN.1 OCTET STRING
// and writes the result to `out`. It returns one on success and zero on error.
// If `tag` is non-zero, the tag is replaced with `tag`.
//
// This function may be used to marshal other string-based universal types whose
// encoding is that of an implicitly-tagged OCTET STRING, e.g. UTF8String.
int asn1_marshal_octet_string(CBB *out, const ASN1_STRING *in,
CBS_ASN1_TAG tag);
OPENSSL_EXPORT int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d,
int allow_timezone_offset);
OPENSSL_EXPORT int asn1_generalizedtime_to_tm(struct tm *tm,
const ASN1_GENERALIZEDTIME *d);
int asn1_parse_time(CBS *cbs, ASN1_TIME *out, int allow_utc_timezone_offset);
int asn1_marshal_time(CBB *cbb, const ASN1_TIME *in);
// The ASN.1 ANY type.
// asn1_type_value_as_pointer returns `a`'s value in pointer form. This is
// usually the value object but, for BOOLEAN values, is 0 or 0xff cast to
// a pointer.
const void *asn1_type_value_as_pointer(const ASN1_TYPE *a);
// asn1_type_set0_string sets `a`'s value to the object represented by `str` and
// takes ownership of `str`.
void asn1_type_set0_string(ASN1_TYPE *a, ASN1_STRING *str);
// asn1_parse_any parses a DER-encoded ASN.1 value of any type from `cbs` and
// writes the result to `*out`. On success, it advances `cbs` past the parsed
// element and returns one. On entry, `*out` must contain an `ASN1_TYPE` in some
// valid state.
int asn1_parse_any(CBS *cbs, ASN1_TYPE *out);
// asn1_parse_any_as_string behaves like `asn1_parse_any` but represents the
// value as an `ASN1_STRING`. Types which are not represented with
// `ASN1_STRING`, such as `ASN1_OBJECT`, are represented with type
// `V_ASN1_OTHER`.
int asn1_parse_any_as_string(CBS *cbs, ASN1_STRING *out);
// asn1_marshal_any marshals `in` as a DER-encoded ASN.1 value and writes the
// result to `out`. It returns one on success and zero on error.
int asn1_marshal_any(CBB *out, const ASN1_TYPE *in);
// asn1_marshal_any_string marshals `in` as a DER-encoded ASN.1 value and writes
// the result to `out`. It returns one on success and zero on error.
int asn1_marshal_any_string(CBB *out, const ASN1_STRING *in);
// Support structures for the template-based encoder.
// ASN1_ENCODING is used to save the received encoding of an ASN.1 type. This
// avoids problems with invalid encodings that break signatures.
typedef struct ASN1_ENCODING_st {
// 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;
} ASN1_ENCODING;
int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt);
// ASN1_item_ex_d2i parses |len| bytes from |*in| as a structure of type |it|
// and writes the result to |*pval|. If |tag| is non-negative, |it| is
// implicitly tagged with the tag specified by |tag| and |aclass|. If |opt| is
// non-zero, the value is optional. If |buf| is non-NULL, |*in| must point into
// |buf|.
//
// This function returns one and advances |*in| if an object was successfully
// parsed, -1 if an optional value was successfully skipped, and zero on error.
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass, char opt,
CRYPTO_BUFFER *buf);
// ASN1_item_ex_i2d encodes |*pval| as a value of type |it| to |out| under the
// i2d output convention. It returns a non-zero length on success and -1 on
// error. If |tag| is -1. the tag and class come from |it|. Otherwise, the tag
// number is |tag| and the class is |aclass|. This is used for implicit tagging.
// This function treats a missing value as an error, not an optional field.
int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
// asn1_get_choice_selector returns the CHOICE selector value for |*pval|, which
// must of type |it|.
// asn1_load_ptr returns `*pval`, but without asserting `*pval`'s underlying
// type for strict aliasing. This helper must be used when the field's
// underlying type is not known statically. It must not be used for
// `ASN1_BOOLEAN` fields, which are not a pointers.
inline ASN1_VALUE *asn1_load_ptr(ASN1_VALUE **pval) {
ASN1_VALUE *ret;
OPENSSL_memcpy(&ret, pval, sizeof(ASN1_VALUE *));
return ret;
}
// asn1_load_ptr_as behaves like `asn1_load_ptr`, but casts the result to `T*`.
template <typename T>
inline T *asn1_load_ptr_as(ASN1_VALUE **pval) {
return reinterpret_cast<T *>(asn1_load_ptr(pval));
}
// asn1_store_ptr sets `*pval` to `v`, but without asserting `*pval`'s
// underlying type for strict aliasing. This helper must be used when the
// field's underlying type is not known statically. It must not be used for
// `ASN1_BOOLEAN` fields, which are not a pointers.
inline void asn1_store_ptr(ASN1_VALUE **pval, const void *v) {
OPENSSL_memcpy(pval, &v, sizeof(v));
}
// asn1_get_choice_selector returns the CHOICE selector value for `*pval`, which
// must of type `it`.
int asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it);
int asn1_set_choice_selector(ASN1_VALUE **pval, int value, const ASN1_ITEM *it);
// asn1_get_field_ptr returns a pointer to the field in |*pval| corresponding to
// |tt|.
// asn1_get_field_ptr returns a pointer to the field in `*pval` corresponding to
// `tt`.
ASN1_VALUE **asn1_get_field_ptr(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt);
// asn1_do_adb returns the |ASN1_TEMPLATE| for the ANY DEFINED BY field |tt|,
// based on the selector INTEGER or OID in |*pval|. If |tt| is not an ADB field,
// it returns |tt|. If the selector does not match any value, it returns NULL.
// If |nullerr| is non-zero, it will additionally push an error to the error
// asn1_do_adb returns the `ASN1_TEMPLATE` for the ANY DEFINED BY field `tt`,
// based on the selector INTEGER or OID in `*pval`. If `tt` is not an ADB field,
// it returns `tt`. If the selector does not match any value, it returns NULL.
// If `nullerr` is non-zero, it will additionally push an error to the error
// queue when there is no match.
const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt,
int nullerr);
@@ -135,45 +284,29 @@ int asn1_refcount_dec_and_test_zero(ASN1_VALUE **pval, const ASN1_ITEM *it);
void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it);
void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
// asn1_enc_restore, if |*pval| has a saved encoding, writes it to |out| under
// the i2d output convention, sets |*len| to the length, and returns one. If it
// has no saved encoding, it returns zero.
int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval,
// asn1_enc_restore, if `*pval` has a saved encoding, sets `*out` to it, and
// returns one. If it has no saved encoding, it returns zero.
int asn1_enc_restore(Span<const uint8_t> *out, ASN1_VALUE **pval,
const ASN1_ITEM *it);
// asn1_enc_save saves |inlen| bytes from |in| as |*pval|'s saved encoding. It
// returns one on success and zero on error. If |buf| is non-NULL, |in| must
// point into |buf|.
// 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);
const ASN1_ITEM *it);
// asn1_encoding_clear clears the cached encoding in |enc|.
// asn1_encoding_clear clears the cached encoding in `enc`.
void asn1_encoding_clear(ASN1_ENCODING *enc);
// asn1_type_value_as_pointer returns |a|'s value in pointer form. This is
// usually the value object but, for BOOLEAN values, is 0 or 0xff cast to
// a pointer.
const void *asn1_type_value_as_pointer(const ASN1_TYPE *a);
// asn1_type_set0_string sets |a|'s value to the object represented by |str| and
// takes ownership of |str|.
void asn1_type_set0_string(ASN1_TYPE *a, ASN1_STRING *str);
// asn1_type_cleanup releases memory associated with |a|'s value, without
// freeing |a| itself.
void asn1_type_cleanup(ASN1_TYPE *a);
// asn1_is_printable returns one if |value| is a valid Unicode codepoint for an
// ASN.1 PrintableString, and zero otherwise.
int asn1_is_printable(uint32_t value);
// asn1_bit_string_length returns the number of bytes in |str| and sets
// |*out_padding_bits| to the number of padding bits.
// asn1_tag_to_cbs converts a tag from this library's representation (the
// `V_ASN1_*` constants) to that of `CBS` and `CBB`. It returns the tag on
// success and zero if the input could not be represented. (Zero would be
// [UNIVERSAL 0], which is a reserved tag value.)
//
// This function should be used instead of |ASN1_STRING_length| to correctly
// handle the non-|ASN1_STRING_FLAG_BITS_LEFT| case.
int asn1_bit_string_length(const ASN1_BIT_STRING *str,
uint8_t *out_padding_bits);
// The resulting tag will not have the constructed bit set. The caller must OR
// the result with `CBS_ASN1_CONSTRUCTED` if necessary, before passing to
// `CBS` and `CBB` functions.
CBS_ASN1_TAG asn1_tag_to_cbs(int aclass, int tag);
typedef struct {
int nid;
@@ -183,35 +316,115 @@ typedef struct {
unsigned long flags;
} ASN1_STRING_TABLE;
// asn1_get_string_table_for_testing sets |*out_ptr| and |*out_len| to the table
// of built-in |ASN1_STRING_TABLE| values. It is exported for testing.
// asn1_get_string_table_for_testing sets `*out_ptr` and `*out_len` to the table
// of built-in `ASN1_STRING_TABLE` values. It is exported for testing.
OPENSSL_EXPORT void asn1_get_string_table_for_testing(
const ASN1_STRING_TABLE **out_ptr, size_t *out_len);
typedef ASN1_VALUE *ASN1_new_func(void);
typedef ASN1_VALUE *ASN1_new_func();
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);
// An ASN1_ex_parse function should parse a value from `cbs` and set `*pval` to
// the result. It should return one on success and zero on failure. If `opt` is
// non-zero, the field may be optional. If an optional element is missing, the
// function should return one and consume zero bytes from `cbs`.
//
// If `opt` is non-zero, the function can assume that `*pval` is nullptr on
// entry. Otherwise, `*pval` may either be nullptr, or the result of
// `ASN1_ex_new_func`. The function may either write into the existing object,
// if any, or unconditionally make a new one. (The existing object comes from
// tasn_new.cc recursively filling in objects before parsing into them.)
typedef int ASN1_ex_parse(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it,
int opt);
// An ASN1_ex_marshal function should marshal `*pval`, a value of type `it`, to
// `cbb` and return one on success or zero on error.
typedef int ASN1_ex_marshal(CBB *cbb, ASN1_VALUE **pval, const ASN1_ITEM *it);
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_ex_parse *asn1_ex_parse;
ASN1_ex_marshal *asn1_ex_marshal;
} ASN1_EXTERN_FUNCS;
// IMPLEMENT_EXTERN_ASN1_PARSE_NEW implements an `ASN1_ITEM` for a type whose
// parse function returns a new object.
#define IMPLEMENT_EXTERN_ASN1_PARSE_NEW(name, new_func, free_func, tag, \
parse_func, marshal_func) \
static int name##_new_cb(ASN1_VALUE **pval, const ASN1_ITEM *it) { \
name *obj = new_func(); \
if (obj == nullptr) { \
return 0; \
} \
asn1_store_ptr(pval, obj); \
return 1; \
} \
\
static void name##_free_cb(ASN1_VALUE **pval, const ASN1_ITEM *it) { \
free_func(asn1_load_ptr_as<name>(pval)); \
asn1_store_ptr(pval, nullptr); \
} \
\
static int name##_parse_cb(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it, \
int opt) { \
if (opt && !CBS_peek_asn1_tag(cbs, (tag))) { \
return 1; \
} \
\
bssl::UniquePtr<name> ret = parse_func(cbs); \
if (ret == nullptr) { \
return 0; \
} \
name##_free_cb(pval, it); \
asn1_store_ptr(pval, ret.release()); \
return 1; \
} \
\
static int name##_marshal_cb(CBB *cbb, ASN1_VALUE **pval, \
const ASN1_ITEM *it) { \
return marshal_func(cbb, asn1_load_ptr_as<name>(pval)); \
} \
\
static const ASN1_EXTERN_FUNCS name##_extern_funcs = { \
name##_new_cb, name##_free_cb, name##_parse_cb, name##_marshal_cb}; \
\
IMPLEMENT_EXTERN_ASN1(name, name##_extern_funcs)
#if defined(__cplusplus)
} // extern C
#endif
// IMPLEMENT_EXTERN_ASN1_PARSE_INTO implements an `ASN1_ITEM` for a type whose
// parse function writes into an existing object.
#define IMPLEMENT_EXTERN_ASN1_PARSE_INTO(name, new_func, free_func, tag, \
parse_func, marshal_func) \
\
static bssl::UniquePtr<name> name##_parse_new(CBS *cbs) { \
bssl::UniquePtr<name> ret(new_func()); \
if (ret == nullptr || !parse_func(cbs, ret.get())) { \
return 0; \
} \
return ret; \
} \
\
IMPLEMENT_EXTERN_ASN1_PARSE_NEW(name, new_func, free_func, tag, \
name##_parse_new, marshal_func)
#endif // OPENSSL_HEADER_ASN1_INTERNAL_H
// ASN1_TIME is an `ASN1_ITEM` whose ASN.1 type is X.509 Time (RFC 5280) and C
// type is `ASN1_TIME*`.
DECLARE_ASN1_ITEM(ASN1_TIME)
// DIRECTORYSTRING is an `ASN1_ITEM` whose ASN.1 type is X.509 DirectoryString
// (RFC 5280) and C type is `ASN1_STRING*`.
DECLARE_ASN1_ITEM(DIRECTORYSTRING)
// DISPLAYTEXT is an `ASN1_ITEM` whose ASN.1 type is X.509 DisplayText (RFC
// 5280) and C type is `ASN1_STRING*`.
DECLARE_ASN1_ITEM(DISPLAYTEXT)
BSSL_NAMESPACE_END
#endif // OPENSSL_HEADER_CRYPTO_ASN1_INTERNAL_H
+21 -18
View File
@@ -1,16 +1,16 @@
/* Copyright 2022 The BoringSSL Authors
*
* 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. */
// Copyright 2022 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Time conversion to/from POSIX time_t and struct tm, with no support
// for time zones other than UTC
@@ -29,6 +29,8 @@
#define SECS_PER_DAY (INT64_C(24) * SECS_PER_HOUR)
using namespace bssl;
// Is a year/month/day combination valid, in the range from year 0000
// to 9999?
static int is_valid_date(int64_t year, int64_t month, int64_t day) {
@@ -183,18 +185,19 @@ int OPENSSL_timegm(const struct tm *tm, time_t *out) {
return 1;
}
struct tm *OPENSSL_gmtime(const time_t *time, struct tm *out_tm) {
struct tm *bssl::OPENSSL_gmtime(const time_t *time, struct tm *out_tm) {
static_assert(
sizeof(time_t) == sizeof(int32_t) || sizeof(time_t) == sizeof(int64_t),
"time_t is broken");
int64_t posix_time = *time;
if (!OPENSSL_posix_to_tm(posix_time, out_tm)) {
return NULL;
return nullptr;
}
return out_tm;
}
int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, int64_t offset_sec) {
int bssl::OPENSSL_gmtime_adj(struct tm *tm, int offset_day,
int64_t offset_sec) {
int64_t posix_time;
if (!OPENSSL_tm_to_posix(tm, &posix_time)) {
return 0;
@@ -221,8 +224,8 @@ int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, int64_t offset_sec) {
return 1;
}
int OPENSSL_gmtime_diff(int *out_days, int *out_secs, const struct tm *from,
const struct tm *to) {
int bssl::OPENSSL_gmtime_diff(int *out_days, int *out_secs,
const struct tm *from, const struct tm *to) {
int64_t time_to, time_from;
if (!OPENSSL_tm_to_posix(to, &time_to) ||
!OPENSSL_tm_to_posix(from, &time_from)) {
File diff suppressed because it is too large. Load diff
+232 -548
View File
@@ -1,11 +1,16 @@
/*
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -16,616 +21,306 @@
#include <CNIOBoringSSL_asn1t.h>
#include <CNIOBoringSSL_mem.h>
#include "../bytestring/internal.h"
#include "../internal.h"
#include "internal.h"
static int asn1_item_ex_i2d_opt(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass,
int optional);
static int asn1_i2d_ex_primitive(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass,
int optional);
static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cont, int *out_omit,
int *putype, const ASN1_ITEM *it);
static int asn1_set_seq_out(STACK_OF(ASN1_VALUE) *sk, unsigned char **out,
int skcontlen, const ASN1_ITEM *item, int do_sort);
static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_TEMPLATE *tt, int tag, int aclass,
int optional);
using namespace bssl;
// Top level i2d equivalents
static int asn1_marshal_item(CBB *cbb, ASN1_VALUE **pval, const ASN1_ITEM *it,
CBS_ASN1_TAG tag);
static int asn1_marshal_template(CBB *cbb, ASN1_VALUE **pval,
const ASN1_TEMPLATE *tt, CBS_ASN1_TAG tag);
static int asn1_marshal_template_no_explicit(CBB *cbb, ASN1_VALUE **pval,
const ASN1_TEMPLATE *tt,
CBS_ASN1_TAG tag);
static int asn1_marshal_primitive(CBB *cbb, ASN1_VALUE **pval,
const ASN1_ITEM *it, CBS_ASN1_TAG tag);
int ASN1_item_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it) {
if (out && !*out) {
unsigned char *p, *buf;
int len = ASN1_item_ex_i2d(&val, NULL, it, /*tag=*/-1, /*aclass=*/0);
if (len <= 0) {
return len;
}
buf = reinterpret_cast<uint8_t *>(OPENSSL_malloc(len));
if (!buf) {
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);
*out = buf;
return len;
static bool asn1_item_has_value(ASN1_VALUE **pval, const ASN1_ITEM *it);
static bool asn1_template_has_value(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt);
int ASN1_item_i2d(ASN1_VALUE *val, uint8_t **out, const ASN1_ITEM *it) {
return I2DFromCBB(/*initial_capacity=*/64, out, [&](CBB *cbb) -> bool {
return asn1_marshal_item(cbb, &val, it, /*tag=*/0);
});
}
// asn1_item_has_value returns whether `pval`, which must have type `it`,
// contains a value.
bool asn1_item_has_value(ASN1_VALUE **pval, const ASN1_ITEM *it) {
// Almost every `ASN1_VALUE` is a pointer, except for types represented as
// `ASN1_BOOLEAN`.
if (it->itype != ASN1_ITYPE_PRIMITIVE) {
// All non-primitive types are pointers.
return asn1_load_ptr(pval) != nullptr;
}
return ASN1_item_ex_i2d(&val, out, it, /*tag=*/-1, /*aclass=*/0);
if (it->templates != nullptr) {
// This is an `ASN1_ITEM_TEMPLATE`. Recurse into the template.
return asn1_template_has_value(pval, it->templates);
}
if (it->utype != V_ASN1_BOOLEAN) {
return asn1_load_ptr(pval) != nullptr;
}
// `ASN1_BOOLEAN` may be omitted in two ways. -1 indicates an omitted
// OPTIONAL BOOLEAN. Additionally, if `it` is `ASN1_FBOOLEAN` or
// `ASN1_TBOOLEAN`, this is DEFAULT FALSE and DEFAULT TRUE, respectively. This
// is stored in `it->size`.
ASN1_BOOLEAN b = *reinterpret_cast<const ASN1_BOOLEAN *>(pval);
if (b == ASN1_BOOLEAN_NONE) {
return false;
}
if (it->size > 0) {
// This is DEFAULT TRUE, so only FALSE is present.
return b == ASN1_BOOLEAN_FALSE;
}
if (it->size == 0) {
// This is DEFAULT FALSE, so only TRUE is present.
return b != ASN1_BOOLEAN_FALSE;
}
return true;
}
// Encode an item, taking care of IMPLICIT tagging (if any). This function
// performs the normal item handling: it can be used in external types.
int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass) {
int ret = asn1_item_ex_i2d_opt(pval, out, it, tag, aclass, /*optional=*/0);
assert(ret != 0);
return ret;
// asn1_template_has_value returns whether `pval`, which must have type `tt`,
// contains a value.
bool asn1_template_has_value(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) {
if (tt->flags & ASN1_TFLG_SK_MASK) {
// If `tt` is a SEQUENCE OF or SET OF type, the C type is `STACK_OF(T)` and
// is a pointer.
return asn1_load_ptr(pval) != nullptr;
}
// Otherwise, `tt`'s representation is the underlying item.
return asn1_item_has_value(pval, ASN1_ITEM_ptr(tt->item));
}
// asn1_item_ex_i2d_opt behaves like |ASN1_item_ex_i2d| but, if |optional| is
// non-zero and |*pval| is omitted, it returns zero and writes no bytes.
int asn1_item_ex_i2d_opt(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass,
int optional) {
const ASN1_TEMPLATE *tt = NULL;
int i, seqcontlen, seqlen;
// Historically, |aclass| was repurposed to pass additional flags into the
// encoding process.
assert((aclass & ASN1_TFLG_TAG_CLASS) == aclass);
// If not overridding the tag, |aclass| is ignored and should be zero.
assert(tag != -1 || aclass == 0);
// All fields are pointers, except for boolean |ASN1_ITYPE_PRIMITIVE|s.
// Optional primitives are handled later.
if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !*pval) {
if (optional) {
return 0;
}
// asn1_marshal_item marshals `pval`, of type `it`, and writes the result to
// `cbb`. It returns one on success and zero on error. If `tag` is non-zero, the
// value is implicitly tagged with `tag`.
static int asn1_marshal_item(CBB *cbb, ASN1_VALUE **pval, const ASN1_ITEM *it,
CBS_ASN1_TAG tag) {
// All fields are pointers, except for boolean `ASN1_ITYPE_PRIMITIVE`s. Those
// cases will be checked later.
if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !asn1_load_ptr(pval)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE);
return -1;
return 0;
}
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
// This is an |ASN1_ITEM_TEMPLATE|.
// This is an `ASN1_ITEM_TEMPLATE`, so the underlying template cannot be
// optional. Optionality should be expressed at the layer above.
if (it->templates->flags & ASN1_TFLG_OPTIONAL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
return 0;
}
return asn1_template_ex_i2d(pval, out, it->templates, tag, aclass,
optional);
return asn1_marshal_template(cbb, pval, it->templates, tag);
}
return asn1_i2d_ex_primitive(pval, out, it, tag, aclass, optional);
return asn1_marshal_primitive(cbb, pval, it, tag);
case ASN1_ITYPE_MSTRING:
// It never makes sense for multi-strings to have implicit tagging, so
// if tag != -1, then this looks like an error in the template.
if (tag != -1) {
// CHOICE types cannot be implicitly tagged.
if (tag != 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
return 0;
}
return asn1_i2d_ex_primitive(pval, out, it, -1, 0, optional);
return asn1_marshal_any_string(cbb, asn1_load_ptr_as<ASN1_STRING>(pval));
case ASN1_ITYPE_CHOICE: {
// It never makes sense for CHOICE types to have implicit tagging, so if
// tag != -1, then this looks like an error in the template.
if (tag != -1) {
// CHOICE types cannot be implicitly tagged.
if (tag != 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
return 0;
}
i = asn1_get_choice_selector(pval, it);
int i = asn1_get_choice_selector(pval, it);
if (i < 0 || i >= it->tcount) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NO_MATCHING_CHOICE_TYPE);
return -1;
return 0;
}
const ASN1_TEMPLATE *chtt = it->templates + i;
const ASN1_TEMPLATE *chtt = &it->templates[i];
if (chtt->flags & ASN1_TFLG_OPTIONAL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
return 0;
}
ASN1_VALUE **pchval = asn1_get_field_ptr(pval, chtt);
return asn1_template_ex_i2d(pchval, out, chtt, -1, 0, /*optional=*/0);
return asn1_marshal_template(cbb, pchval, chtt, /*tag=*/0);
}
case ASN1_ITYPE_EXTERN: {
// We don't support implicit tagging with external types.
if (tag != -1) {
if (tag != 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
return 0;
}
const ASN1_EXTERN_FUNCS *ef =
reinterpret_cast<const ASN1_EXTERN_FUNCS *>(it->funcs);
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
// must be pointers.
OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR);
return -1;
}
return ret;
auto *ef = static_cast<const ASN1_EXTERN_FUNCS *>(it->funcs);
return ef->asn1_ex_marshal(cbb, pval, it);
}
case ASN1_ITYPE_SEQUENCE: {
i = asn1_enc_restore(&seqcontlen, out, pval, it);
// An error occurred
if (i < 0) {
return -1;
Span<const uint8_t> enc;
if (asn1_enc_restore(&enc, pval, it)) {
return CBB_add_bytes(cbb, enc.data(), enc.size());
}
// We have a valid cached encoding...
if (i > 0) {
return seqcontlen;
tag = tag == 0 ? CBS_ASN1_SEQUENCE : (tag | CBS_ASN1_CONSTRUCTED);
CBB seq;
if (!CBB_add_asn1(cbb, &seq, tag)) {
return 0;
}
// Otherwise carry on
seqcontlen = 0;
// If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL
if (tag == -1) {
tag = V_ASN1_SEQUENCE;
aclass = V_ASN1_UNIVERSAL;
}
// First work out sequence content length
for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
int tmplen;
seqtt = asn1_do_adb(pval, tt, 1);
for (int i = 0; i < it->tcount; i++) {
const ASN1_TEMPLATE *tt = &it->templates[i];
const ASN1_TEMPLATE *seqtt = asn1_do_adb(pval, tt, /*nullerr=*/1);
if (!seqtt) {
return -1;
return 0;
}
pseqval = asn1_get_field_ptr(pval, seqtt);
tmplen =
asn1_template_ex_i2d(pseqval, NULL, seqtt, -1, 0, /*optional=*/0);
if (tmplen == -1 || (tmplen > INT_MAX - seqcontlen)) {
return -1;
ASN1_VALUE **pseqval = asn1_get_field_ptr(pval, seqtt);
if (!asn1_template_has_value(pseqval, seqtt)) {
if ((seqtt->flags & ASN1_TFLG_OPTIONAL) != 0) {
continue;
}
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE);
return 0;
}
seqcontlen += tmplen;
}
seqlen = ASN1_object_size(/*constructed=*/1, seqcontlen, tag);
if (!out || seqlen == -1) {
return seqlen;
}
// Output SEQUENCE header
ASN1_put_object(out, /*constructed=*/1, seqcontlen, tag, aclass);
for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 1);
if (!seqtt) {
return -1;
}
pseqval = asn1_get_field_ptr(pval, seqtt);
if (asn1_template_ex_i2d(pseqval, out, seqtt, -1, 0, /*optional=*/0) <
0) {
return -1;
if (!asn1_marshal_template(&seq, pseqval, seqtt, /*tag=*/0)) {
return 0;
}
}
return seqlen;
return CBB_flush(cbb);
}
default:
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
return 0;
}
}
// asn1_template_ex_i2d behaves like |asn1_item_ex_i2d_opt| but uses an
// |ASN1_TEMPLATE| instead of an |ASN1_ITEM|. An |ASN1_TEMPLATE| wraps an
// |ASN1_ITEM| with modifiers such as tagging, SEQUENCE or SET, etc.
static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_TEMPLATE *tt, int tag, int iclass,
int optional) {
int i, ret, ttag, tclass;
size_t j;
// asn1_marshal_template marshals `pval`, of type `tt`, and writes the result to
// `cbb`. It returns one on success and zero on error. If `tag` is non-zero, the
// value is implicitly tagged with `tag`.
//
// This function does not look at `ASN1_TFLG_OPTIONAL`. The caller is expected
// to have evaluated it already and, if applicable, skip this function.
static int asn1_marshal_template(CBB *cbb, ASN1_VALUE **pval,
const ASN1_TEMPLATE *tt, CBS_ASN1_TAG tag) {
uint32_t flags = tt->flags;
if (!(flags & ASN1_TFLG_EXPTAG)) {
return asn1_marshal_template_no_explicit(cbb, pval, tt, tag);
}
// Determine the explicit tag to use. If the caller supplied an implicit tag,
// it overrides this one. Otherwise, use the tag in the template.
if (tag == 0) {
tag = asn1_tag_to_cbs(flags & ASN1_TFLG_TAG_CLASS, tt->tag);
if (tag == 0) {
return 0;
}
}
CBB child;
return CBB_add_asn1(cbb, &child, tag | CBS_ASN1_CONSTRUCTED) &&
asn1_marshal_template_no_explicit(&child, pval, tt, /*tag=*/0) &&
CBB_flush(cbb);
}
// asn1_marshal_template_no_explicit behaves like `asn1_marshal_template` except
// it ignores any explicit tagging specified in `tt`.
static int asn1_marshal_template_no_explicit(CBB *cbb, ASN1_VALUE **pval,
const ASN1_TEMPLATE *tt,
CBS_ASN1_TAG tag) {
uint32_t flags = tt->flags;
// Historically, |iclass| was repurposed to pass additional flags into the
// encoding process.
assert((iclass & ASN1_TFLG_TAG_CLASS) == iclass);
// If not overridding the tag, |iclass| is ignored and should be zero.
assert(tag != -1 || iclass == 0);
// Work out tag and class to use: tagging may come either from the
// template or the arguments, not both because this would create
// ambiguity.
if (flags & ASN1_TFLG_TAG_MASK) {
// Error if argument and template tagging
if (tag != -1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
// If `tt` provides implicit tagging and the caller did not already override
// the tag, pick up the tag from the template.
if ((flags & ASN1_TFLG_IMPTAG) && tag == 0) {
tag = asn1_tag_to_cbs(flags & ASN1_TFLG_TAG_CLASS, tt->tag);
if (tag == 0) {
return 0;
}
// Get tagging from template
ttag = tt->tag;
tclass = flags & ASN1_TFLG_TAG_CLASS;
} else if (tag != -1) {
// No template tagging, get from arguments
ttag = tag;
tclass = iclass & ASN1_TFLG_TAG_CLASS;
} else {
ttag = -1;
tclass = 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.
if (flags & ASN1_TFLG_SK_MASK) {
// SET OF, SEQUENCE OF
STACK_OF(ASN1_VALUE) *sk = (STACK_OF(ASN1_VALUE) *)*pval;
int isset, sktag, skaclass;
int skcontlen, sklen;
ASN1_VALUE *skitem;
if (!*pval) {
if (optional) {
return 0;
}
// This is a SET OF or SEQUENCE OF type.
STACK_OF(ASN1_VALUE) *sk = asn1_load_ptr_as<STACK_OF(ASN1_VALUE)>(pval);
if (sk == nullptr) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE);
return -1;
return 0;
}
if (flags & ASN1_TFLG_SET_OF) {
isset = 1;
// Historically, types with both bits set were mutated when
// serialized to apply the sort. We no longer support this.
bool is_set = (flags & ASN1_TFLG_SET_OF) != 0;
if (is_set) {
// Historically, types with both bits set were mutated when serialized to
// apply the sort. We no longer support this.
assert((flags & ASN1_TFLG_SEQUENCE_OF) == 0);
} else {
isset = 0;
}
// Work out inner tag value: if EXPLICIT or no tagging use underlying
// type.
if ((ttag != -1) && !(flags & ASN1_TFLG_EXPTAG)) {
sktag = ttag;
skaclass = tclass;
} else {
skaclass = V_ASN1_UNIVERSAL;
if (isset) {
sktag = V_ASN1_SET;
} else {
sktag = V_ASN1_SEQUENCE;
}
if (tag == 0) {
tag = is_set ? CBS_ASN1_SET : CBS_ASN1_SEQUENCE;
}
// Determine total length of items
skcontlen = 0;
for (j = 0; j < sk_ASN1_VALUE_num(sk); j++) {
int tmplen;
skitem = sk_ASN1_VALUE_value(sk, j);
tmplen = ASN1_item_ex_i2d(&skitem, NULL, ASN1_ITEM_ptr(tt->item), -1, 0);
if (tmplen == -1 || (skcontlen > INT_MAX - tmplen)) {
return -1;
}
skcontlen += tmplen;
CBB child;
if (!CBB_add_asn1(cbb, &child, tag | CBS_ASN1_CONSTRUCTED)) {
return 0;
}
sklen = ASN1_object_size(/*constructed=*/1, skcontlen, sktag);
if (sklen == -1) {
return -1;
}
// If EXPLICIT need length of surrounding tag
if (flags & ASN1_TFLG_EXPTAG) {
ret = ASN1_object_size(/*constructed=*/1, sklen, ttag);
} else {
ret = sklen;
}
if (!out || ret == -1) {
return ret;
}
// Now encode this lot...
// EXPLICIT tag
if (flags & ASN1_TFLG_EXPTAG) {
ASN1_put_object(out, /*constructed=*/1, sklen, ttag, tclass);
}
// SET or SEQUENCE and IMPLICIT tag
ASN1_put_object(out, /*constructed=*/1, skcontlen, sktag, skaclass);
// And the stuff itself
if (!asn1_set_seq_out(sk, out, skcontlen, ASN1_ITEM_ptr(tt->item), isset)) {
return -1;
}
return ret;
}
if (flags & ASN1_TFLG_EXPTAG) {
// EXPLICIT tagging
// Find length of tagged item
i = asn1_item_ex_i2d_opt(pval, NULL, ASN1_ITEM_ptr(tt->item), -1, 0,
optional);
if (i <= 0) {
return i;
}
// Find length of EXPLICIT tag
ret = ASN1_object_size(/*constructed=*/1, i, ttag);
if (out && ret != -1) {
// Output tag and item
ASN1_put_object(out, /*constructed=*/1, i, ttag, tclass);
if (ASN1_item_ex_i2d(pval, out, ASN1_ITEM_ptr(tt->item), -1, 0) < 0) {
return -1;
}
}
return ret;
}
// Either normal or IMPLICIT tagging
return asn1_item_ex_i2d_opt(pval, out, ASN1_ITEM_ptr(tt->item), ttag, tclass,
optional);
}
// Temporary structure used to hold DER encoding of items for SET OF
typedef struct {
unsigned char *data;
int length;
} DER_ENC;
static int der_cmp(const void *a, const void *b) {
const DER_ENC *d1 = reinterpret_cast<const DER_ENC *>(a),
*d2 = reinterpret_cast<const DER_ENC *>(b);
int cmplen, i;
cmplen = (d1->length < d2->length) ? d1->length : d2->length;
i = OPENSSL_memcmp(d1->data, d2->data, cmplen);
if (i) {
return i;
}
return d1->length - d2->length;
}
// asn1_set_seq_out writes |sk| to |out| under the i2d output convention,
// excluding the tag and length. It returns one on success and zero on error.
// |skcontlen| must be the total encoded size. If |do_sort| is non-zero, the
// elements are sorted for a SET OF type. Each element of |sk| has type
// |item|.
static int asn1_set_seq_out(STACK_OF(ASN1_VALUE) *sk, unsigned char **out,
int skcontlen, const ASN1_ITEM *item, int do_sort) {
// No need to sort if there are fewer than two items.
if (!do_sort || sk_ASN1_VALUE_num(sk) < 2) {
for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
ASN1_VALUE *skitem = sk_ASN1_VALUE_value(sk, i);
if (ASN1_item_ex_i2d(&skitem, out, item, -1, 0) < 0) {
ASN1_VALUE *elem = sk_ASN1_VALUE_value(sk, i);
if (!asn1_marshal_item(&child, &elem, ASN1_ITEM_ptr(tt->item),
/*tag=*/0)) {
return 0;
}
}
return 1;
}
int ret = 0;
uint8_t *const buf = reinterpret_cast<uint8_t *>(OPENSSL_malloc(skcontlen));
DER_ENC *encoded = reinterpret_cast<DER_ENC *>(
OPENSSL_calloc(sk_ASN1_VALUE_num(sk), sizeof(*encoded)));
uint8_t *p = buf;
if (encoded == NULL || buf == NULL) {
goto err;
}
// Encode all the elements into |buf| and populate |encoded|.
for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
ASN1_VALUE *skitem = sk_ASN1_VALUE_value(sk, i);
encoded[i].data = p;
encoded[i].length = ASN1_item_ex_i2d(&skitem, &p, item, -1, 0);
if (encoded[i].length < 0) {
goto err;
// If this is a SET OF type, sort the encodings when flushing.
if (is_set) {
return CBB_flush_asn1_set_of(&child) && CBB_flush(cbb);
}
assert(p - buf <= skcontlen);
return CBB_flush(cbb);
}
qsort(encoded, sk_ASN1_VALUE_num(sk), sizeof(*encoded), der_cmp);
// Output the elements in sorted order.
p = *out;
for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
OPENSSL_memcpy(p, encoded[i].data, encoded[i].length);
p += encoded[i].length;
}
*out = p;
ret = 1;
err:
OPENSSL_free(encoded);
OPENSSL_free(buf);
return ret;
return asn1_marshal_item(cbb, pval, ASN1_ITEM_ptr(tt->item), tag);
}
// asn1_i2d_ex_primitive behaves like |ASN1_item_ex_i2d| but |item| must be a
// a PRIMITIVE or MSTRING type that is not an |ASN1_ITEM_TEMPLATE|.
static int asn1_i2d_ex_primitive(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass,
int optional) {
// Get length of content octets and maybe find out the underlying type.
int omit;
int utype = it->utype;
int len = asn1_ex_i2c(pval, NULL, &omit, &utype, it);
if (len < 0) {
return -1;
}
if (omit) {
if (optional) {
return 0;
}
static int asn1_marshal_primitive(CBB *cbb, ASN1_VALUE **pval,
const ASN1_ITEM *it, CBS_ASN1_TAG tag) {
assert(it->itype == ASN1_ITYPE_PRIMITIVE);
// Historically, `it->funcs` for primitive types contained an
// `ASN1_PRIMITIVE_FUNCS` table of callbacks.
assert(it->funcs == nullptr);
if (!asn1_item_has_value(pval, it)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE);
return -1;
return 0;
}
// If SEQUENCE, SET or OTHER then header is included in pseudo content
// octets so don't include tag+length. We need to check here because the
// call to asn1_ex_i2c() could change utype.
int usetag =
utype != V_ASN1_SEQUENCE && utype != V_ASN1_SET && utype != V_ASN1_OTHER;
// If not implicitly tagged get tag from underlying type
if (tag == -1) {
tag = utype;
}
// Output tag+length followed by content octets
if (out) {
if (usetag) {
ASN1_put_object(out, /*constructed=*/0, len, tag, aclass);
}
int len2 = asn1_ex_i2c(pval, *out, &omit, &utype, it);
if (len2 < 0) {
return -1;
}
assert(len == len2);
assert(!omit);
*out += len;
}
if (usetag) {
return ASN1_object_size(/*constructed=*/0, len, tag);
}
return len;
}
// asn1_ex_i2c writes the |*pval| to |cout| under the i2d output convention,
// excluding the tag and length. It returns the number of bytes written,
// possibly zero, on success or -1 on error. If |*pval| should be omitted, it
// returns zero and sets |*out_omit| to true.
//
// If |it| is an MSTRING or ANY type, it gets the underlying type from |*pval|,
// which must be an |ASN1_STRING| or |ASN1_TYPE|, respectively. It then updates
// |*putype| with the tag number of type used, or |V_ASN1_OTHER| if it was not a
// universal type. If |*putype| is set to |V_ASN1_SEQUENCE|, |V_ASN1_SET|, or
// |V_ASN1_OTHER|, it additionally outputs the tag and length, so the caller
// must not do so.
//
// Otherwise, |*putype| must contain |it->utype|.
//
// WARNING: Unlike most functions in this file, |asn1_ex_i2c| can return zero
// without omitting the element. ASN.1 values may have empty contents.
static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *out_omit,
int *putype, const ASN1_ITEM *it) {
ASN1_BOOLEAN *tbool = NULL;
ASN1_STRING *strtmp;
ASN1_OBJECT *otmp;
int utype;
const unsigned char *cont;
unsigned char c;
int len;
// Historically, |it->funcs| for primitive types contained an
// |ASN1_PRIMITIVE_FUNCS| table of callbacks.
assert(it->funcs == NULL);
*out_omit = 0;
// Should type be omitted?
if ((it->itype != ASN1_ITYPE_PRIMITIVE) || (it->utype != V_ASN1_BOOLEAN)) {
if (!*pval) {
*out_omit = 1;
return 0;
}
}
if (it->itype == ASN1_ITYPE_MSTRING) {
// If MSTRING type set the underlying type
strtmp = (ASN1_STRING *)*pval;
utype = strtmp->type;
if (utype < 0 && utype != V_ASN1_OTHER) {
// MSTRINGs can have type -1 when default-constructed.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE);
return -1;
}
// Negative INTEGER and ENUMERATED values use |ASN1_STRING| type values
// that do not match their corresponding utype values. INTEGERs cannot
// participate in MSTRING types, but ENUMERATEDs can.
//
// TODO(davidben): Is this a bug? Although arguably one of the MSTRING
// types should contain more values, rather than less. See
// https://crbug.com/boringssl/412. But it is not possible to fit all
// possible ANY values into an |ASN1_STRING|, so matching the spec here
// is somewhat hopeless.
if (utype == V_ASN1_NEG_INTEGER) {
utype = V_ASN1_INTEGER;
} else if (utype == V_ASN1_NEG_ENUMERATED) {
utype = V_ASN1_ENUMERATED;
}
*putype = utype;
} else if (it->utype == V_ASN1_ANY) {
// If ANY set type and pointer to value
ASN1_TYPE *typ;
typ = (ASN1_TYPE *)*pval;
utype = typ->type;
if (utype < 0 && utype != V_ASN1_OTHER) {
// |ASN1_TYPE|s can have type -1 when default-constructed.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE);
return -1;
}
*putype = utype;
pval = &typ->value.asn1_value;
} else {
utype = *putype;
}
switch (utype) {
case V_ASN1_OBJECT:
otmp = (ASN1_OBJECT *)*pval;
cont = otmp->data;
len = otmp->length;
if (len == 0) {
// Some |ASN1_OBJECT|s do not have OIDs and cannot be serialized.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OBJECT);
return -1;
}
break;
case V_ASN1_NULL:
cont = NULL;
len = 0;
break;
case V_ASN1_BOOLEAN:
tbool = (ASN1_BOOLEAN *)pval;
if (*tbool == ASN1_BOOLEAN_NONE) {
*out_omit = 1;
// Handle non-string types.
switch (it->utype) {
case V_ASN1_ANY:
// ANY types cannot be implicitly tagged.
if (tag != 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return 0;
}
if (it->utype != V_ASN1_ANY) {
// Default handling if value == size field then omit
if ((*tbool && (it->size > 0)) || (!*tbool && !it->size)) {
*out_omit = 1;
return 0;
}
}
c = *tbool ? 0xff : 0x00;
cont = &c;
len = 1;
break;
case V_ASN1_BIT_STRING: {
int ret =
i2c_ASN1_BIT_STRING((ASN1_BIT_STRING *)*pval, cout ? &cout : NULL);
// |i2c_ASN1_BIT_STRING| returns zero on error instead of -1.
return ret <= 0 ? -1 : ret;
return asn1_marshal_any(cbb, asn1_load_ptr_as<ASN1_TYPE>(pval));
case V_ASN1_OBJECT:
return asn1_marshal_object(cbb, asn1_load_ptr_as<ASN1_OBJECT>(pval), tag);
case V_ASN1_NULL:
tag = tag == 0 ? CBS_ASN1_NULL : tag;
return CBB_add_asn1_element(cbb, tag, nullptr, 0);
case V_ASN1_BOOLEAN: {
// `ASN1_BOOLEAN` is not a pointer type.
ASN1_BOOLEAN b = *reinterpret_cast<const ASN1_BOOLEAN *>(pval);
tag = tag == 0 ? CBS_ASN1_BOOLEAN : tag;
CBB child;
return CBB_add_asn1(cbb, &child, tag) &&
CBB_add_u8(&child, b ? 0xff : 0x00) && //
CBB_flush(cbb);
}
}
// All other supported types are represented as strings.
const ASN1_STRING *str = asn1_load_ptr_as<ASN1_STRING>(pval);
switch (it->utype) {
case V_ASN1_BIT_STRING:
return asn1_marshal_bit_string(cbb, str, tag);
case V_ASN1_INTEGER:
case V_ASN1_ENUMERATED: {
// |i2c_ASN1_INTEGER| also handles ENUMERATED.
int ret = i2c_ASN1_INTEGER((ASN1_INTEGER *)*pval, cout ? &cout : NULL);
// |i2c_ASN1_INTEGER| returns zero on error instead of -1.
return ret <= 0 ? -1 : ret;
}
return asn1_marshal_integer(cbb, str, tag);
case V_ASN1_ENUMERATED:
tag = tag == 0 ? CBS_ASN1_ENUMERATED : tag;
return asn1_marshal_integer(cbb, str, tag);
case V_ASN1_OCTET_STRING:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
@@ -640,25 +335,14 @@ static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *out_omit,
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
tag = tag == 0 ? static_cast<CBS_ASN1_TAG>(it->utype) : tag;
return asn1_marshal_octet_string(cbb, str, tag);
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.
// The `ASN1_SEQUENCE` item stores the entire element.
return CBB_add_bytes(cbb, ASN1_STRING_get0_data(str),
ASN1_STRING_length(str));
default:
// All based on ASN1_STRING and handled the same
strtmp = (ASN1_STRING *)*pval;
cont = strtmp->data;
len = strtmp->length;
break;
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return 0;
}
if (cout && len) {
OPENSSL_memcpy(cout, cont, len);
}
return len;
}
+43 -39
View File
@@ -1,11 +1,16 @@
/*
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -16,17 +21,20 @@
#include "internal.h"
using namespace bssl;
// Free up an ASN1 structure
void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it) {
ASN1_item_ex_free(&val, it);
}
void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
void bssl::ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
if (!pval) {
return;
}
if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !*pval) {
if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !asn1_load_ptr(pval)) {
return;
}
@@ -45,9 +53,9 @@ void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
case ASN1_ITYPE_CHOICE: {
const ASN1_AUX *aux = reinterpret_cast<const ASN1_AUX *>(it->funcs);
ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr;
if (asn1_cb) {
if (asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL) == 2) {
if (asn1_cb(ASN1_OP_FREE_PRE, pval, it, nullptr) == 2) {
return;
}
}
@@ -58,10 +66,10 @@ void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
ASN1_template_free(pchval, tt);
}
if (asn1_cb) {
asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL);
asn1_cb(ASN1_OP_FREE_POST, pval, it, nullptr);
}
OPENSSL_free(*pval);
*pval = NULL;
OPENSSL_free(asn1_load_ptr(pval));
asn1_store_ptr(pval, nullptr);
break;
}
@@ -79,15 +87,15 @@ void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
return;
}
const ASN1_AUX *aux = reinterpret_cast<const ASN1_AUX *>(it->funcs);
ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr;
if (asn1_cb) {
if (asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL) == 2) {
if (asn1_cb(ASN1_OP_FREE_PRE, pval, it, nullptr) == 2) {
return;
}
}
asn1_enc_free(pval, it);
// If we free up as normal we will invalidate any ANY DEFINED BY
// field and we wont be able to determine the type of the field it
// field and we won't be able to determine the type of the field it
// defines. So free up in reverse order.
for (int i = it->tcount - 1; i >= 0; i--) {
const ASN1_TEMPLATE *seqtt = asn1_do_adb(pval, &it->templates[i], 0);
@@ -98,45 +106,46 @@ void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
ASN1_template_free(pseqval, seqtt);
}
if (asn1_cb) {
asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL);
asn1_cb(ASN1_OP_FREE_POST, pval, it, nullptr);
}
OPENSSL_free(*pval);
*pval = NULL;
OPENSSL_free(asn1_load_ptr(pval));
asn1_store_ptr(pval, nullptr);
break;
}
}
}
void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) {
void bssl::ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) {
if (tt->flags & ASN1_TFLG_SK_MASK) {
STACK_OF(ASN1_VALUE) *sk = (STACK_OF(ASN1_VALUE) *)*pval;
STACK_OF(ASN1_VALUE) *sk = asn1_load_ptr_as<STACK_OF(ASN1_VALUE)>(pval);
for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
ASN1_VALUE *vtmp = sk_ASN1_VALUE_value(sk, i);
ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item));
}
sk_ASN1_VALUE_free(sk);
*pval = NULL;
asn1_store_ptr(pval, nullptr);
} else {
ASN1_item_ex_free(pval, ASN1_ITEM_ptr(tt->item));
}
}
void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
// Historically, |it->funcs| for primitive types contained an
// |ASN1_PRIMITIVE_FUNCS| table of calbacks.
assert(it->funcs == NULL);
void bssl::ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
// Historically, `it->funcs` for primitive types contained an
// `ASN1_PRIMITIVE_FUNCS` table of callbacks.
assert(it->funcs == nullptr);
int utype = it->itype == ASN1_ITYPE_MSTRING ? -1 : it->utype;
switch (utype) {
case V_ASN1_OBJECT:
ASN1_OBJECT_free((ASN1_OBJECT *)*pval);
ASN1_OBJECT_free(asn1_load_ptr_as<ASN1_OBJECT>(pval));
break;
case V_ASN1_BOOLEAN:
if (it) {
*(ASN1_BOOLEAN *)pval = (ASN1_BOOLEAN)it->size;
*reinterpret_cast<ASN1_BOOLEAN *>(pval) =
static_cast<ASN1_BOOLEAN>(it->size);
} else {
*(ASN1_BOOLEAN *)pval = ASN1_BOOLEAN_NONE;
*reinterpret_cast<ASN1_BOOLEAN *>(pval) = ASN1_BOOLEAN_NONE;
}
return;
@@ -144,16 +153,11 @@ void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
break;
case V_ASN1_ANY:
if (*pval != NULL) {
asn1_type_cleanup((ASN1_TYPE *)*pval);
OPENSSL_free(*pval);
}
ASN1_TYPE_free(asn1_load_ptr_as<ASN1_TYPE>(pval));
break;
default:
ASN1_STRING_free((ASN1_STRING *)*pval);
*pval = NULL;
break;
ASN1_STRING_free(asn1_load_ptr_as<ASN1_STRING>(pval));
}
*pval = NULL;
asn1_store_ptr(pval, nullptr);
}
+63 -60
View File
@@ -1,11 +1,16 @@
/*
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -17,9 +22,12 @@
#include <CNIOBoringSSL_obj.h>
#include "../internal.h"
#include "../mem_internal.h"
#include "internal.h"
using namespace bssl;
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);
@@ -27,17 +35,17 @@ static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
static void asn1_primitive_clear(ASN1_VALUE **pval, const ASN1_ITEM *it);
ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it) {
ASN1_VALUE *ret = NULL;
ASN1_VALUE *ret = nullptr;
if (ASN1_item_ex_new(&ret, it) > 0) {
return ret;
}
return NULL;
return nullptr;
}
// Allocate an ASN1 structure
int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
const ASN1_TEMPLATE *tt = NULL;
int bssl::ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
const ASN1_TEMPLATE *tt = nullptr;
const ASN1_EXTERN_FUNCS *ef;
ASN1_VALUE **pseqval;
int i;
@@ -70,9 +78,9 @@ int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
case ASN1_ITYPE_CHOICE: {
const ASN1_AUX *aux = reinterpret_cast<const ASN1_AUX *>(it->funcs);
ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr;
if (asn1_cb) {
i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, NULL);
i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, nullptr);
if (!i) {
goto auxerr;
}
@@ -80,12 +88,13 @@ int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
return 1;
}
}
*pval = reinterpret_cast<ASN1_VALUE *>(OPENSSL_zalloc(it->size));
if (!*pval) {
void *obj = OPENSSL_zalloc(it->size);
if (obj == nullptr) {
goto memerr;
}
asn1_store_ptr(pval, obj);
asn1_set_choice_selector(pval, -1, it);
if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL)) {
if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, nullptr)) {
goto auxerr2;
}
break;
@@ -93,9 +102,9 @@ int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
case ASN1_ITYPE_SEQUENCE: {
const ASN1_AUX *aux = reinterpret_cast<const ASN1_AUX *>(it->funcs);
ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr;
if (asn1_cb) {
i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, NULL);
i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, nullptr);
if (!i) {
goto auxerr;
}
@@ -103,10 +112,11 @@ int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
return 1;
}
}
*pval = reinterpret_cast<ASN1_VALUE *>(OPENSSL_zalloc(it->size));
if (!*pval) {
void *obj = OPENSSL_zalloc(it->size);
if (obj == nullptr) {
goto memerr;
}
asn1_store_ptr(pval, obj);
asn1_refcount_set_one(pval, it);
asn1_enc_init(pval, it);
for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) {
@@ -115,7 +125,7 @@ int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
goto memerr2;
}
}
if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL)) {
if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, nullptr)) {
goto auxerr2;
}
break;
@@ -138,7 +148,7 @@ auxerr:
static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) {
switch (it->itype) {
case ASN1_ITYPE_EXTERN:
*pval = NULL;
asn1_store_ptr(pval, nullptr);
break;
case ASN1_ITYPE_PRIMITIVE:
@@ -155,46 +165,39 @@ static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) {
case ASN1_ITYPE_CHOICE:
case ASN1_ITYPE_SEQUENCE:
*pval = NULL;
asn1_store_ptr(pval, nullptr);
break;
}
}
static int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) {
const ASN1_ITEM *it = ASN1_ITEM_ptr(tt->item);
int ret;
if (tt->flags & ASN1_TFLG_OPTIONAL) {
asn1_template_clear(pval, tt);
return 1;
}
// If ANY DEFINED BY nothing to do
// If ANY DEFINED BY, there is nothing to do.
if (tt->flags & ASN1_TFLG_ADB_MASK) {
*pval = NULL;
asn1_store_ptr(pval, nullptr);
return 1;
}
// If SET OF or SEQUENCE OF, its a STACK
// If SET OF or SEQUENCE OF, it's a STACK.
if (tt->flags & ASN1_TFLG_SK_MASK) {
STACK_OF(ASN1_VALUE) *skval;
skval = sk_ASN1_VALUE_new_null();
STACK_OF(ASN1_VALUE) *skval = sk_ASN1_VALUE_new_null();
if (!skval) {
ret = 0;
goto done;
return 0;
}
*pval = (ASN1_VALUE *)skval;
ret = 1;
goto done;
asn1_store_ptr(pval, skval);
return 1;
}
// Otherwise pass it back to the item routine
ret = ASN1_item_ex_new(pval, it);
done:
return ret;
// Otherwise, pass it back to the item routine.
return ASN1_item_ex_new(pval, it);
}
static void asn1_template_clear(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) {
// If ADB or STACK just NULL the field
// If ADB or STACK, just NULL the field.
if (tt->flags & (ASN1_TFLG_ADB_MASK | ASN1_TFLG_SK_MASK)) {
*pval = NULL;
asn1_store_ptr(pval, nullptr);
} else {
asn1_item_clear(pval, ASN1_ITEM_ptr(tt->item));
}
@@ -208,9 +211,9 @@ static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
return 0;
}
// Historically, |it->funcs| for primitive types contained an
// |ASN1_PRIMITIVE_FUNCS| table of calbacks.
assert(it->funcs == NULL);
// Historically, `it->funcs` for primitive types contained an
// `ASN1_PRIMITIVE_FUNCS` table of callbacks.
assert(it->funcs == nullptr);
int utype;
if (it->itype == ASN1_ITYPE_MSTRING) {
@@ -220,34 +223,32 @@ static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
}
switch (utype) {
case V_ASN1_OBJECT:
*pval = (ASN1_VALUE *)OBJ_get_undef();
asn1_store_ptr(pval, OBJ_get_undef());
return 1;
case V_ASN1_BOOLEAN:
*(ASN1_BOOLEAN *)pval = (ASN1_BOOLEAN)it->size;
*reinterpret_cast<ASN1_BOOLEAN *>(pval) =
static_cast<ASN1_BOOLEAN>(it->size);
return 1;
case V_ASN1_NULL:
*pval = (ASN1_VALUE *)1;
asn1_store_ptr(pval, reinterpret_cast<ASN1_VALUE *>(1));
return 1;
case V_ASN1_ANY: {
ASN1_TYPE *typ =
reinterpret_cast<ASN1_TYPE *>(OPENSSL_malloc(sizeof(ASN1_TYPE)));
ASN1_TYPE *typ = ASN1_TYPE_new();
if (!typ) {
return 0;
}
typ->value.ptr = NULL;
typ->type = -1;
*pval = (ASN1_VALUE *)typ;
asn1_store_ptr(pval, typ);
break;
}
default:
*pval = (ASN1_VALUE *)ASN1_STRING_type_new(utype);
asn1_store_ptr(pval, ASN1_STRING_type_new(utype));
break;
}
if (*pval) {
if (asn1_load_ptr(pval)) {
return 1;
}
return 0;
@@ -255,17 +256,19 @@ static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
static void asn1_primitive_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) {
int utype;
// Historically, |it->funcs| for primitive types contained an
// |ASN1_PRIMITIVE_FUNCS| table of calbacks.
assert(it == NULL || it->funcs == NULL);
// Historically, `it->funcs` for primitive types contained an
// `ASN1_PRIMITIVE_FUNCS` table of callbacks.
assert(it == nullptr || it->funcs == nullptr);
if (!it || (it->itype == ASN1_ITYPE_MSTRING)) {
utype = -1;
} else {
utype = it->utype;
}
if (utype == V_ASN1_BOOLEAN) {
*(ASN1_BOOLEAN *)pval = (ASN1_BOOLEAN)it->size;
// `ASN1_BOOLEAN` is not a pointer type.
*reinterpret_cast<ASN1_BOOLEAN *>(pval) =
static_cast<ASN1_BOOLEAN>(it->size);
} else {
*pval = NULL;
asn1_store_ptr(pval, nullptr);
}
}
+33 -20
View File
@@ -1,22 +1,33 @@
/*
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
#include <CNIOBoringSSL_asn1t.h>
// Declarations for string types
#include "internal.h"
#define IMPLEMENT_ASN1_STRING_FUNCTIONS(sname) \
IMPLEMENT_ASN1_TYPE(sname) \
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(sname, sname, sname) \
sname *sname##_new(void) { return ASN1_STRING_type_new(V_##sname); } \
using namespace bssl;
// TODO(crbug.com/42290417): While we need `ASN1_ITEM`s, the exposed new, free,
// i2d, and d2i functions should call the underlying implementations directly.
#define IMPLEMENT_ASN1_STRING_FUNCTIONS(sname) \
IMPLEMENT_ASN1_TYPE(sname) \
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(sname, sname, sname) \
sname *sname##_new() { return ASN1_STRING_type_new(V_##sname); } \
void sname##_free(sname *x) { ASN1_STRING_free(x); }
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_OCTET_STRING)
@@ -44,18 +55,20 @@ IMPLEMENT_ASN1_TYPE(ASN1_ANY)
// Just swallow an ASN1_SEQUENCE in an ASN1_STRING
IMPLEMENT_ASN1_TYPE(ASN1_SEQUENCE)
IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE)
// Multistring types
IMPLEMENT_ASN1_MSTRING(ASN1_PRINTABLE, B_ASN1_PRINTABLE)
IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_STRING, ASN1_PRINTABLE,
ASN1_PRINTABLE)
BSSL_NAMESPACE_BEGIN
IMPLEMENT_ASN1_MSTRING(DISPLAYTEXT, B_ASN1_DISPLAYTEXT)
BSSL_NAMESPACE_END
IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_STRING, DISPLAYTEXT, DISPLAYTEXT)
BSSL_NAMESPACE_BEGIN
IMPLEMENT_ASN1_MSTRING(DIRECTORYSTRING, B_ASN1_DIRECTORYSTRING)
BSSL_NAMESPACE_END
IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_STRING, DIRECTORYSTRING,
DIRECTORYSTRING)
+76 -82
View File
@@ -1,11 +1,16 @@
/*
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
@@ -17,28 +22,30 @@
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_obj.h>
#include <CNIOBoringSSL_pool.h>
#include <CNIOBoringSSL_thread.h>
#include "../internal.h"
#include "internal.h"
using namespace bssl;
// Utility functions for manipulating fields and offsets
// Add 'offset' to 'addr'
#define offset2ptr(addr, offset) (void *)(((char *)(addr)) + (offset))
// Given an ASN1_ITEM CHOICE type return the selector value
int asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it) {
int *sel = reinterpret_cast<int *>(offset2ptr(*pval, it->utype));
int bssl::asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it) {
int *sel =
reinterpret_cast<int *>(offset2ptr(asn1_load_ptr(pval), it->utype));
return *sel;
}
// Given an ASN1_ITEM CHOICE type set the selector value, return old value.
int asn1_set_choice_selector(ASN1_VALUE **pval, int value,
const ASN1_ITEM *it) {
int bssl::asn1_set_choice_selector(ASN1_VALUE **pval, int value,
const ASN1_ITEM *it) {
int *sel, ret;
sel = reinterpret_cast<int *>(offset2ptr(*pval, it->utype));
sel = reinterpret_cast<int *>(offset2ptr(asn1_load_ptr(pval), it->utype));
ret = *sel;
*sel = value;
return ret;
@@ -47,26 +54,27 @@ int asn1_set_choice_selector(ASN1_VALUE **pval, int value,
static CRYPTO_refcount_t *asn1_get_references(ASN1_VALUE **pval,
const ASN1_ITEM *it) {
if (it->itype != ASN1_ITYPE_SEQUENCE) {
return NULL;
return nullptr;
}
const ASN1_AUX *aux = reinterpret_cast<const ASN1_AUX *>(it->funcs);
if (!aux || !(aux->flags & ASN1_AFLG_REFCOUNT)) {
return NULL;
return nullptr;
}
return reinterpret_cast<CRYPTO_refcount_t *>(
offset2ptr(*pval, aux->ref_offset));
offset2ptr(asn1_load_ptr(pval), aux->ref_offset));
}
void asn1_refcount_set_one(ASN1_VALUE **pval, const ASN1_ITEM *it) {
void bssl::asn1_refcount_set_one(ASN1_VALUE **pval, const ASN1_ITEM *it) {
CRYPTO_refcount_t *references = asn1_get_references(pval, it);
if (references != NULL) {
if (references != nullptr) {
*references = 1;
}
}
int asn1_refcount_dec_and_test_zero(ASN1_VALUE **pval, const ASN1_ITEM *it) {
int bssl::asn1_refcount_dec_and_test_zero(ASN1_VALUE **pval,
const ASN1_ITEM *it) {
CRYPTO_refcount_t *references = asn1_get_references(pval, it);
if (references != NULL) {
if (references != nullptr) {
return CRYPTO_refcount_dec_and_test_zero(references);
}
return 1;
@@ -75,34 +83,34 @@ int asn1_refcount_dec_and_test_zero(ASN1_VALUE **pval, const ASN1_ITEM *it) {
static ASN1_ENCODING *asn1_get_enc_ptr(ASN1_VALUE **pval, const ASN1_ITEM *it) {
assert(it->itype == ASN1_ITYPE_SEQUENCE);
const ASN1_AUX *aux;
if (!pval || !*pval) {
return NULL;
if (!pval || !asn1_load_ptr(pval)) {
return nullptr;
}
aux = reinterpret_cast<const ASN1_AUX *>(it->funcs);
if (!aux || !(aux->flags & ASN1_AFLG_ENCODING)) {
return NULL;
return nullptr;
}
return reinterpret_cast<ASN1_ENCODING *>(offset2ptr(*pval, aux->enc_offset));
return reinterpret_cast<ASN1_ENCODING *>(
offset2ptr(asn1_load_ptr(pval), aux->enc_offset));
}
void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it) {
void bssl::asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it) {
ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it);
if (enc) {
enc->enc = NULL;
enc->enc = nullptr;
enc->len = 0;
enc->buf = NULL;
}
}
void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
void bssl::asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it);
if (enc) {
asn1_encoding_clear(enc);
}
}
int asn1_enc_save(ASN1_VALUE **pval, const uint8_t *in, size_t in_len,
const ASN1_ITEM *it, CRYPTO_BUFFER *buf) {
int bssl::asn1_enc_save(ASN1_VALUE **pval, const uint8_t *in, size_t in_len,
const ASN1_ITEM *it) {
ASN1_ENCODING *enc;
enc = asn1_get_enc_ptr(pval, it);
if (!enc) {
@@ -110,80 +118,55 @@ int asn1_enc_save(ASN1_VALUE **pval, const uint8_t *in, size_t in_len,
}
asn1_encoding_clear(enc);
if (buf != NULL) {
assert(CRYPTO_BUFFER_data(buf) <= in &&
in + in_len <= CRYPTO_BUFFER_data(buf) + CRYPTO_BUFFER_len(buf));
CRYPTO_BUFFER_up_ref(buf);
enc->buf = buf;
enc->enc = (uint8_t *)in;
} else {
enc->enc = reinterpret_cast<uint8_t *>(OPENSSL_memdup(in, in_len));
if (!enc->enc) {
return 0;
}
enc->enc = reinterpret_cast<uint8_t *>(OPENSSL_memdup(in, in_len));
if (!enc->enc) {
return 0;
}
enc->len = in_len;
return 1;
}
void asn1_encoding_clear(ASN1_ENCODING *enc) {
if (enc->buf != NULL) {
CRYPTO_BUFFER_free(enc->buf);
} else {
OPENSSL_free(enc->enc);
}
enc->enc = NULL;
void bssl::asn1_encoding_clear(ASN1_ENCODING *enc) {
OPENSSL_free(enc->enc);
enc->enc = nullptr;
enc->len = 0;
enc->buf = NULL;
}
int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval,
const ASN1_ITEM *it) {
int bssl::asn1_enc_restore(Span<const uint8_t> *out, ASN1_VALUE **pval,
const ASN1_ITEM *it) {
ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it);
if (!enc || enc->len == 0) {
return 0;
}
if (out) {
OPENSSL_memcpy(*out, enc->enc, enc->len);
*out += enc->len;
}
if (len) {
*len = enc->len;
}
*out = Span(enc->enc, enc->len);
return 1;
}
// 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 =
reinterpret_cast<ASN1_VALUE **>(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;
ASN1_VALUE **bssl::asn1_get_field_ptr(ASN1_VALUE **pval,
const ASN1_TEMPLATE *tt) {
return reinterpret_cast<ASN1_VALUE **>(
offset2ptr(asn1_load_ptr(pval), tt->offset));
}
// Handle ANY DEFINED BY template, find the selector, look up the relevant
// ASN1_TEMPLATE in the table and return it.
const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt,
int nullerr) {
const ASN1_ADB *adb;
const ASN1_ADB_TABLE *atbl;
ASN1_VALUE **sfld;
int i;
const ASN1_TEMPLATE *bssl::asn1_do_adb(ASN1_VALUE **pval,
const ASN1_TEMPLATE *tt, int nullerr) {
if (!(tt->flags & ASN1_TFLG_ADB_MASK)) {
return tt;
}
// Else ANY DEFINED BY ... get the table
adb = ASN1_ADB_ptr(tt->item);
const ASN1_ADB *adb = ASN1_ADB_ptr(tt->item);
// Get the selector field
sfld = reinterpret_cast<ASN1_VALUE **>(offset2ptr(*pval, adb->offset));
// Check if NULL
ASN1_VALUE **sfld = reinterpret_cast<ASN1_VALUE **>(
offset2ptr(asn1_load_ptr(pval), adb->offset));
int selector;
if (*sfld == NULL) {
const ASN1_OBJECT *selector_obj = asn1_load_ptr_as<ASN1_OBJECT>(sfld);
if (selector_obj == nullptr) {
if (!adb->null_tt) {
goto err;
}
@@ -194,21 +177,19 @@ const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt,
// NB: don't check for NID_undef here because it
// might be a legitimate value in the table
assert(tt->flags & ASN1_TFLG_ADB_OID);
selector = OBJ_obj2nid((ASN1_OBJECT *)*sfld);
selector = OBJ_obj2nid(asn1_load_ptr_as<ASN1_OBJECT>(sfld));
// Try to find matching entry in table Maybe should check application types
// first to allow application override? Might also be useful to have a flag
// which indicates table is sorted and we can do a binary search. For now
// stick to a linear search.
for (atbl = adb->tbl, i = 0; i < adb->tblcount; i++, atbl++) {
for (int i = 0; i < adb->tblcount; i++) {
const ASN1_ADB_TABLE *atbl = &adb->tbl[i];
if (atbl->value == selector) {
return &atbl->tt;
}
}
// FIXME: need to search application table too
// No match, return default type
if (!adb->default_tt) {
goto err;
@@ -220,5 +201,18 @@ err:
if (nullerr) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE);
}
return NULL;
return nullptr;
}
CBS_ASN1_TAG bssl::asn1_tag_to_cbs(int aclass, int tag) {
if ((aclass & ASN1_TFLG_TAG_CLASS) != aclass || //
tag < 0 || static_cast<CBS_ASN1_TAG>(tag) > CBS_ASN1_TAG_NUMBER_MASK ||
// Universal tag zero is reserved and should never appear in a template.
// This file treats the zero tag as a sentinel value.
(aclass == 0 && tag == 0)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return 0;
}
return ((static_cast<CBS_ASN1_TAG>(aclass)) << CBS_ASN1_TAG_SHIFT) |
static_cast<CBS_ASN1_TAG>(tag);
}
+27 -23
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_base64.h>
@@ -14,22 +19,24 @@
#include <string.h>
#include "../internal.h"
#include "../mem_internal.h"
// constant_time_lt_args_8 behaves like |constant_time_lt_8| but takes |uint8_t|
using namespace bssl;
// constant_time_lt_args_8 behaves like `constant_time_lt_8` but takes `uint8_t`
// arguments for a slightly simpler implementation.
static inline uint8_t constant_time_lt_args_8(uint8_t a, uint8_t b) {
static uint8_t constant_time_lt_args_8(uint8_t a, uint8_t b) {
crypto_word_t aw = a;
crypto_word_t bw = b;
// |crypto_word_t| is larger than |uint8_t|, so |aw| and |bw| have the same
// MSB. |aw| < |bw| iff MSB(|aw| - |bw|) is 1.
// `crypto_word_t` is larger than `uint8_t`, so `aw` and `bw` have the same
// MSB. `aw` < `bw` iff MSB(`aw` - `bw`) is 1.
return constant_time_msb_w(aw - bw);
}
// constant_time_in_range_8 returns |CONSTTIME_TRUE_8| if |min| <= |a| <= |max|
// and |CONSTTIME_FALSE_8| otherwise.
static inline uint8_t constant_time_in_range_8(uint8_t a, uint8_t min,
uint8_t max) {
// constant_time_in_range_8 returns `CONSTTIME_TRUE_8` if `min` <= `a` <= `max`
// and `CONSTTIME_FALSE_8` otherwise.
static uint8_t constant_time_in_range_8(uint8_t a, uint8_t min, uint8_t max) {
a -= min;
return constant_time_lt_args_8(a, max - min + 1);
}
@@ -49,7 +56,7 @@ static uint8_t conv_bin2ascii(uint8_t a) {
return ret;
}
static_assert(sizeof(((EVP_ENCODE_CTX *)(NULL))->data) % 3 == 0,
static_assert(sizeof(((EVP_ENCODE_CTX *)nullptr)->data) % 3 == 0,
"data length must be a multiple of base64 chunk size");
int EVP_EncodedLength(size_t *out_len, size_t len) {
@@ -73,12 +80,9 @@ int EVP_EncodedLength(size_t *out_len, size_t len) {
return 1;
}
EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void) {
return reinterpret_cast<EVP_ENCODE_CTX *>(
OPENSSL_zalloc(sizeof(EVP_ENCODE_CTX)));
}
EVP_ENCODE_CTX *EVP_ENCODE_CTX_new() { return New<EVP_ENCODE_CTX>(); }
void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx) { OPENSSL_free(ctx); }
void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx) { Delete(ctx); }
void EVP_EncodeInit(EVP_ENCODE_CTX *ctx) {
OPENSSL_memset(ctx, 0, sizeof(EVP_ENCODE_CTX));
@@ -238,7 +242,7 @@ static uint8_t base64_ascii_to_bin(uint8_t a) {
}
// base64_decode_quad decodes a single “quad” (i.e. four characters) of base64
// data and writes up to three bytes to |out|. It sets |*out_num_bytes| to the
// data and writes up to three bytes to `out`. It sets `*out_num_bytes` to the
// number of bytes written, which will be less than three if the quad ended
// with padding. It returns one on success or zero on error.
static int base64_decode_quad(uint8_t *out, size_t *out_num_bytes,
+20 -77
View File
@@ -1,16 +1,16 @@
/* Copyright 2024 The BoringSSL Authors
*
* 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. */
// Copyright 2024 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSSL_HEADER_CRYPTO_BCM_SUPPORT_H
#define OPENSSL_HEADER_CRYPTO_BCM_SUPPORT_H
@@ -19,73 +19,19 @@
#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
BSSL_NAMESPACE_BEGIN
// 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);
void CRYPTO_init_sysrand();
// CRYPTO_sysrand fills |len| bytes at |buf| with entropy from the operating
// 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
@@ -98,9 +44,9 @@ void RAND_need_entropy(size_t bytes_needed);
// 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
// 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);
OPENSSL_EXPORT uint64_t CRYPTO_get_fork_generation();
// CRYPTO_fork_detect_force_madv_wipeonfork_for_testing is an internal detail
// used for testing purposes.
@@ -109,11 +55,8 @@ OPENSSL_EXPORT void CRYPTO_fork_detect_force_madv_wipeonfork_for_testing(
// CRYPTO_get_stderr returns stderr. This function exists to avoid BCM needing
// a data dependency on libc.
FILE *CRYPTO_get_stderr(void);
FILE *CRYPTO_get_stderr();
#if defined(__cplusplus)
} // extern C
#endif
BSSL_NAMESPACE_END
#endif // OPENSSL_HEADER_CRYPTO_BCM_SUPPORT_H
+251 -189
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bio.h>
@@ -14,58 +19,58 @@
#include <limits.h>
#include <string.h>
#include <algorithm>
#include <utility>
#include <CNIOBoringSSL_asn1.h>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_thread.h>
#include <CNIOBoringSSL_span.h>
#include "../internal.h"
#include "../mem_internal.h"
#include "internal.h"
static CRYPTO_EX_DATA_CLASS g_ex_data_class =
CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA;
using namespace bssl;
static ExDataClass g_ex_data_class(/*with_app_data=*/true);
Bio::Bio(const BIO_METHOD *m) : RefCounted(CheckSubClass()), method(m) {
CRYPTO_new_ex_data(&ex_data);
}
BIO *BIO_new(const BIO_METHOD *method) {
BIO *ret = reinterpret_cast<BIO *>(OPENSSL_zalloc(sizeof(BIO)));
if (ret == NULL) {
return NULL;
UniquePtr<Bio> ret(New<Bio>(method));
if (ret == nullptr) {
return nullptr;
}
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);
return NULL;
if (method->create != nullptr && !method->create(ret.get())) {
return nullptr;
}
return ret;
return ret.release();
}
Bio::~Bio() {
BIO *next = BIO_pop(this);
if (method->destroy != nullptr) {
method->destroy(this);
}
CRYPTO_free_ex_data(&g_ex_data_class, &ex_data);
BIO_free(next);
}
int BIO_free(BIO *bio) {
BIO *next_bio;
for (; bio != NULL; bio = next_bio) {
if (!CRYPTO_refcount_dec_and_test_zero(&bio->references)) {
return 0;
}
next_bio = BIO_pop(bio);
if (bio->method != NULL && bio->method->destroy != NULL) {
bio->method->destroy(bio);
}
CRYPTO_free_ex_data(&g_ex_data_class, bio, &bio->ex_data);
OPENSSL_free(bio);
if (bio == nullptr) {
return 1;
}
return 1;
return FromOpaque(bio)->DecRefInternal();
}
int BIO_up_ref(BIO *bio) {
CRYPTO_refcount_inc(&bio->references);
FromOpaque(bio)->UpRefInternal();
return 1;
}
@@ -74,71 +79,108 @@ void BIO_vfree(BIO *bio) { BIO_free(bio); }
void BIO_free_all(BIO *bio) { BIO_free(bio); }
int BIO_read(BIO *bio, void *buf, int len) {
if (bio == NULL || bio->method == NULL || bio->method->bread == NULL) {
auto *impl = FromOpaque(bio);
if (impl == nullptr || impl->method->bread == nullptr) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
return -1;
}
if (!bio->init) {
if (!impl->init) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNINITIALIZED);
return -2;
return -1;
}
if (len <= 0) {
return 0;
}
int ret = bio->method->bread(bio, reinterpret_cast<char *>(buf), len);
int ret = impl->method->bread(impl, reinterpret_cast<char *>(buf), len);
if (ret > 0) {
bio->num_read += ret;
impl->num_read += ret;
} else if (ret < 0) {
// In preparation for |BIO_read_ex|, canonicalize error returns to -1.
ret = -1;
}
return ret;
}
int BIO_gets(BIO *bio, char *buf, int len) {
if (bio == NULL || bio->method == NULL || bio->method->bgets == NULL) {
auto *impl = FromOpaque(bio);
if (impl == nullptr || impl->method->bgets == nullptr) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
return -1;
}
if (!bio->init) {
if (!impl->init) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNINITIALIZED);
return -2;
return -1;
}
if (len <= 0) {
return 0;
}
int ret = bio->method->bgets(bio, buf, len);
int ret = impl->method->bgets(impl, buf, len);
if (ret > 0) {
bio->num_read += ret;
impl->num_read += ret;
}
return ret;
}
int BIO_write(BIO *bio, const void *in, int inl) {
if (bio == NULL || bio->method == NULL || bio->method->bwrite == NULL) {
int BIO_write_ex(BIO *bio, const void *data, size_t len, size_t *out_written) {
if (out_written != nullptr) {
*out_written = 0;
}
auto *impl = FromOpaque(bio);
if (impl == nullptr ||
(impl->method->bwrite == nullptr && impl->method->bwrite_ex == nullptr)) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
}
if (!bio->init) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNINITIALIZED);
return -2;
}
if (inl <= 0) {
return 0;
}
int ret = bio->method->bwrite(bio, reinterpret_cast<const char *>(in), inl);
if (ret > 0) {
bio->num_write += ret;
if (!impl->init) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNINITIALIZED);
return 0;
}
return ret;
}
int BIO_write_all(BIO *bio, const void *data, size_t len) {
const uint8_t *data_u8 = reinterpret_cast<const uint8_t *>(data);
while (len > 0) {
int ret = BIO_write(bio, data_u8, len > INT_MAX ? INT_MAX : (int)len);
// Matching OpenSSL, writing zero bytes should "successfully" write no bytes.
if (len == 0) {
return 1;
}
// Support `BIO_METHOD`s using either the old or new API.
size_t written;
if (impl->method->bwrite_ex != nullptr) {
if (!impl->method->bwrite_ex(bio, static_cast<const char *>(data), len,
&written)) {
return 0;
}
} else {
int ret =
impl->method->bwrite(impl, static_cast<const char *>(data),
static_cast<int>(std::min(len, size_t{INT_MAX})));
if (ret <= 0) {
return 0;
}
data_u8 += ret;
len -= ret;
written = static_cast<size_t>(ret);
}
impl->num_write += written;
if (out_written != nullptr) {
*out_written = written;
}
return 1;
}
int BIO_write(BIO *bio, const void *in, int inl) {
// Matching OpenSSL, `inl <= 0` returns zero, i.e. a "successful" write of
// zero bytes.
inl = std::max(inl, 0);
size_t written;
if (!BIO_write_ex(bio, in, static_cast<size_t>(inl), &written)) {
return -1;
}
return static_cast<int>(written);
}
int BIO_write_all(BIO *bio, const void *data, size_t len) {
auto span = Span(reinterpret_cast<const uint8_t *>(data), len);
while (!span.empty()) {
size_t written;
if (!BIO_write_ex(bio, span.data(), span.size(), &written)) {
return 0;
}
span = span.subspan(written);
}
return 1;
}
@@ -146,33 +188,36 @@ int BIO_write_all(BIO *bio, const void *data, size_t len) {
int BIO_puts(BIO *bio, const char *in) {
size_t len = strlen(in);
if (len > INT_MAX) {
// |BIO_write| and the return value both assume the string fits in |int|.
// `BIO_write` and the return value both assume the string fits in `int`.
OPENSSL_PUT_ERROR(BIO, ERR_R_OVERFLOW);
return -1;
}
return BIO_write(bio, in, (int)len);
}
int BIO_flush(BIO *bio) { return (int)BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, NULL); }
int BIO_flush(BIO *bio) {
return (int)BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, nullptr);
}
long BIO_ctrl(BIO *bio, int cmd, long larg, void *parg) {
if (bio == NULL) {
auto *impl = FromOpaque(bio);
if (impl == nullptr) {
return 0;
}
if (bio->method == NULL || bio->method->ctrl == NULL) {
if (impl->method->ctrl == nullptr) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
return -1;
}
return bio->method->ctrl(bio, cmd, larg, parg);
return impl->method->ctrl(impl, cmd, larg, parg);
}
char *BIO_ptr_ctrl(BIO *b, int cmd, long larg) {
char *p = NULL;
char *p = nullptr;
if (BIO_ctrl(b, cmd, larg, (void *)&p) <= 0) {
return NULL;
return nullptr;
}
return p;
@@ -184,13 +229,17 @@ long BIO_int_ctrl(BIO *b, int cmd, long larg, int iarg) {
return BIO_ctrl(b, cmd, larg, (void *)&i);
}
int BIO_reset(BIO *bio) { return (int)BIO_ctrl(bio, BIO_CTRL_RESET, 0, NULL); }
int BIO_reset(BIO *bio) {
return (int)BIO_ctrl(bio, BIO_CTRL_RESET, 0, nullptr);
}
int BIO_eof(BIO *bio) { return (int)BIO_ctrl(bio, BIO_CTRL_EOF, 0, NULL); }
int BIO_eof(BIO *bio) { return (int)BIO_ctrl(bio, BIO_CTRL_EOF, 0, nullptr); }
void BIO_set_flags(BIO *bio, int flags) { bio->flags |= flags; }
void BIO_set_flags(BIO *bio, int flags) { FromOpaque(bio)->flags |= flags; }
int BIO_test_flags(const BIO *bio, int flags) { return bio->flags & flags; }
int BIO_test_flags(const BIO *bio, int flags) {
return FromOpaque(bio)->flags & flags;
}
int BIO_should_read(const BIO *bio) {
return BIO_test_flags(bio, BIO_FLAGS_READ);
@@ -208,52 +257,67 @@ int BIO_should_io_special(const BIO *bio) {
return BIO_test_flags(bio, BIO_FLAGS_IO_SPECIAL);
}
int BIO_get_retry_reason(const BIO *bio) { return bio->retry_reason; }
int BIO_get_retry_reason(const BIO *bio) {
return FromOpaque(bio)->retry_reason;
}
void BIO_set_retry_reason(BIO *bio, int reason) { bio->retry_reason = reason; }
void BIO_set_retry_reason(BIO *bio, int reason) {
FromOpaque(bio)->retry_reason = reason;
}
void BIO_clear_flags(BIO *bio, int flags) { bio->flags &= ~flags; }
void BIO_clear_flags(BIO *bio, int flags) { FromOpaque(bio)->flags &= ~flags; }
void BIO_set_retry_read(BIO *bio) {
bio->flags |= BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY;
FromOpaque(bio)->flags |= BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY;
}
void BIO_set_retry_write(BIO *bio) {
bio->flags |= BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY;
FromOpaque(bio)->flags |= BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY;
}
void BIO_set_retry_special(BIO *bio) {
FromOpaque(bio)->flags |= BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY;
}
static const int kRetryFlags = BIO_FLAGS_RWS | BIO_FLAGS_SHOULD_RETRY;
int BIO_get_retry_flags(BIO *bio) { return bio->flags & kRetryFlags; }
int BIO_get_retry_flags(BIO *bio) {
return FromOpaque(bio)->flags & kRetryFlags;
}
void BIO_clear_retry_flags(BIO *bio) {
bio->flags &= ~kRetryFlags;
bio->retry_reason = 0;
auto *impl = FromOpaque(bio);
impl->flags &= ~kRetryFlags;
impl->retry_reason = 0;
}
int BIO_method_type(const BIO *bio) { return bio->method->type; }
int BIO_method_type(const BIO *bio) {
return FromOpaque(bio)->method->type;
}
void BIO_copy_next_retry(BIO *bio) {
BIO_clear_retry_flags(bio);
BIO_set_flags(bio, BIO_get_retry_flags(bio->next_bio));
bio->retry_reason = bio->next_bio->retry_reason;
auto *impl = FromOpaque(bio);
BIO_clear_retry_flags(impl);
BIO_set_flags(impl, BIO_get_retry_flags(impl->next_bio));
impl->retry_reason = impl->next_bio->retry_reason;
}
long BIO_callback_ctrl(BIO *bio, int cmd, bio_info_cb fp) {
if (bio == NULL) {
long BIO_callback_ctrl(BIO *bio, int cmd, BIO_info_cb *fp) {
auto *impl = FromOpaque(bio);
if (impl == nullptr) {
return 0;
}
if (bio->method == NULL || bio->method->callback_ctrl == NULL) {
if (impl->method->callback_ctrl == nullptr) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD);
return 0;
}
return bio->method->callback_ctrl(bio, cmd, fp);
return impl->method->callback_ctrl(impl, cmd, fp);
}
size_t BIO_pending(const BIO *bio) {
const long r = BIO_ctrl((BIO *)bio, BIO_CTRL_PENDING, 0, NULL);
const long r = BIO_ctrl(const_cast<BIO *>(bio), BIO_CTRL_PENDING, 0, nullptr);
assert(r >= 0);
if (r < 0) {
@@ -265,7 +329,8 @@ size_t BIO_pending(const BIO *bio) {
size_t BIO_ctrl_pending(const BIO *bio) { return BIO_pending(bio); }
size_t BIO_wpending(const BIO *bio) {
const long r = BIO_ctrl((BIO *)bio, BIO_CTRL_WPENDING, 0, NULL);
const long r =
BIO_ctrl(const_cast<BIO *>(bio), BIO_CTRL_WPENDING, 0, nullptr);
assert(r >= 0);
if (r < 0) {
@@ -275,75 +340,62 @@ size_t BIO_wpending(const BIO *bio) {
}
int BIO_set_close(BIO *bio, int close_flag) {
return (int)BIO_ctrl(bio, BIO_CTRL_SET_CLOSE, close_flag, NULL);
return (int)BIO_ctrl(bio, BIO_CTRL_SET_CLOSE, close_flag, nullptr);
}
OPENSSL_EXPORT uint64_t BIO_number_read(const BIO *bio) {
return bio->num_read;
}
uint64_t BIO_number_read(const BIO *bio) { return FromOpaque(bio)->num_read; }
OPENSSL_EXPORT uint64_t BIO_number_written(const BIO *bio) {
return bio->num_write;
uint64_t BIO_number_written(const BIO *bio) {
return FromOpaque(bio)->num_write;
}
BIO *BIO_push(BIO *bio, BIO *appended_bio) {
BIO *last_bio;
if (bio == NULL) {
if (bio == nullptr) {
return bio;
}
last_bio = bio;
while (last_bio->next_bio != NULL) {
Bio *last_bio = FromOpaque(bio);
while (last_bio->next_bio != nullptr) {
last_bio = last_bio->next_bio;
}
last_bio->next_bio = appended_bio;
last_bio->next_bio = FromOpaque(appended_bio);
return bio;
}
BIO *BIO_pop(BIO *bio) {
BIO *ret;
if (bio == NULL) {
return NULL;
if (bio == nullptr) {
return nullptr;
}
ret = bio->next_bio;
bio->next_bio = NULL;
return ret;
return std::exchange(FromOpaque(bio)->next_bio, nullptr);
}
BIO *BIO_next(BIO *bio) {
if (!bio) {
return NULL;
return nullptr;
}
return bio->next_bio;
return FromOpaque(bio)->next_bio;
}
BIO *BIO_find_type(BIO *bio, int type) {
int method_type, mask;
if (!bio) {
return NULL;
return nullptr;
}
mask = type & 0xff;
int mask = type & 0xff;
do {
if (bio->method != NULL) {
method_type = bio->method->type;
if (!mask) {
if (method_type & type) {
return bio;
}
} else if (method_type == type) {
int method_type = BIO_method_type(bio);
if (!mask) {
if (method_type & type) {
return bio;
}
} else if (method_type == type) {
return bio;
}
bio = bio->next_bio;
} while (bio != NULL);
bio = BIO_next(bio);
} while (bio != nullptr);
return NULL;
return nullptr;
}
int BIO_indent(BIO *bio, unsigned indent, unsigned max_indent) {
@@ -365,15 +417,15 @@ static int print_bio(const char *str, size_t len, void *bio) {
void ERR_print_errors(BIO *bio) { ERR_print_errors_cb(print_bio, bio); }
// bio_read_all reads everything from |bio| and prepends |prefix| to it. On
// success, |*out| is set to an allocated buffer (which should be freed with
// |OPENSSL_free|), |*out_len| is set to its length and one is returned. The
// buffer will contain |prefix| followed by the contents of |bio|. On failure,
// bio_read_all reads everything from `bio` and prepends `prefix` to it. On
// success, `*out` is set to an allocated buffer (which should be freed with
// `OPENSSL_free`), `*out_len` is set to its length and one is returned. The
// buffer will contain `prefix` followed by the contents of `bio`. On failure,
// zero is returned.
//
// The function will fail if the size of the output would equal or exceed
// |max_len|.
static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len,
// `max_len`.
static int bio_read_all(Bio *bio, uint8_t **out, size_t *out_len,
const uint8_t *prefix, size_t prefix_len,
size_t max_len) {
static const size_t kChunkSize = 4096;
@@ -386,7 +438,7 @@ static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len,
return 0;
}
*out = reinterpret_cast<uint8_t *>(OPENSSL_malloc(len));
if (*out == NULL) {
if (*out == nullptr) {
return 0;
}
OPENSSL_memcpy(*out, prefix, prefix_len);
@@ -405,7 +457,7 @@ static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len,
if (n == 0) {
*out_len = done;
return 1;
} else if (n == -1) {
} else if (n < 0) {
OPENSSL_free(*out);
return 0;
}
@@ -418,7 +470,7 @@ static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len,
}
uint8_t *new_buf =
reinterpret_cast<uint8_t *>(OPENSSL_realloc(*out, len));
if (new_buf == NULL) {
if (new_buf == nullptr) {
OPENSSL_free(*out);
return 0;
}
@@ -427,19 +479,19 @@ static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len,
}
}
// bio_read_full reads |len| bytes |bio| and writes them into |out|. It
// tolerates partial reads from |bio| and returns one on success or zero if a
// read fails before |len| bytes are read. On failure, it additionally sets
// |*out_eof_on_first_read| to whether the error was due to |bio| returning zero
// on the first read. |out_eof_on_first_read| may be NULL to discard the value.
static int bio_read_full(BIO *bio, uint8_t *out, int *out_eof_on_first_read,
// bio_read_full reads `len` bytes `bio` and writes them into `out`. It
// tolerates partial reads from `bio` and returns one on success or zero if a
// read fails before `len` bytes are read. On failure, it additionally sets
// `*out_eof_on_first_read` to whether the error was due to `bio` returning zero
// on the first read. `out_eof_on_first_read` may be NULL to discard the value.
static int bio_read_full(Bio *bio, uint8_t *out, int *out_eof_on_first_read,
size_t len) {
int first_read = 1;
while (len > 0) {
int todo = len <= INT_MAX ? (int)len : INT_MAX;
int ret = BIO_read(bio, out, todo);
if (ret <= 0) {
if (out_eof_on_first_read != NULL) {
if (out_eof_on_first_read != nullptr) {
*out_eof_on_first_read = first_read && ret == 0;
}
return 0;
@@ -452,8 +504,8 @@ static int bio_read_full(BIO *bio, uint8_t *out, int *out_eof_on_first_read,
return 1;
}
// For compatibility with existing |d2i_*_bio| callers, |BIO_read_asn1| uses
// |ERR_LIB_ASN1| errors.
// For compatibility with existing `d2i_*_bio` callers, `BIO_read_asn1` uses
// `ERR_LIB_ASN1` errors.
OPENSSL_DECLARE_ERROR_REASON(ASN1, ASN1_R_DECODE_ERROR)
OPENSSL_DECLARE_ERROR_REASON(ASN1, ASN1_R_HEADER_TOO_LONG)
OPENSSL_DECLARE_ERROR_REASON(ASN1, ASN1_R_NOT_ENOUGH_DATA)
@@ -464,11 +516,12 @@ int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) {
static const size_t kInitialHeaderLen = 2;
int eof_on_first_read;
if (!bio_read_full(bio, header, &eof_on_first_read, kInitialHeaderLen)) {
auto *impl = FromOpaque(bio);
if (!bio_read_full(impl, header, &eof_on_first_read, kInitialHeaderLen)) {
if (eof_on_first_read) {
// Historically, OpenSSL returned |ASN1_R_HEADER_TOO_LONG| when
// |d2i_*_bio| could not read anything. CPython conditions on this to
// determine if |bio| was empty.
// Historically, OpenSSL returned `ASN1_R_HEADER_TOO_LONG` when
// `d2i_*_bio` could not read anything. CPython conditions on this to
// determine if `bio` was empty.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_HEADER_TOO_LONG);
} else {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA);
@@ -495,7 +548,7 @@ int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) {
if ((tag & 0x20 /* constructed */) != 0 && num_bytes == 0) {
// indefinite length.
if (!bio_read_all(bio, out, out_len, header, kInitialHeaderLen,
if (!bio_read_all(impl, out, out_len, header, kInitialHeaderLen,
max_len)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA);
return 0;
@@ -508,7 +561,7 @@ int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) {
return 0;
}
if (!bio_read_full(bio, header + kInitialHeaderLen, NULL, num_bytes)) {
if (!bio_read_full(impl, header + kInitialHeaderLen, nullptr, num_bytes)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA);
return 0;
}
@@ -543,11 +596,11 @@ int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) {
*out_len = len;
*out = reinterpret_cast<uint8_t *>(OPENSSL_malloc(len));
if (*out == NULL) {
if (*out == nullptr) {
return 0;
}
OPENSSL_memcpy(*out, header, header_len);
if (!bio_read_full(bio, (*out) + header_len, NULL, len - header_len)) {
if (!bio_read_full(impl, (*out) + header_len, nullptr, len - header_len)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA);
OPENSSL_free(*out);
return 0;
@@ -556,35 +609,28 @@ int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) {
return 1;
}
void BIO_set_retry_special(BIO *bio) {
bio->flags |= BIO_FLAGS_READ | BIO_FLAGS_IO_SPECIAL;
}
int BIO_set_write_buffer_size(BIO *bio, int buffer_size) { return 0; }
static CRYPTO_MUTEX g_index_lock = CRYPTO_MUTEX_INIT;
static StaticMutex g_index_lock;
static int g_index = BIO_TYPE_START;
int BIO_get_new_index(void) {
CRYPTO_MUTEX_lock_write(&g_index_lock);
// If |g_index| exceeds 255, it will collide with the flags bits.
int BIO_get_new_index() {
MutexWriteLock lock(&g_index_lock);
// If `g_index` exceeds 255, it will collide with the flags bits.
int ret = g_index > 255 ? -1 : g_index++;
CRYPTO_MUTEX_unlock_write(&g_index_lock);
return ret;
}
BIO_METHOD *BIO_meth_new(int type, const char *name) {
BIO_METHOD *method =
reinterpret_cast<BIO_METHOD *>(OPENSSL_zalloc(sizeof(BIO_METHOD)));
if (method == NULL) {
return NULL;
BIO_METHOD *method = New<BIO_METHOD>();
if (method == nullptr) {
return nullptr;
}
method->type = type;
method->name = name;
return method;
}
void BIO_meth_free(BIO_METHOD *method) { OPENSSL_free(method); }
void BIO_meth_free(BIO_METHOD *method) { Delete(method); }
int BIO_meth_set_create(BIO_METHOD *method, int (*create_func)(BIO *)) {
method->create = create_func;
@@ -596,6 +642,13 @@ int BIO_meth_set_destroy(BIO_METHOD *method, int (*destroy_func)(BIO *)) {
return 1;
}
int BIO_meth_set_write_ex(BIO_METHOD *method,
int (*write_ex_func)(BIO *, const char *, size_t,
size_t *)) {
method->bwrite_ex = write_ex_func;
return 1;
}
int BIO_meth_set_write(BIO_METHOD *method,
int (*write_func)(BIO *, const char *, int)) {
method->bwrite = write_func;
@@ -620,20 +673,29 @@ int BIO_meth_set_ctrl(BIO_METHOD *method,
return 1;
}
void BIO_set_data(BIO *bio, void *ptr) { bio->ptr = ptr; }
int BIO_meth_set_callback_ctrl(BIO_METHOD *method,
long (*callback_ctrl_func)(BIO *, int,
BIO_info_cb *)) {
method->callback_ctrl = callback_ctrl_func;
return 1;
}
void *BIO_get_data(BIO *bio) { return bio->ptr; }
void BIO_set_data(BIO *bio, void *ptr) { FromOpaque(bio)->ptr = ptr; }
void BIO_set_init(BIO *bio, int init) { bio->init = init; }
void *BIO_get_data(BIO *bio) { return FromOpaque(bio)->ptr; }
int BIO_get_init(BIO *bio) { return bio->init; }
void BIO_set_init(BIO *bio, int init) { FromOpaque(bio)->init = init; }
void BIO_set_shutdown(BIO *bio, int shutdown) { bio->shutdown = shutdown; }
int BIO_get_init(BIO *bio) { return FromOpaque(bio)->init; }
int BIO_get_shutdown(BIO *bio) { return bio->shutdown; }
void BIO_set_shutdown(BIO *bio, int shutdown) {
FromOpaque(bio)->shutdown = shutdown;
}
int BIO_get_shutdown(BIO *bio) { return FromOpaque(bio)->shutdown; }
int BIO_meth_set_puts(BIO_METHOD *method, int (*puts)(BIO *, const char *)) {
// Ignore the parameter. We implement |BIO_puts| using |BIO_write|.
// Ignore the parameter. We implement `BIO_puts` using `BIO_write`.
return 1;
}
@@ -645,9 +707,9 @@ int BIO_get_ex_new_index(long argl, void *argp, //
}
int BIO_set_ex_data(BIO *bio, int idx, void *data) {
return CRYPTO_set_ex_data(&bio->ex_data, idx, data);
return CRYPTO_set_ex_data(&FromOpaque(bio)->ex_data, idx, data);
}
void *BIO_get_ex_data(const BIO *bio, int idx) {
return CRYPTO_get_ex_data(&bio->ex_data, idx);
return CRYPTO_get_ex_data(&FromOpaque(bio)->ex_data, idx);
}
+91 -94
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bio.h>
@@ -17,8 +22,11 @@
#include <CNIOBoringSSL_mem.h>
#include "../internal.h"
#include "internal.h"
using namespace bssl;
BIO *BIO_new_mem_buf(const void *buf, ossl_ssize_t len) {
BIO *ret;
BUF_MEM *b;
@@ -26,26 +34,26 @@ BIO *BIO_new_mem_buf(const void *buf, ossl_ssize_t len) {
if (!buf && len != 0) {
OPENSSL_PUT_ERROR(BIO, BIO_R_NULL_PARAMETER);
return NULL;
return nullptr;
}
ret = BIO_new(BIO_s_mem());
if (ret == NULL) {
return NULL;
if (ret == nullptr) {
return nullptr;
}
b = (BUF_MEM *)ret->ptr;
// BIO_FLAGS_MEM_RDONLY ensures |b->data| is not written to.
b = (BUF_MEM *)BIO_get_data(ret);
// BIO_FLAGS_MEM_RDONLY ensures `b->data` is not written to.
b->data = reinterpret_cast<char *>(const_cast<void *>(buf));
b->length = size;
b->max = size;
ret->flags |= BIO_FLAGS_MEM_RDONLY;
BIO_set_flags(ret, BIO_FLAGS_MEM_RDONLY);
// |num| is used to store the value that this BIO will return when it runs
// `num` is used to store the value that this BIO will return when it runs
// out of data. If it's negative then the retry flags will also be set. Since
// this is static data, retrying wont help
ret->num = 0;
// this is static data, retrying won't help
FromOpaque(ret)->num = 0;
return ret;
}
@@ -54,41 +62,38 @@ static int mem_new(BIO *bio) {
BUF_MEM *b;
b = BUF_MEM_new();
if (b == NULL) {
if (b == nullptr) {
return 0;
}
// |shutdown| is used to store the close flag: whether the BIO has ownership
// `shutdown` is used to store the close flag: whether the BIO has ownership
// of the BUF_MEM.
bio->shutdown = 1;
bio->init = 1;
bio->num = -1;
bio->ptr = (char *)b;
BIO_set_shutdown(bio, 1);
BIO_set_init(bio, 1);
FromOpaque(bio)->num = -1;
BIO_set_data(bio, (char *)b);
return 1;
}
static int mem_free(BIO *bio) {
if (!bio->shutdown || !bio->init || bio->ptr == NULL) {
if (!BIO_get_shutdown(bio) || !BIO_get_init(bio) ||
BIO_get_data(bio) == nullptr) {
return 1;
}
BUF_MEM *b = (BUF_MEM *)bio->ptr;
if (bio->flags & BIO_FLAGS_MEM_RDONLY) {
b->data = NULL;
BUF_MEM *b = (BUF_MEM *)BIO_get_data(bio);
if (BIO_test_flags(bio, BIO_FLAGS_MEM_RDONLY)) {
b->data = nullptr;
}
BUF_MEM_free(b);
bio->ptr = NULL;
BIO_set_data(bio, nullptr);
return 1;
}
static int mem_read(BIO *bio, char *out, int outl) {
BIO_clear_retry_flags(bio);
if (outl <= 0) {
return 0;
}
BUF_MEM *b = reinterpret_cast<BUF_MEM *>(bio->ptr);
BUF_MEM *b = reinterpret_cast<BUF_MEM *>(BIO_get_data(bio));
int ret = outl;
if ((size_t)ret > b->length) {
ret = (int)b->length;
@@ -97,13 +102,13 @@ static int mem_read(BIO *bio, char *out, int outl) {
if (ret > 0) {
OPENSSL_memcpy(out, b->data, ret);
b->length -= ret;
if (bio->flags & BIO_FLAGS_MEM_RDONLY) {
if (BIO_test_flags(bio, BIO_FLAGS_MEM_RDONLY)) {
b->data += ret;
} else {
OPENSSL_memmove(b->data, &b->data[ret], b->length);
}
} else if (b->length == 0) {
ret = bio->num;
ret = FromOpaque(bio)->num;
if (ret != 0) {
BIO_set_retry_read(bio);
}
@@ -111,23 +116,20 @@ static int mem_read(BIO *bio, char *out, int outl) {
return ret;
}
static int mem_write(BIO *bio, const char *in, int inl) {
static int mem_write_ex(BIO *bio, const char *in, size_t inl,
size_t *out_written) {
BIO_clear_retry_flags(bio);
if (inl <= 0) {
return 0; // Successfully write zero bytes.
}
if (bio->flags & BIO_FLAGS_MEM_RDONLY) {
if (BIO_test_flags(bio, BIO_FLAGS_MEM_RDONLY)) {
OPENSSL_PUT_ERROR(BIO, BIO_R_WRITE_TO_READ_ONLY_BIO);
return -1;
return 0;
}
BUF_MEM *b = reinterpret_cast<BUF_MEM *>(bio->ptr);
BUF_MEM *b = reinterpret_cast<BUF_MEM *>(BIO_get_data(bio));
if (!BUF_MEM_append(b, in, inl)) {
return -1;
return 0;
}
return inl;
*out_written = inl;
return 1;
}
static int mem_gets(BIO *bio, char *buf, int size) {
@@ -138,7 +140,7 @@ static int mem_gets(BIO *bio, char *buf, int size) {
// The buffer size includes space for the trailing NUL, so we can read at most
// one fewer byte.
BUF_MEM *b = reinterpret_cast<BUF_MEM *>(bio->ptr);
BUF_MEM *b = reinterpret_cast<BUF_MEM *>(BIO_get_data(bio));
int ret = size - 1;
if ((size_t)ret > b->length) {
ret = (int)b->length;
@@ -147,7 +149,7 @@ static int mem_gets(BIO *bio, char *buf, int size) {
// Stop at the first newline.
const char *newline =
reinterpret_cast<char *>(OPENSSL_memchr(b->data, '\n', ret));
if (newline != NULL) {
if (newline != nullptr) {
ret = (int)(newline - b->data + 1);
}
@@ -159,15 +161,12 @@ static int mem_gets(BIO *bio, char *buf, int size) {
}
static long mem_ctrl(BIO *bio, int cmd, long num, void *ptr) {
long ret = 1;
BUF_MEM *b = (BUF_MEM *)bio->ptr;
BUF_MEM *b = static_cast<BUF_MEM *>(BIO_get_data(bio));
switch (cmd) {
case BIO_CTRL_RESET:
if (b->data != NULL) {
if (b->data != nullptr) {
// For read only case reset to the start again
if (bio->flags & BIO_FLAGS_MEM_RDONLY) {
if (BIO_test_flags(bio, BIO_FLAGS_MEM_RDONLY)) {
b->data -= b->max - b->length;
b->length = b->max;
} else {
@@ -175,72 +174,70 @@ static long mem_ctrl(BIO *bio, int cmd, long num, void *ptr) {
b->length = 0;
}
}
break;
return 1;
case BIO_CTRL_EOF:
ret = (long)(b->length == 0);
break;
return b->length == 0;
case BIO_C_SET_BUF_MEM_EOF_RETURN:
bio->num = (int)num;
break;
FromOpaque(bio)->num = static_cast<int>(num);
return 1;
case BIO_CTRL_INFO:
ret = (long)b->length;
if (ptr != NULL) {
char **pptr = reinterpret_cast<char **>(ptr);
*pptr = b->data;
if (ptr != nullptr) {
char **out = reinterpret_cast<char **>(ptr);
*out = b->data;
}
break;
// This API can overflow on 64-bit Windows, where `long` is smaller than
// `ptrdiff_t`. `BIO_mem_contents` is the overflow-safe API.
return static_cast<long>(b->length);
case BIO_C_SET_BUF_MEM:
mem_free(bio);
bio->shutdown = (int)num;
bio->ptr = ptr;
break;
BIO_set_shutdown(bio, static_cast<int>(num));
BIO_set_data(bio, ptr);
return 1;
case BIO_C_GET_BUF_MEM_PTR:
if (ptr != NULL) {
BUF_MEM **pptr = reinterpret_cast<BUF_MEM **>(ptr);
*pptr = b;
if (ptr != nullptr) {
BUF_MEM **out = reinterpret_cast<BUF_MEM **>(ptr);
*out = b;
}
break;
return 1;
case BIO_CTRL_GET_CLOSE:
ret = (long)bio->shutdown;
break;
return BIO_get_shutdown(bio);
case BIO_CTRL_SET_CLOSE:
bio->shutdown = (int)num;
break;
BIO_set_shutdown(bio, static_cast<int>(num));
return 1;
case BIO_CTRL_WPENDING:
ret = 0L;
break;
return 0;
case BIO_CTRL_PENDING:
ret = (long)b->length;
break;
// TODO(crbug.com/412584975): This can overflow on 64-bit Windows.
return static_cast<long>(b->length);
case BIO_CTRL_FLUSH:
ret = 1;
break;
return 1;
default:
ret = 0;
break;
return 0;
}
return ret;
}
static const BIO_METHOD mem_method = {
BIO_TYPE_MEM, "memory buffer",
mem_write, mem_read,
NULL /* puts */, mem_gets,
mem_ctrl, mem_new,
mem_free, NULL /* callback_ctrl */,
BIO_TYPE_MEM,
/*bwrite=*/nullptr,
mem_write_ex,
mem_read,
mem_gets,
mem_ctrl,
mem_new,
mem_free,
/*callback_ctrl=*/nullptr,
};
const BIO_METHOD *BIO_s_mem(void) { return &mem_method; }
const BIO_METHOD *BIO_s_mem() { return &mem_method; }
int BIO_mem_contents(const BIO *bio, const uint8_t **out_contents,
size_t *out_len) {
const BUF_MEM *b;
if (bio->method != &mem_method) {
if (FromOpaque(bio)->method != &mem_method) {
return 0;
}
b = (BUF_MEM *)bio->ptr;
b = (BUF_MEM *)BIO_get_data((BIO *)bio);
*out_contents = (uint8_t *)b->data;
*out_len = b->length;
return 1;
@@ -259,5 +256,5 @@ int BIO_set_mem_buf(BIO *bio, BUF_MEM *b, int take_ownership) {
}
int BIO_set_mem_eof_return(BIO *bio, int eof_value) {
return (int)BIO_ctrl(bio, BIO_C_SET_BUF_MEM_EOF_RETURN, eof_value, NULL);
return (int)BIO_ctrl(bio, BIO_C_SET_BUF_MEM_EOF_RETURN, eof_value, nullptr);
}
+170 -213
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bio.h>
@@ -13,6 +18,7 @@
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#if !defined(OPENSSL_WINDOWS)
@@ -21,19 +27,23 @@
#include <sys/socket.h>
#include <unistd.h>
#else
OPENSSL_MSVC_PRAGMA(warning(push, 3))
#include <winsock2.h>
#include <ws2tcpip.h>
OPENSSL_MSVC_PRAGMA(warning(pop))
#endif
#include <algorithm>
#include <utility>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_mem.h>
#include "../internal.h"
#include "../mem_internal.h"
#include "internal.h"
using namespace bssl;
enum {
BIO_CONN_S_BEFORE,
BIO_CONN_S_BLOCKED_CONNECT,
@@ -41,46 +51,45 @@ enum {
};
namespace {
typedef struct bio_connect_st {
int state;
struct BIO_CONNECT {
int state = BIO_CONN_S_BEFORE;
char *param_hostname;
char *param_port;
int nbio;
UniquePtr<char> param_hostname;
UniquePtr<char> param_port;
int nbio = 0;
unsigned short port;
unsigned short port = 0;
struct sockaddr_storage them;
socklen_t them_length;
sockaddr_storage them;
socklen_t them_length = 0;
// the file descriptor is kept in bio->num in order to match the socket
// BIO.
// The file descriptor is kept in bio->num in order to match the socket BIO.
// info_callback is called when the connection is initially made
// callback(BIO,state,ret); The callback should return 'ret', state is for
// compatibility with the SSL info_callback.
int (*info_callback)(const BIO *bio, int state, int ret);
} BIO_CONNECT;
int (*info_callback)(BIO *bio, int state, int ret) = nullptr;
};
} // namespace
#if !defined(OPENSSL_WINDOWS)
static int closesocket(int sock) { return close(sock); }
#endif
// split_host_and_port sets |*out_host| and |*out_port| to the host and port
// parsed from |name|. It returns one on success or zero on error. Even when
// successful, |*out_port| may be NULL on return if no port was specified.
static int split_host_and_port(char **out_host, char **out_port,
const char *name) {
const char *host, *port = NULL;
// split_host_and_port sets `*out_host` and `*out_port` to the host and port
// parsed from `name`. It returns one on success or zero on error. Even when
// successful, `*out_port` may be NULL on return if no port was specified.
static int split_host_and_port(UniquePtr<char> *out_host,
UniquePtr<char> *out_port, const char *name) {
const char *host, *port = nullptr;
size_t host_len = 0;
*out_host = NULL;
*out_port = NULL;
*out_host = nullptr;
*out_port = nullptr;
if (name[0] == '[') { // bracketed IPv6 address
const char *close = strchr(name, ']');
if (close == NULL) {
if (close == nullptr) {
return 0;
}
host = name + 1;
@@ -92,7 +101,8 @@ static int split_host_and_port(char **out_host, char **out_port,
}
} else {
const char *colon = strchr(name, ':');
if (colon == NULL || strchr(colon + 1, ':') != NULL) { // IPv6 address
if (colon == nullptr ||
strchr(colon + 1, ':') != nullptr) { // IPv6 address
host = name;
host_len = strlen(name);
} else { // host:port
@@ -102,18 +112,17 @@ static int split_host_and_port(char **out_host, char **out_port,
}
}
*out_host = OPENSSL_strndup(host, host_len);
if (*out_host == NULL) {
out_host->reset(OPENSSL_strndup(host, host_len));
if (*out_host == nullptr) {
return 0;
}
if (port == NULL) {
*out_port = NULL;
if (port == nullptr) {
*out_port = nullptr;
return 1;
}
*out_port = OPENSSL_strdup(port);
if (*out_port == NULL) {
OPENSSL_free(*out_host);
*out_host = NULL;
out_port->reset(OPENSSL_strdup(port));
if (*out_port == nullptr) {
*out_host = nullptr;
return 0;
}
return 1;
@@ -121,9 +130,9 @@ static int split_host_and_port(char **out_host, char **out_port,
static int conn_state(BIO *bio, BIO_CONNECT *c) {
int ret = -1, i;
int (*cb)(const BIO *, int, int) = NULL;
int (*cb)(BIO *, int, int) = nullptr;
if (c->info_callback != NULL) {
if (c->info_callback != nullptr) {
cb = c->info_callback;
}
@@ -134,67 +143,66 @@ static int conn_state(BIO *bio, BIO_CONNECT *c) {
// exactly what they say. If there is only a hostname, try
// (just once) to split it into a hostname and port.
if (c->param_hostname == NULL) {
if (c->param_hostname == nullptr) {
OPENSSL_PUT_ERROR(BIO, BIO_R_NO_HOSTNAME_SPECIFIED);
goto exit_loop;
}
if (c->param_port == NULL) {
char *host, *port;
if (!split_host_and_port(&host, &port, c->param_hostname) ||
port == NULL) {
OPENSSL_free(host);
OPENSSL_free(port);
if (c->param_port == nullptr) {
UniquePtr<char> host, port;
if (!split_host_and_port(&host, &port, c->param_hostname.get()) ||
port == nullptr) {
OPENSSL_PUT_ERROR(BIO, BIO_R_NO_PORT_SPECIFIED);
ERR_add_error_data(2, "host=", c->param_hostname);
ERR_add_error_data(2, "host=", c->param_hostname.get());
goto exit_loop;
}
OPENSSL_free(c->param_port);
c->param_port = port;
OPENSSL_free(c->param_hostname);
c->param_hostname = host;
c->param_port = std::move(port);
c->param_hostname = std::move(host);
}
if (!bio_ip_and_port_to_socket_and_addr(
&bio->num, &c->them, &c->them_length, c->param_hostname,
c->param_port)) {
&FromOpaque(bio)->num, &c->them, &c->them_length,
c->param_hostname.get(), c->param_port.get())) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNABLE_TO_CREATE_SOCKET);
ERR_add_error_data(4, "host=", c->param_hostname, ":", c->param_port);
ERR_add_error_data(4, "host=", c->param_hostname.get(), ":",
c->param_port.get());
goto exit_loop;
}
if (c->nbio) {
if (!bio_socket_nbio(bio->num, 1)) {
if (!bio_socket_nbio(FromOpaque(bio)->num, 1)) {
OPENSSL_PUT_ERROR(BIO, BIO_R_ERROR_SETTING_NBIO);
ERR_add_error_data(4, "host=", c->param_hostname, ":",
c->param_port);
ERR_add_error_data(4, "host=", c->param_hostname.get(), ":",
c->param_port.get());
goto exit_loop;
}
}
i = 1;
ret = setsockopt(bio->num, SOL_SOCKET, SO_KEEPALIVE, (char *)&i,
sizeof(i));
ret = setsockopt(FromOpaque(bio)->num, SOL_SOCKET, SO_KEEPALIVE,
(char *)&i, sizeof(i));
if (ret < 0) {
OPENSSL_PUT_SYSTEM_ERROR();
OPENSSL_PUT_ERROR(BIO, BIO_R_KEEPALIVE);
ERR_add_error_data(4, "host=", c->param_hostname, ":", c->param_port);
ERR_add_error_data(4, "host=", c->param_hostname.get(), ":",
c->param_port.get());
goto exit_loop;
}
BIO_clear_retry_flags(bio);
ret = connect(bio->num, (struct sockaddr *)&c->them, c->them_length);
ret = connect(FromOpaque(bio)->num, (struct sockaddr *)&c->them,
c->them_length);
if (ret < 0) {
if (bio_socket_should_retry(ret)) {
BIO_set_flags(bio, (BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY));
BIO_set_retry_special(bio);
c->state = BIO_CONN_S_BLOCKED_CONNECT;
bio->retry_reason = BIO_RR_CONNECT;
BIO_set_retry_reason(bio, BIO_RR_CONNECT);
} else {
OPENSSL_PUT_SYSTEM_ERROR();
OPENSSL_PUT_ERROR(BIO, BIO_R_CONNECT_ERROR);
ERR_add_error_data(4, "host=", c->param_hostname, ":",
c->param_port);
ERR_add_error_data(4, "host=", c->param_hostname.get(), ":",
c->param_port.get());
}
goto exit_loop;
} else {
@@ -203,21 +211,19 @@ static int conn_state(BIO *bio, BIO_CONNECT *c) {
break;
case BIO_CONN_S_BLOCKED_CONNECT:
i = bio_sock_error(bio->num);
if (i) {
if (bio_socket_should_retry(ret)) {
BIO_set_flags(bio, (BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY));
if (!bio_socket_finish_connect(FromOpaque(bio)->num)) {
if (bio_socket_should_retry(-1)) {
BIO_set_retry_special(bio);
c->state = BIO_CONN_S_BLOCKED_CONNECT;
bio->retry_reason = BIO_RR_CONNECT;
ret = -1;
BIO_set_retry_reason(bio, BIO_RR_CONNECT);
} else {
BIO_clear_retry_flags(bio);
OPENSSL_PUT_SYSTEM_ERROR();
OPENSSL_PUT_ERROR(BIO, BIO_R_NBIO_CONNECT_ERROR);
ERR_add_error_data(4, "host=", c->param_hostname, ":",
c->param_port);
ret = 0;
ERR_add_error_data(4, "host=", c->param_hostname.get(), ":",
c->param_port.get());
}
ret = -1;
goto exit_loop;
} else {
c->state = BIO_CONN_S_OK;
@@ -232,7 +238,7 @@ static int conn_state(BIO *bio, BIO_CONNECT *c) {
goto exit_loop;
}
if (cb != NULL) {
if (cb != nullptr) {
ret = cb((BIO *)bio, c->state, ret);
if (ret == 0) {
goto end;
@@ -241,7 +247,7 @@ static int conn_state(BIO *bio, BIO_CONNECT *c) {
}
exit_loop:
if (cb != NULL) {
if (cb != nullptr) {
ret = cb((BIO *)bio, c->state, ret);
}
@@ -249,55 +255,35 @@ end:
return ret;
}
static BIO_CONNECT *BIO_CONNECT_new(void) {
BIO_CONNECT *ret =
reinterpret_cast<BIO_CONNECT *>(OPENSSL_zalloc(sizeof(BIO_CONNECT)));
if (ret == NULL) {
return NULL;
}
ret->state = BIO_CONN_S_BEFORE;
return ret;
}
static void BIO_CONNECT_free(BIO_CONNECT *c) {
if (c == nullptr) {
return;
}
OPENSSL_free(c->param_hostname);
OPENSSL_free(c->param_port);
OPENSSL_free(c);
}
static int conn_new(BIO *bio) {
bio->init = 0;
bio->num = -1;
bio->flags = 0;
bio->ptr = BIO_CONNECT_new();
return bio->ptr != NULL;
BIO_set_init(bio, 0);
FromOpaque(bio)->num = -1;
FromOpaque(bio)->flags = 0;
BIO_set_data(bio, New<BIO_CONNECT>());
return BIO_get_data(bio) != nullptr;
}
static void conn_close_socket(BIO *bio) {
BIO_CONNECT *c = (BIO_CONNECT *)bio->ptr;
BIO_CONNECT *c = (BIO_CONNECT *)BIO_get_data(bio);
if (bio->num == -1) {
if (FromOpaque(bio)->num == -1) {
return;
}
// Only do a shutdown if things were established
if (c->state == BIO_CONN_S_OK) {
shutdown(bio->num, 2);
shutdown(FromOpaque(bio)->num, 2);
}
closesocket(bio->num);
bio->num = -1;
closesocket(FromOpaque(bio)->num);
FromOpaque(bio)->num = -1;
}
static int conn_free(BIO *bio) {
if (bio->shutdown) {
if (BIO_get_shutdown(bio)) {
conn_close_socket(bio);
}
BIO_CONNECT_free((BIO_CONNECT *)bio->ptr);
Delete(static_cast<BIO_CONNECT *>(BIO_get_data(bio)));
return 1;
}
@@ -305,7 +291,7 @@ static int conn_read(BIO *bio, char *out, int out_len) {
int ret = 0;
BIO_CONNECT *data;
data = (BIO_CONNECT *)bio->ptr;
data = (BIO_CONNECT *)BIO_get_data(bio);
if (data->state != BIO_CONN_S_OK) {
ret = conn_state(bio, data);
if (ret <= 0) {
@@ -314,7 +300,7 @@ static int conn_read(BIO *bio, char *out, int out_len) {
}
bio_clear_socket_error();
ret = (int)recv(bio->num, out, out_len, 0);
ret = (int)recv(FromOpaque(bio)->num, out, out_len, 0);
BIO_clear_retry_flags(bio);
if (ret <= 0) {
if (bio_socket_should_retry(ret)) {
@@ -325,161 +311,132 @@ static int conn_read(BIO *bio, char *out, int out_len) {
return ret;
}
static int conn_write(BIO *bio, const char *in, int in_len) {
int ret;
BIO_CONNECT *data;
data = (BIO_CONNECT *)bio->ptr;
static int conn_write_ex(BIO *bio, const char *in, size_t in_len,
size_t *out_written) {
BIO_CONNECT *data = (BIO_CONNECT *)BIO_get_data(bio);
if (data->state != BIO_CONN_S_OK) {
ret = conn_state(bio, data);
if (ret <= 0) {
return ret;
if (conn_state(bio, data) <= 0) {
return 0;
}
}
bio_clear_socket_error();
ret = (int)send(bio->num, in, in_len, 0);
#if defined(OPENSSL_WINDOWS)
in_len = std::min(in_len, size_t{INT_MAX});
int ret = send(FromOpaque(bio)->num, in, static_cast<int>(in_len), 0);
#else
ssize_t ret = send(FromOpaque(bio)->num, in, in_len, 0);
#endif
BIO_clear_retry_flags(bio);
if (ret <= 0) {
if (bio_socket_should_retry(ret)) {
BIO_set_retry_write(bio);
}
return 0;
}
return ret;
*out_written = ret;
return 1;
}
static long conn_ctrl(BIO *bio, int cmd, long num, void *ptr) {
int *ip;
long ret = 1;
BIO_CONNECT *data;
data = (BIO_CONNECT *)bio->ptr;
BIO_CONNECT *data = static_cast<BIO_CONNECT *>(BIO_get_data(bio));
switch (cmd) {
case BIO_CTRL_RESET:
ret = 0;
data->state = BIO_CONN_S_BEFORE;
conn_close_socket(bio);
bio->flags = 0;
break;
FromOpaque(bio)->flags = 0;
return 0;
case BIO_C_DO_STATE_MACHINE:
// use this one to start the connection
if (data->state != BIO_CONN_S_OK) {
ret = (long)conn_state(bio, data);
return conn_state(bio, data);
} else {
ret = 1;
return 1;
}
break;
case BIO_C_SET_CONNECT:
if (ptr != NULL) {
bio->init = 1;
if (num == 0) {
OPENSSL_free(data->param_hostname);
data->param_hostname =
OPENSSL_strdup(reinterpret_cast<const char *>(ptr));
if (data->param_hostname == NULL) {
ret = 0;
}
} else if (num == 1) {
OPENSSL_free(data->param_port);
data->param_port =
OPENSSL_strdup(reinterpret_cast<const char *>(ptr));
if (data->param_port == NULL) {
ret = 0;
}
} else {
ret = 0;
}
if (ptr == nullptr) {
return 0;
}
break;
case BIO_C_SET_NBIO:
data->nbio = (int)num;
break;
case BIO_C_GET_FD:
if (bio->init) {
ip = (int *)ptr;
if (ip != NULL) {
*ip = bio->num;
BIO_set_init(bio, 1);
if (num == 0) {
data->param_hostname.reset(
OPENSSL_strdup(reinterpret_cast<const char *>(ptr)));
if (data->param_hostname == nullptr) {
return 0;
}
} else if (num == 1) {
data->param_port.reset(
OPENSSL_strdup(reinterpret_cast<const char *>(ptr)));
if (data->param_port == nullptr) {
return 0;
}
ret = bio->num;
} else {
ret = -1;
return 0;
}
return 1;
case BIO_C_SET_NBIO:
data->nbio = static_cast<int>(num);
return 1;
case BIO_C_GET_FD:
if (BIO_get_init(bio)) {
int *out = static_cast<int *>(ptr);
if (out != nullptr) {
*out = FromOpaque(bio)->num;
}
return FromOpaque(bio)->num;
} else {
return -1;
}
break;
case BIO_CTRL_GET_CLOSE:
ret = bio->shutdown;
break;
return BIO_get_shutdown(bio);
case BIO_CTRL_SET_CLOSE:
bio->shutdown = (int)num;
break;
case BIO_CTRL_PENDING:
case BIO_CTRL_WPENDING:
ret = 0;
break;
BIO_set_shutdown(bio, static_cast<int>(num));
return 1;
case BIO_CTRL_FLUSH:
break;
return 1;
case BIO_CTRL_GET_CALLBACK: {
int (**fptr)(const BIO *bio, int state, int xret);
fptr = reinterpret_cast<decltype(fptr)>(ptr);
*fptr = data->info_callback;
} break;
auto out = reinterpret_cast<int (**)(BIO *bio, int state, int xret)>(ptr);
*out = data->info_callback;
return 1;
}
default:
ret = 0;
break;
return 0;
}
return ret;
}
static long conn_callback_ctrl(BIO *bio, int cmd, bio_info_cb fp) {
long ret = 1;
BIO_CONNECT *data;
data = (BIO_CONNECT *)bio->ptr;
static long conn_callback_ctrl(BIO *bio, int cmd, BIO_info_cb *fp) {
BIO_CONNECT *data = static_cast<BIO_CONNECT *>(BIO_get_data(bio));
switch (cmd) {
case BIO_CTRL_SET_CALLBACK:
// This is the actual type signature of |fp|. The caller is expected to
// cast it to |bio_info_cb| due to the |BIO_callback_ctrl| calling
// convention.
OPENSSL_MSVC_PRAGMA(warning(push))
OPENSSL_MSVC_PRAGMA(warning(disable : 4191))
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;
data->info_callback = fp;
return 1;
default:
ret = 0;
break;
return 0;
}
return ret;
}
BIO *BIO_new_connect(const char *hostname) {
BIO *ret;
ret = BIO_new(BIO_s_connect());
if (ret == NULL) {
return NULL;
if (ret == nullptr) {
return nullptr;
}
if (!BIO_set_conn_hostname(ret, hostname)) {
BIO_free(ret);
return NULL;
return nullptr;
}
return ret;
}
static const BIO_METHOD methods_connectp = {
BIO_TYPE_CONNECT, "socket connect", conn_write, conn_read,
NULL /* puts */, NULL /* gets */, conn_ctrl, conn_new,
conn_free, conn_callback_ctrl,
BIO_TYPE_CONNECT, /*bwrite=*/nullptr, conn_write_ex,
conn_read, /*gets=*/nullptr, conn_ctrl,
conn_new, conn_free, conn_callback_ctrl,
};
const BIO_METHOD *BIO_s_connect(void) { return &methods_connectp; }
const BIO_METHOD *BIO_s_connect() { return &methods_connectp; }
int BIO_set_conn_hostname(BIO *bio, const char *name) {
return (int)BIO_ctrl(bio, BIO_C_SET_CONNECT, 0, (void *)name);
@@ -496,11 +453,11 @@ int BIO_set_conn_int_port(BIO *bio, const int *port) {
}
int BIO_set_nbio(BIO *bio, int on) {
return (int)BIO_ctrl(bio, BIO_C_SET_NBIO, on, NULL);
return (int)BIO_ctrl(bio, BIO_C_SET_NBIO, on, nullptr);
}
int BIO_do_connect(BIO *bio) {
return (int)BIO_ctrl(bio, BIO_C_DO_STATE_MACHINE, 0, NULL);
return (int)BIO_ctrl(bio, BIO_C_DO_STATE_MACHINE, 0, nullptr);
}
#endif // OPENSSL_NO_SOCK
+16 -9
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bio.h>
@@ -14,7 +19,9 @@
#include "internal.h"
int bio_errno_should_retry(int return_value) {
using namespace bssl;
int bssl::bio_errno_should_retry(int return_value) {
if (return_value != -1) {
return 0;
}
+68 -63
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bio.h>
@@ -18,6 +23,8 @@
#include <unistd.h>
#else
#include <io.h>
#include <limits.h>
#include <algorithm>
#endif
#include <CNIOBoringSSL_err.h>
@@ -31,18 +38,18 @@
#define BORINGSSL_CLOSE _close
#define BORINGSSL_LSEEK _lseek
#define BORINGSSL_READ _read
#define BORINGSSL_WRITE _write
#else
#define BORINGSSL_CLOSE close
#define BORINGSSL_LSEEK lseek
#define BORINGSSL_READ read
#define BORINGSSL_WRITE write
#endif
using namespace bssl;
BIO *BIO_new_fd(int fd, int close_flag) {
BIO *ret = BIO_new(BIO_s_fd());
if (ret == NULL) {
return NULL;
if (ret == nullptr) {
return nullptr;
}
BIO_set_fd(ret, fd, close_flag);
return ret;
@@ -50,24 +57,22 @@ BIO *BIO_new_fd(int fd, int close_flag) {
static int fd_new(BIO *bio) {
// num is used to store the file descriptor.
bio->num = -1;
FromOpaque(bio)->num = -1;
return 1;
}
static int fd_free(BIO *bio) {
if (bio->shutdown) {
if (bio->init) {
BORINGSSL_CLOSE(bio->num);
if (BIO_get_shutdown(bio)) {
if (BIO_get_init(bio)) {
BORINGSSL_CLOSE(FromOpaque(bio)->num);
}
bio->init = 0;
BIO_set_init(bio, 0);
}
return 1;
}
static int fd_read(BIO *b, char *out, int outl) {
int ret = 0;
ret = (int)BORINGSSL_READ(b->num, out, outl);
int ret = (int)BORINGSSL_READ(FromOpaque(b)->num, out, outl);
BIO_clear_retry_flags(b);
if (ret <= 0) {
if (bio_errno_should_retry(ret)) {
@@ -78,75 +83,68 @@ static int fd_read(BIO *b, char *out, int outl) {
return ret;
}
static int fd_write(BIO *b, const char *in, int inl) {
int ret = (int)BORINGSSL_WRITE(b->num, in, inl);
static int fd_write_ex(BIO *b, const char *in, size_t inl,
size_t *out_written) {
#if defined(OPENSSL_WINDOWS)
inl = std::min(inl, size_t{UINT_MAX});
int ret = _write(FromOpaque(b)->num, in, static_cast<unsigned>(inl));
#else
ssize_t ret = write(FromOpaque(b)->num, in, inl);
#endif
BIO_clear_retry_flags(b);
if (ret <= 0) {
if (bio_errno_should_retry(ret)) {
BIO_set_retry_write(b);
}
return 0;
}
return ret;
*out_written = ret;
return 1;
}
static long fd_ctrl(BIO *b, int cmd, long num, void *ptr) {
long ret = 1;
int *ip;
switch (cmd) {
case BIO_CTRL_RESET:
num = 0;
[[fallthrough]];
case BIO_C_FILE_SEEK:
ret = 0;
if (b->init) {
ret = (long)BORINGSSL_LSEEK(b->num, num, SEEK_SET);
if (BIO_get_init(b)) {
return (long)BORINGSSL_LSEEK(FromOpaque(b)->num, num, SEEK_SET);
}
break;
return 0;
case BIO_C_FILE_TELL:
case BIO_CTRL_INFO:
ret = 0;
if (b->init) {
ret = (long)BORINGSSL_LSEEK(b->num, 0, SEEK_CUR);
if (BIO_get_init(b)) {
return (long)BORINGSSL_LSEEK(FromOpaque(b)->num, 0, SEEK_CUR);
}
break;
return 0;
case BIO_C_SET_FD:
fd_free(b);
b->num = *((int *)ptr);
b->shutdown = (int)num;
b->init = 1;
break;
FromOpaque(b)->num = *static_cast<int *>(ptr);
BIO_set_shutdown(b, static_cast<int>(num));
BIO_set_init(b, 1);
return 1;
case BIO_C_GET_FD:
if (b->init) {
ip = (int *)ptr;
if (ip != NULL) {
*ip = b->num;
if (BIO_get_init(b)) {
int *out = static_cast<int *>(ptr);
if (out != nullptr) {
*out = FromOpaque(b)->num;
}
return b->num;
return FromOpaque(b)->num;
} else {
ret = -1;
return -1;
}
break;
case BIO_CTRL_GET_CLOSE:
ret = b->shutdown;
break;
return BIO_get_shutdown(b);
case BIO_CTRL_SET_CLOSE:
b->shutdown = (int)num;
break;
case BIO_CTRL_PENDING:
case BIO_CTRL_WPENDING:
ret = 0;
break;
BIO_set_shutdown(b, static_cast<int>(num));
return 1;
case BIO_CTRL_FLUSH:
ret = 1;
break;
return 1;
default:
ret = 0;
break;
return 0;
}
return ret;
}
static int fd_gets(BIO *bp, char *buf, int size) {
@@ -166,16 +164,23 @@ static int fd_gets(BIO *bp, char *buf, int size) {
ptr[0] = '\0';
// The output length is bounded by |size|.
// The output length is bounded by `size`.
return (int)(ptr - buf);
}
static const BIO_METHOD methods_fdp = {
BIO_TYPE_FD, "file descriptor", fd_write, fd_read, NULL /* puts */,
fd_gets, fd_ctrl, fd_new, fd_free, NULL /* callback_ctrl */,
BIO_TYPE_FD,
/*bwrite=*/nullptr,
fd_write_ex,
fd_read,
fd_gets,
fd_ctrl,
fd_new,
fd_free,
/*callback_ctrl=*/nullptr,
};
const BIO_METHOD *BIO_s_fd(void) { return &methods_fdp; }
const BIO_METHOD *BIO_s_fd() { return &methods_fdp; }
#endif // OPENSSL_NO_POSIX_IO
+82 -86
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if defined(__linux) || defined(__sun) || defined(__hpux)
// Following definition aliases fopen to fopen64 on above mentioned
@@ -35,6 +40,7 @@
#include <CNIOBoringSSL_mem.h>
#include "../internal.h"
#include "internal.h"
#if defined(OPENSSL_WINDOWS)
#include <fcntl.h>
@@ -50,7 +56,7 @@
#else
static FILE *fopen_if_available(const char *path, const char *mode) {
errno = ENOENT;
return NULL;
return nullptr;
}
#endif
@@ -59,7 +65,7 @@ BIO *BIO_new_file(const char *filename, const char *mode) {
FILE *file;
file = fopen_if_available(filename, mode);
if (file == NULL) {
if (file == nullptr) {
OPENSSL_PUT_SYSTEM_ERROR();
ERR_add_error_data(5, "fopen('", filename, "','", mode, "')");
@@ -68,13 +74,13 @@ BIO *BIO_new_file(const char *filename, const char *mode) {
} else {
OPENSSL_PUT_ERROR(BIO, BIO_R_SYS_LIB);
}
return NULL;
return nullptr;
}
ret = BIO_new_fp(file, BIO_CLOSE);
if (ret == NULL) {
if (ret == nullptr) {
fclose(file);
return NULL;
return nullptr;
}
return ret;
@@ -82,8 +88,8 @@ BIO *BIO_new_file(const char *filename, const char *mode) {
BIO *BIO_new_fp(FILE *stream, int flags) {
BIO *ret = BIO_new(BIO_s_file());
if (ret == NULL) {
return NULL;
if (ret == nullptr) {
return nullptr;
}
BIO_set_fp(ret, stream, flags);
@@ -91,86 +97,80 @@ BIO *BIO_new_fp(FILE *stream, int flags) {
}
static int file_free(BIO *bio) {
if (!bio->shutdown) {
if (!BIO_get_shutdown(bio)) {
return 1;
}
if (bio->init && bio->ptr != NULL) {
fclose(reinterpret_cast<FILE *>(bio->ptr));
bio->ptr = NULL;
if (BIO_get_init(bio) && BIO_get_data(bio) != nullptr) {
fclose(reinterpret_cast<FILE *>(BIO_get_data(bio)));
BIO_set_data(bio, nullptr);
}
bio->init = 0;
BIO_set_init(bio, 0);
return 1;
}
static int file_read(BIO *b, char *out, int outl) {
if (!b->init) {
return 0;
}
size_t ret = fread(out, 1, outl, (FILE *)b->ptr);
if (ret == 0 && ferror((FILE *)b->ptr)) {
size_t ret = fread(out, 1, outl, (FILE *)BIO_get_data(b));
if (ret == 0 && ferror((FILE *)BIO_get_data(b))) {
OPENSSL_PUT_SYSTEM_ERROR();
OPENSSL_PUT_ERROR(BIO, ERR_R_SYS_LIB);
return -1;
}
// fread reads at most |outl| bytes, so |ret| fits in an int.
// fread reads at most `outl` bytes, so `ret` fits in an int.
return (int)ret;
}
static int file_write(BIO *b, const char *in, int inl) {
if (!b->init) {
static int file_write_ex(BIO *b, const char *in, size_t inl,
size_t *out_written) {
if (fwrite(in, inl, 1, (FILE *)BIO_get_data(b)) == 0) {
return 0;
}
int ret = (int)fwrite(in, inl, 1, (FILE *)b->ptr);
if (ret > 0) {
ret = inl;
}
return ret;
// We currently ask |fwrite| to write one "object" of size |inl|, rather than
// |inl| objects of size 1. |fwrite| will only succeed if it wrote the whole
// input.
//
// TODO(crbug.com/518854940): This also means we discard information about
// partial writes.
*out_written = inl;
return 1;
}
static long file_ctrl(BIO *b, int cmd, long num, void *ptr) {
long ret = 1;
FILE *fp = (FILE *)b->ptr;
FILE **fpp;
FILE *fp = static_cast<FILE *>(BIO_get_data(b));
switch (cmd) {
case BIO_CTRL_RESET:
num = 0;
[[fallthrough]];
case BIO_C_FILE_SEEK:
ret = (long)fseek(fp, num, 0);
break;
return fseek(fp, num, 0);
case BIO_CTRL_EOF:
ret = (long)feof(fp);
break;
// feof may return any non-zero value for EOF, but we must return 1.
return feof(fp) != 0;
case BIO_C_FILE_TELL:
case BIO_CTRL_INFO:
ret = ftell(fp);
break;
return ftell(fp);
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
// 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|.
// tested under POSIX will inadvertently change the state of `FILE`
// objects when wrapping them in a `BIO`.
if (num & BIO_FP_TEXT) {
_setmode(_fileno(reinterpret_cast<FILE *>(ptr)), _O_TEXT);
}
#endif
b->shutdown = (int)num & BIO_CLOSE;
b->ptr = ptr;
b->init = 1;
break;
BIO_set_shutdown(b, static_cast<int>(num) & BIO_CLOSE);
BIO_set_data(b, ptr);
BIO_set_init(b, 1);
return 1;
case BIO_C_SET_FILENAME:
file_free(b);
b->shutdown = (int)num & BIO_CLOSE;
BIO_set_shutdown(b, static_cast<int>(num) & BIO_CLOSE);
const char *mode;
if (num & BIO_FP_APPEND) {
if (num & BIO_FP_READ) {
@@ -186,43 +186,35 @@ static long file_ctrl(BIO *b, int cmd, long num, void *ptr) {
mode = "rb";
} else {
OPENSSL_PUT_ERROR(BIO, BIO_R_BAD_FOPEN_MODE);
ret = 0;
break;
return 0;
}
fp = fopen_if_available(reinterpret_cast<const char *>(ptr), mode);
if (fp == NULL) {
if (fp == nullptr) {
OPENSSL_PUT_SYSTEM_ERROR();
ERR_add_error_data(5, "fopen('", ptr, "','", mode, "')");
OPENSSL_PUT_ERROR(BIO, ERR_R_SYS_LIB);
ret = 0;
break;
return 0;
}
b->ptr = fp;
b->init = 1;
break;
BIO_set_data(b, fp);
BIO_set_init(b, 1);
return 1;
case BIO_C_GET_FILE_PTR:
// the ptr parameter is actually a FILE ** in this case.
if (ptr != NULL) {
fpp = (FILE **)ptr;
*fpp = (FILE *)b->ptr;
if (ptr != nullptr) {
FILE **out = static_cast<FILE **>(ptr);
*out = fp;
}
break;
return 1;
case BIO_CTRL_GET_CLOSE:
ret = (long)b->shutdown;
break;
return BIO_get_shutdown(b);
case BIO_CTRL_SET_CLOSE:
b->shutdown = (int)num;
break;
BIO_set_shutdown(b, static_cast<int>(num));
return 1;
case BIO_CTRL_FLUSH:
ret = 0 == fflush((FILE *)b->ptr);
break;
case BIO_CTRL_WPENDING:
case BIO_CTRL_PENDING:
return fflush(fp) == 0;
default:
ret = 0;
break;
return 0;
}
return ret;
}
static int file_gets(BIO *bp, char *buf, int size) {
@@ -230,10 +222,10 @@ static int file_gets(BIO *bp, char *buf, int size) {
return 0;
}
if (!fgets(buf, size, (FILE *)bp->ptr)) {
if (!fgets(buf, size, (FILE *)BIO_get_data(bp))) {
buf[0] = 0;
// TODO(davidben): This doesn't distinguish error and EOF. This should check
// |ferror| as in |file_read|.
// `ferror` as in `file_read`.
return 0;
}
@@ -241,14 +233,18 @@ static int file_gets(BIO *bp, char *buf, int size) {
}
static const BIO_METHOD methods_filep = {
BIO_TYPE_FILE, "FILE pointer",
file_write, file_read,
NULL /* puts */, file_gets,
file_ctrl, NULL /* create */,
file_free, NULL /* callback_ctrl */,
BIO_TYPE_FILE,
/*bwrite=*/nullptr,
file_write_ex,
file_read,
file_gets,
file_ctrl,
/*create=*/nullptr,
file_free,
/*callback_ctrl=*/nullptr,
};
const BIO_METHOD *BIO_s_file(void) { return &methods_filep; }
const BIO_METHOD *BIO_s_file() { return &methods_filep; }
int BIO_get_fp(BIO *bio, FILE **out_file) {
@@ -280,8 +276,8 @@ int BIO_rw_filename(BIO *bio, const char *filename) {
(char *)filename);
}
long BIO_tell(BIO *bio) { return BIO_ctrl(bio, BIO_C_FILE_TELL, 0, NULL); }
long BIO_tell(BIO *bio) { return BIO_ctrl(bio, BIO_C_FILE_TELL, 0, nullptr); }
long BIO_seek(BIO *bio, long offset) {
return BIO_ctrl(bio, BIO_C_FILE_SEEK, offset, NULL);
return BIO_ctrl(bio, BIO_C_FILE_SEEK, offset, nullptr);
}
+19 -12
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bio.h>
@@ -15,6 +20,8 @@
#include "../internal.h"
using namespace bssl;
namespace {
// hexdump_ctx contains the state of a hexdump.
struct hexdump_ctx {
@@ -39,8 +46,8 @@ static char to_char(uint8_t b) {
return b;
}
// hexdump_write adds |len| bytes of |data| to the current hex dump described by
// |ctx|.
// hexdump_write adds `len` bytes of `data` to the current hex dump described by
// `ctx`.
static int hexdump_write(struct hexdump_ctx *ctx, const uint8_t *data,
size_t len) {
char buf[10];
@@ -99,9 +106,9 @@ static int hexdump_write(struct hexdump_ctx *ctx, const uint8_t *data,
return 1;
}
// finish flushes any buffered data in |ctx|.
// finish flushes any buffered data in `ctx`.
static int finish(struct hexdump_ctx *ctx) {
// See the comments in |hexdump| for the details of this format.
// See the comments in `hexdump` for the details of this format.
const unsigned n_bytes = ctx->used;
unsigned l;
char buf[5];
+85 -31
View File
@@ -1,16 +1,26 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSSL_HEADER_BIO_INTERNAL_H
#define OPENSSL_HEADER_BIO_INTERNAL_H
#ifndef OPENSSL_HEADER_CRYPTO_BIO_INTERNAL_H
#define OPENSSL_HEADER_CRYPTO_BIO_INTERNAL_H
#include <CNIOBoringSSL_base.h>
#include <CNIOBoringSSL_bio.h>
#include <CNIOBoringSSL_ex_data.h>
#include "../internal.h"
#include "../mem_internal.h"
#if !defined(OPENSSL_NO_SOCK)
#if !defined(OPENSSL_WINDOWS)
@@ -18,57 +28,101 @@
// newlib uses u_short in socket.h without defining it.
typedef unsigned short u_short;
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/types.h>
#else
OPENSSL_MSVC_PRAGMA(warning(push, 3))
#include <winsock2.h>
OPENSSL_MSVC_PRAGMA(warning(pop))
typedef int socklen_t;
#endif
#endif // !OPENSSL_NO_SOCK
#if defined(__cplusplus)
extern "C" {
#endif
DECLARE_OPAQUE_STRUCT(bio_st, Bio)
struct bio_method_st {
int type;
int (*bwrite)(BIO *, const char *, int);
int (*bwrite_ex)(BIO *, const char *, size_t, size_t *);
int (*bread)(BIO *, char *, int);
int (*bgets)(BIO *, char *, int);
long (*ctrl)(BIO *, int, long, void *);
int (*create)(BIO *);
int (*destroy)(BIO *);
long (*callback_ctrl)(BIO *, int, BIO_info_cb *);
};
BSSL_NAMESPACE_BEGIN
class Bio : public bio_st, public RefCounted<Bio> {
public:
explicit Bio(const BIO_METHOD *m);
const BIO_METHOD *method;
CRYPTO_EX_DATA ex_data;
// TODO(crbug.com/412269080): `init` and `shutdown` could be bitfields, or
// integrated into `flags`, to save memory.
// init is non-zero if this `BIO` has been initialised.
int init = 0;
// shutdown is often used by specific `BIO_METHOD`s to determine whether
// they own some underlying resource. This flag can often be controlled by
// `BIO_set_close`. For example, whether an fd BIO closes the underlying fd
// when it, itself, is closed.
int shutdown = 1;
int flags = 0;
int retry_reason = 0;
// num is a BIO-specific value. For example, in fd BIOs it's used to store a
// file descriptor.
int num = 0;
void *ptr = nullptr;
// next_bio points to the next `BIO` in a chain. This `BIO` owns a reference
// to `next_bio`.
Bio *next_bio = nullptr; // used by filter BIOs
uint64_t num_read = 0, num_write = 0;
private:
friend RefCounted;
~Bio();
};
#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.
// 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,
struct sockaddr_storage *out_addr,
socklen_t *out_addr_length,
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.
//
// TODO(fork): remove all callers of this.
void bio_clear_socket_error(void);
void bio_clear_socket_error();
// bio_sock_error returns the last socket error on |sock|.
int bio_sock_error(int sock);
// bio_socket_finish_connect attempts to complete an in-progress, non-blocking
// connect operation on `sock`. It returns one if the connect operation
// succeeded. Otherwise, it returns zero and sets the last socket error to the
// reason it failed.
int bio_socket_finish_connect(int sock);
// bio_socket_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.
// bio_errno_should_retry returns non-zero if `return_value` indicates an error
// and `errno` indicates that it's non-fatal.
int bio_errno_should_retry(int return_value);
BSSL_NAMESPACE_END
#if defined(__cplusplus)
} // extern C
#endif
#endif // OPENSSL_HEADER_BIO_INTERNAL_H
#endif // OPENSSL_HEADER_CRYPTO_BIO_INTERNAL_H
+128 -143
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bio.h>
@@ -16,112 +21,105 @@
#include <CNIOBoringSSL_mem.h>
#include "../internal.h"
#include "../mem_internal.h"
#include "internal.h"
using namespace bssl;
namespace {
struct bio_bio_st {
BIO *peer; // NULL if buf == NULL.
// If peer != NULL, then peer->ptr is also a bio_bio_st,
// and its "peer" member points back to us.
// peer != NULL iff init != 0 in the BIO.
BIO *peer = nullptr; // NULL if buf == NULL.
// If peer != NULL, then BIO_get_data(peer) is also a
// bio_bio_st, and its "peer" member points back to us.
// peer != NULL iff init != 0 in the BIO.
// This is for what we write (i.e. reading uses peer's struct):
int closed; // valid iff peer != NULL
size_t len; // valid iff buf != NULL; 0 if peer == NULL
size_t offset; // valid iff buf != NULL; 0 if len == 0
size_t size;
uint8_t *buf; // "size" elements (if != NULL)
int closed = 0; // valid iff peer != NULL
size_t len = 0; // valid iff buf != NULL; 0 if peer == NULL
size_t offset = 0; // valid iff buf != NULL; 0 if len == 0
size_t size = 0;
uint8_t *buf = nullptr; // "size" elements (if != NULL)
size_t request; // valid iff peer != NULL; 0 if len != 0,
// otherwise set by peer to number of bytes
// it (unsuccessfully) tried to read,
// never more than buffer space (size-len) warrants.
size_t request = 0; // valid iff peer != NULL; 0 if len != 0,
// otherwise set by peer to number of bytes
// it (unsuccessfully) tried to read,
// never more than buffer space (size-len) warrants.
};
} // namespace
static int bio_new(BIO *bio) {
struct bio_bio_st *b =
reinterpret_cast<bio_bio_st *>(OPENSSL_zalloc(sizeof *b));
if (b == NULL) {
struct bio_bio_st *b = New<struct bio_bio_st>();
if (b == nullptr) {
return 0;
}
b->size = 17 * 1024; // enough for one TLS record (just a default)
bio->ptr = b;
BIO_set_data(bio, b);
return 1;
}
static void bio_destroy_pair(BIO *bio) {
struct bio_bio_st *b = reinterpret_cast<bio_bio_st *>(bio->ptr);
struct bio_bio_st *b = reinterpret_cast<bio_bio_st *>(BIO_get_data(bio));
BIO *peer_bio;
struct bio_bio_st *peer_b;
if (b == NULL) {
if (b == nullptr) {
return;
}
peer_bio = b->peer;
if (peer_bio == NULL) {
if (peer_bio == nullptr) {
return;
}
peer_b = reinterpret_cast<bio_bio_st *>(peer_bio->ptr);
peer_b = reinterpret_cast<bio_bio_st *>(BIO_get_data(peer_bio));
assert(peer_b != NULL);
assert(peer_b != nullptr);
assert(peer_b->peer == bio);
peer_b->peer = NULL;
peer_bio->init = 0;
assert(peer_b->buf != NULL);
peer_b->peer = nullptr;
BIO_set_init(peer_bio, 0);
assert(peer_b->buf != nullptr);
peer_b->len = 0;
peer_b->offset = 0;
b->peer = NULL;
bio->init = 0;
assert(b->buf != NULL);
b->peer = nullptr;
BIO_set_init(bio, 0);
assert(b->buf != nullptr);
b->len = 0;
b->offset = 0;
}
static int bio_free(BIO *bio) {
struct bio_bio_st *b = reinterpret_cast<bio_bio_st *>(bio->ptr);
struct bio_bio_st *b = reinterpret_cast<bio_bio_st *>(BIO_get_data(bio));
assert(b != NULL);
assert(b != nullptr);
if (b->peer) {
bio_destroy_pair(bio);
}
OPENSSL_free(b->buf);
OPENSSL_free(b);
Delete(b);
return 1;
}
static int bio_read(BIO *bio, char *buf, int size_) {
size_t size = size_;
size_t rest;
struct bio_bio_st *b, *peer_b;
BIO_clear_retry_flags(bio);
if (!bio->init) {
return 0;
}
b = reinterpret_cast<bio_bio_st *>(bio->ptr);
assert(b != NULL);
assert(b->peer != NULL);
peer_b = reinterpret_cast<bio_bio_st *>(b->peer->ptr);
assert(peer_b != NULL);
assert(peer_b->buf != NULL);
bio_bio_st *b = reinterpret_cast<bio_bio_st *>(BIO_get_data(bio));
assert(b != nullptr);
assert(b->peer != nullptr);
bio_bio_st *peer_b = reinterpret_cast<bio_bio_st *>(BIO_get_data(b->peer));
assert(peer_b != nullptr);
assert(peer_b->buf != nullptr);
peer_b->request = 0; // will be set in "retry_read" situation
if (buf == NULL || size == 0) {
return 0;
}
if (peer_b->len == 0) {
if (peer_b->closed) {
return 0; // writer has closed, and no data is left
@@ -144,7 +142,7 @@ static int bio_read(BIO *bio, char *buf, int size_) {
}
// now read "size" bytes
rest = size;
size_t rest = size;
assert(rest > 0);
// one or two iterations
@@ -178,38 +176,31 @@ static int bio_read(BIO *bio, char *buf, int size_) {
rest -= chunk;
} while (rest);
// |size| is bounded by the buffer size, which fits in |int|.
// `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_) {
size_t num = num_;
size_t rest;
struct bio_bio_st *b;
static int bio_write_ex(BIO *bio, const char *buf, size_t num,
size_t *out_written) {
BIO_clear_retry_flags(bio);
if (!bio->init || buf == NULL || num == 0) {
return 0;
}
b = reinterpret_cast<bio_bio_st *>(bio->ptr);
assert(b != NULL);
assert(b->peer != NULL);
assert(b->buf != NULL);
struct bio_bio_st *b = reinterpret_cast<bio_bio_st *>(BIO_get_data(bio));
assert(b != nullptr);
assert(b->peer != nullptr);
assert(b->buf != nullptr);
b->request = 0;
if (b->closed) {
// we already closed
OPENSSL_PUT_ERROR(BIO, BIO_R_BROKEN_PIPE);
return -1;
return 0;
}
assert(b->len <= b->size);
if (b->len == b->size) {
BIO_set_retry_write(bio); // buffer is full
return -1;
return 0;
}
// we can write
@@ -218,7 +209,7 @@ static int bio_write(BIO *bio, const char *buf, int num_) {
}
// now write "num" bytes
rest = num;
size_t rest = num;
assert(rest > 0);
// one or two iterations
@@ -251,43 +242,43 @@ static int bio_write(BIO *bio, const char *buf, int num_) {
buf += chunk;
} while (rest);
// |num| is bounded by the buffer size, which fits in |int|.
return (int)num;
*out_written = num;
return 1;
}
static int bio_make_pair(BIO *bio1, BIO *bio2, size_t writebuf1_len,
size_t writebuf2_len) {
struct bio_bio_st *b1, *b2;
assert(bio1 != NULL);
assert(bio2 != NULL);
assert(bio1 != nullptr);
assert(bio2 != nullptr);
b1 = reinterpret_cast<bio_bio_st *>(bio1->ptr);
b2 = reinterpret_cast<bio_bio_st *>(bio2->ptr);
b1 = reinterpret_cast<bio_bio_st *>(BIO_get_data(bio1));
b2 = reinterpret_cast<bio_bio_st *>(BIO_get_data(bio2));
if (b1->peer != NULL || b2->peer != NULL) {
if (b1->peer != nullptr || b2->peer != nullptr) {
OPENSSL_PUT_ERROR(BIO, BIO_R_IN_USE);
return 0;
}
if (b1->buf == NULL) {
if (b1->buf == nullptr) {
if (writebuf1_len) {
b1->size = writebuf1_len;
}
b1->buf = reinterpret_cast<uint8_t *>(OPENSSL_malloc(b1->size));
if (b1->buf == NULL) {
if (b1->buf == nullptr) {
return 0;
}
b1->len = 0;
b1->offset = 0;
}
if (b2->buf == NULL) {
if (b2->buf == nullptr) {
if (writebuf2_len) {
b2->size = writebuf2_len;
}
b2->buf = reinterpret_cast<uint8_t *>(OPENSSL_malloc(b2->size));
if (b2->buf == NULL) {
if (b2->buf == nullptr) {
return 0;
}
b2->len = 0;
@@ -301,40 +292,39 @@ static int bio_make_pair(BIO *bio1, BIO *bio2, size_t writebuf1_len,
b2->closed = 0;
b2->request = 0;
bio1->init = 1;
bio2->init = 1;
BIO_set_init(bio1, 1);
BIO_set_init(bio2, 1);
return 1;
}
static long bio_ctrl(BIO *bio, int cmd, long num, void *ptr) {
long ret;
struct bio_bio_st *b = reinterpret_cast<bio_bio_st *>(bio->ptr);
assert(b != NULL);
struct bio_bio_st *b = reinterpret_cast<bio_bio_st *>(BIO_get_data(bio));
assert(b != nullptr);
switch (cmd) {
// Specific control codes first:
case BIO_C_GET_WRITE_BUF_SIZE:
ret = (long)b->size;
break;
// TODO(crbug.com/412584975): This can overflow on 64-bit Windows. Do we
// need it? It implements `BIO_get_write_buf_size`, but we don't have the
// wrapper.
return static_cast<long>(b->size);
case BIO_C_GET_WRITE_GUARANTEE:
// How many bytes can the caller feed to the next write
// without having to keep any?
if (b->peer == NULL || b->closed) {
ret = 0;
} else {
ret = (long)b->size - b->len;
if (b->peer == nullptr || b->closed) {
return 0;
}
break;
// TODO(crbug.com/412584975): This can overflow on 64-bit Windows.
return static_cast<long>(b->size - b->len);
case BIO_C_GET_READ_REQUEST:
// If the peer unsuccessfully tried to read, how many bytes
// were requested? (As with BIO_CTRL_PENDING, that number
// can usually be treated as boolean.)
ret = (long)b->request;
break;
//
// TODO(crbug.com/412584975): This can overflow on 64-bit Windows.
return static_cast<long>(b->request);
case BIO_C_RESET_READ_REQUEST:
// Reset request. (Can be useful after read attempts
@@ -342,84 +332,79 @@ static long bio_ctrl(BIO *bio, int cmd, long num, void *ptr) {
// e.g. when probing SSL_read to see if any data is
// available.)
b->request = 0;
ret = 1;
break;
return 1;
case BIO_C_SHUTDOWN_WR:
// similar to shutdown(..., SHUT_WR)
b->closed = 1;
ret = 1;
break;
return 1;
// Standard control codes:
case BIO_CTRL_GET_CLOSE:
ret = bio->shutdown;
break;
return BIO_get_shutdown(bio);
case BIO_CTRL_SET_CLOSE:
bio->shutdown = (int)num;
ret = 1;
break;
BIO_set_shutdown(bio, static_cast<int>(num));
return 1;
case BIO_CTRL_PENDING:
if (b->peer != NULL) {
if (b->peer != nullptr) {
struct bio_bio_st *peer_b =
reinterpret_cast<bio_bio_st *>(b->peer->ptr);
ret = (long)peer_b->len;
} else {
ret = 0;
reinterpret_cast<bio_bio_st *>(BIO_get_data(b->peer));
// TODO(crbug.com/412584975): This can overflow on 64-bit Windows.
return static_cast<long>(peer_b->len);
}
break;
return 0;
case BIO_CTRL_WPENDING:
ret = 0;
if (b->buf != NULL) {
ret = (long)b->len;
if (b->buf == nullptr) {
return 0;
}
break;
// TODO(crbug.com/412584975): This can overflow on 64-bit Windows.
return static_cast<long>(b->len);
case BIO_CTRL_FLUSH:
ret = 1;
break;
return 1;
case BIO_CTRL_EOF: {
BIO *other_bio = reinterpret_cast<BIO *>(ptr);
if (other_bio) {
struct bio_bio_st *other_b =
reinterpret_cast<bio_bio_st *>(other_bio->ptr);
assert(other_b != NULL);
ret = other_b->len == 0 && other_b->closed;
} else {
ret = 1;
if (b->peer) {
auto *peer_b = reinterpret_cast<bio_bio_st *>(BIO_get_data(b->peer));
assert(peer_b != nullptr);
return peer_b->len == 0 && peer_b->closed;
}
} break;
return 1;
}
default:
ret = 0;
return 0;
}
return ret;
}
static const BIO_METHOD methods_biop = {
BIO_TYPE_BIO, "BIO pair", bio_write, bio_read, NULL /* puts */,
NULL /* gets */, bio_ctrl, bio_new, bio_free, NULL /* callback_ctrl */,
BIO_TYPE_BIO,
/*bwrite=*/nullptr,
bio_write_ex,
bio_read,
/*gets=*/nullptr,
bio_ctrl,
bio_new,
bio_free,
/*callback_ctrl=*/nullptr,
};
static const BIO_METHOD *bio_s_bio(void) { return &methods_biop; }
static const BIO_METHOD *bio_s_bio() { return &methods_biop; }
int BIO_new_bio_pair(BIO **bio1_p, size_t writebuf1_len, BIO **bio2_p,
size_t writebuf2_len) {
BIO *bio1 = BIO_new(bio_s_bio());
BIO *bio2 = BIO_new(bio_s_bio());
if (bio1 == NULL || bio2 == NULL ||
if (bio1 == nullptr || bio2 == nullptr ||
!bio_make_pair(bio1, bio2, writebuf1_len, writebuf2_len)) {
BIO_free(bio1);
BIO_free(bio2);
*bio1_p = NULL;
*bio2_p = NULL;
*bio1_p = nullptr;
*bio2_p = nullptr;
return 0;
}
@@ -429,13 +414,13 @@ int BIO_new_bio_pair(BIO **bio1_p, size_t writebuf1_len, BIO **bio2_p,
}
size_t BIO_ctrl_get_read_request(BIO *bio) {
return BIO_ctrl(bio, BIO_C_GET_READ_REQUEST, 0, NULL);
return BIO_ctrl(bio, BIO_C_GET_READ_REQUEST, 0, nullptr);
}
size_t BIO_ctrl_get_write_guarantee(BIO *bio) {
return BIO_ctrl(bio, BIO_C_GET_WRITE_GUARANTEE, 0, NULL);
return BIO_ctrl(bio, BIO_C_GET_WRITE_GUARANTEE, 0, nullptr);
}
int BIO_shutdown_wr(BIO *bio) {
return (int)BIO_ctrl(bio, BIO_C_SHUTDOWN_WR, 0, NULL);
return (int)BIO_ctrl(bio, BIO_C_SHUTDOWN_WR, 0, nullptr);
}
+14 -9
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bio.h>
@@ -34,7 +39,7 @@ int BIO_printf(BIO *bio, const char *format, ...) {
// include a trailing NUL, but the buffer must be sized for it.
out = reinterpret_cast<char *>(OPENSSL_malloc(requested_len + 1));
out_malloced = 1;
if (out == NULL) {
if (out == nullptr) {
return -1;
}
va_start(args, format);
+129 -61
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bio.h>
@@ -13,47 +18,43 @@
#include <fcntl.h>
#include <string.h>
#include <limits.h>
#include <algorithm>
#if !defined(OPENSSL_WINDOWS)
#include <unistd.h>
#else
OPENSSL_MSVC_PRAGMA(warning(push, 3))
#include <winsock2.h>
OPENSSL_MSVC_PRAGMA(warning(pop))
OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
#endif
#include "internal.h"
using namespace bssl;
#if !defined(OPENSSL_WINDOWS)
static int closesocket(int sock) {
return close(sock);
}
static int closesocket(int sock) { return close(sock); }
#endif
static int sock_free(BIO *bio) {
if (bio->shutdown) {
if (bio->init) {
closesocket(bio->num);
if (BIO_get_shutdown(bio)) {
if (BIO_get_init(bio)) {
closesocket(FromOpaque(bio)->num);
}
bio->init = 0;
bio->flags = 0;
BIO_set_init(bio, 0);
BIO_clear_retry_flags(bio);
}
return 1;
}
static int sock_read(BIO *b, char *out, int outl) {
if (out == NULL) {
return 0;
}
bio_clear_socket_error();
#if defined(OPENSSL_WINDOWS)
int ret = recv(b->num, out, outl, 0);
int ret = recv(FromOpaque(b)->num, out, outl, 0);
#else
int ret = (int)read(b->num, out, outl);
int ret = (int)read(FromOpaque(b)->num, out, outl);
#endif
BIO_clear_retry_flags(b);
if (ret <= 0) {
@@ -64,79 +65,146 @@ static int sock_read(BIO *b, char *out, int outl) {
return ret;
}
static int sock_write(BIO *b, const char *in, int inl) {
static int sock_write_ex(BIO *b, const char *in, size_t inl,
size_t *out_written) {
bio_clear_socket_error();
#if defined(OPENSSL_WINDOWS)
int ret = send(b->num, in, inl, 0);
inl = std::min(inl, size_t{INT_MAX});
int ret = send(FromOpaque(b)->num, in, static_cast<int>(inl), 0);
#else
int ret = (int)write(b->num, in, inl);
ssize_t ret = write(FromOpaque(b)->num, in, inl);
#endif
BIO_clear_retry_flags(b);
if (ret <= 0) {
if (bio_socket_should_retry(ret)) {
BIO_set_retry_write(b);
}
return 0;
}
return ret;
*out_written = ret;
return 1;
}
static long sock_ctrl(BIO *b, int cmd, long num, void *ptr) {
long ret = 1;
int *ip;
switch (cmd) {
case BIO_C_SET_FD:
sock_free(b);
b->num = *((int *)ptr);
b->shutdown = (int)num;
b->init = 1;
break;
FromOpaque(b)->num = *static_cast<int *>(ptr);
BIO_set_shutdown(b, static_cast<int>(num));
BIO_set_init(b, 1);
return 1;
case BIO_C_GET_FD:
if (b->init) {
ip = (int *)ptr;
if (ip != NULL) {
*ip = b->num;
if (BIO_get_init(b)) {
int *out = static_cast<int *>(ptr);
if (out != nullptr) {
*out = FromOpaque(b)->num;
}
ret = b->num;
} else {
ret = -1;
return FromOpaque(b)->num;
}
break;
return -1;
case BIO_CTRL_GET_CLOSE:
ret = b->shutdown;
break;
return BIO_get_shutdown(b);
case BIO_CTRL_SET_CLOSE:
b->shutdown = (int)num;
break;
BIO_set_shutdown(b, static_cast<int>(num));
return 1;
case BIO_CTRL_FLUSH:
ret = 1;
break;
return 1;
default:
ret = 0;
break;
return 0;
}
return ret;
}
static const BIO_METHOD methods_sockp = {
BIO_TYPE_SOCKET, "socket",
sock_write, sock_read,
NULL /* puts */, NULL /* gets, */,
sock_ctrl, NULL /* create */,
sock_free, NULL /* callback_ctrl */,
BIO_TYPE_SOCKET,
/*bwrite=*/nullptr, sock_write_ex,
sock_read, nullptr /* gets, */,
sock_ctrl, nullptr /* create */,
sock_free, nullptr /* callback_ctrl */,
};
const BIO_METHOD *BIO_s_socket(void) { return &methods_sockp; }
const BIO_METHOD *BIO_s_socket() { return &methods_sockp; }
BIO *BIO_new_socket(int fd, int close_flag) {
BIO *ret;
ret = BIO_new(BIO_s_socket());
if (ret == NULL) {
return NULL;
if (ret == nullptr) {
return nullptr;
}
BIO_set_fd(ret, fd, close_flag);
return ret;
}
// These functions are provided solely for compatibility with software that
// tries to copy and then modify `BIO_s_socket`. See bio.h for details.
// PostgreSQL's use makes several fragile assumptions on `BIO_s_socket`:
//
// - We do not store anything in `BIO_set_data`. (Broken in upstream OpenSSL,
// which broke PostgreSQL.)
// - We do not store anything in `BIO_set_app_data`.
// - `BIO_s_socket` is implemented internally using the non-`size_t`-clean
// I/O functions rather than the `size_t`-clean ones.
// - `BIO_METHOD` never gains another function pointer that is used in concert
// with any of the functions here.
//
// Some other projects doing similar things use `BIO_meth_get_read` and
// `BIO_meth_get_write` and in turn assume that `BIO_s_socket` has not been
// ported to the `size_t`-clean `BIO_read_ex` and `BIO_write_ex`. (Not yet
// implemented in BoringSSL.)
//
// This is hopelessly fragile. PostgreSQL 18 will include a fix to stop using
// these APIs, but older versions and other software remain impacted, so we
// implement these functions, but only support `BIO_s_socket`. For now they just
// return the underlying functions, but if we ever need to break the above
// assumptions, we can return an older, frozen version of `BIO_s_socket`.
// Limiting to exactly one allowed `BIO_METHOD` lets us do this.
//
// These functions are also deprecated in upstream OpenSSL. See
// https://github.com/openssl/openssl/issues/26047
//
// TODO(davidben): Once Folly and all versions of PostgreSQL we care about are
// updated or patched, remove these functions.
int (*BIO_meth_get_write(const BIO_METHOD *method))(BIO *, const char *, int) {
BSSL_CHECK(method == BIO_s_socket());
return method->bwrite;
}
int (*BIO_meth_get_read(const BIO_METHOD *method))(BIO *, char *, int) {
BSSL_CHECK(method == BIO_s_socket());
return method->bread;
}
int (*BIO_meth_get_gets(const BIO_METHOD *method))(BIO *, char *, int) {
BSSL_CHECK(method == BIO_s_socket());
return method->bgets;
}
int (*BIO_meth_get_puts(const BIO_METHOD *method))(BIO *, const char *) {
BSSL_CHECK(method == BIO_s_socket());
return nullptr;
}
long (*BIO_meth_get_ctrl(const BIO_METHOD *method))(BIO *, int, long, void *) {
BSSL_CHECK(method == BIO_s_socket());
return method->ctrl;
}
int (*BIO_meth_get_create(const BIO_METHOD *method))(BIO *) {
BSSL_CHECK(method == BIO_s_socket());
return method->create;
}
int (*BIO_meth_get_destroy(const BIO_METHOD *method))(BIO *) {
BSSL_CHECK(method == BIO_s_socket());
return method->destroy;
}
long (*BIO_meth_get_callback_ctrl(const BIO_METHOD *method))(BIO *, int,
bio_info_cb) {
BSSL_CHECK(method == BIO_s_socket());
return method->callback_ctrl;
}
#endif // OPENSSL_NO_SOCK
@@ -1,16 +1,16 @@
/* Copyright 2014 The BoringSSL Authors
*
* 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. */
// Copyright 2014 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if defined(__linux__)
#undef _POSIX_C_SOURCE
@@ -27,19 +27,21 @@
#include <sys/types.h>
#if !defined(OPENSSL_WINDOWS)
#include <errno.h>
#include <netdb.h>
#include <poll.h>
#include <unistd.h>
#else
OPENSSL_MSVC_PRAGMA(warning(push, 3))
#include <winsock2.h>
#include <ws2tcpip.h>
OPENSSL_MSVC_PRAGMA(warning(pop))
#endif
#include "internal.h"
#include "../internal.h"
BSSL_NAMESPACE_BEGIN
int bio_ip_and_port_to_socket_and_addr(int *out_sock,
struct sockaddr_storage *out_addr,
socklen_t *out_addr_length,
@@ -109,16 +111,58 @@ int bio_socket_nbio(int sock, int on) {
#endif
}
void bio_clear_socket_error(void) {}
void bio_clear_socket_error() {}
int bio_sock_error(int sock) {
int bio_socket_finish_connect(int sock) {
// A blocked connect signals whether it is ready based on whether it is
// writable. (SO_ERROR is not filled in before it is writable.)
#if defined(OPENSSL_WINDOWS)
fd_set write_set, except_set;
FD_ZERO(&write_set);
FD_SET(static_cast<SOCKET>(sock), &write_set);
FD_ZERO(&except_set);
FD_SET(static_cast<SOCKET>(sock), &except_set);
timeval timeout = {0, 0};
if (select(0 /* unused on Windows */, /*readfds=*/nullptr, &write_set,
&except_set, &timeout) == SOCKET_ERROR) {
return 0;
}
if (!FD_ISSET(sock, &write_set) && !FD_ISSET(sock, &except_set)) {
// The connect has not completed. Set the error that |connect| would return.
WSASetLastError(WSAEWOULDBLOCK);
return 0;
}
#else
pollfd pfd;
pfd.fd = sock;
// poll implicitly listens for POLLERR and POLLHUP.
pfd.events = POLLOUT;
pfd.revents = 0;
if (poll(&pfd, 1, /*timeout=*/0) < 0) {
return 0;
}
if (pfd.revents == 0) {
// The connect has not completed. Set the error that |connect| would return.
errno = EINPROGRESS;
return 0;
}
#endif
// Check if the connection succeeded.
int error;
socklen_t error_size = sizeof(error);
if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&error, &error_size) < 0) {
return 1;
return 0;
}
return error;
if (error != 0) {
#if defined(OPENSSL_WINDOWS)
WSASetLastError(error);
#else
errno = error;
#endif
return 0;
}
return 1;
}
int bio_socket_should_retry(int return_value) {
@@ -130,4 +174,6 @@ int bio_socket_should_retry(int return_value) {
#endif
}
BSSL_NAMESPACE_END
#endif // OPENSSL_NO_SOCK
+22 -18
View File
@@ -1,23 +1,27 @@
/* Copyright 2021 The BoringSSL Authors
*
* 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. */
// Copyright 2021 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_blake2.h>
#include <assert.h>
#include <iterator>
#include "../internal.h"
using namespace bssl;
// https://tools.ietf.org/html/rfc7693#section-2.6
static const uint64_t kIV[8] = {
UINT64_C(0x6a09e667f3bcc908), UINT64_C(0xbb67ae8584caa73b),
@@ -64,7 +68,7 @@ static void blake2b_transform(BLAKE2B_CTX *b2b,
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), "");
static_assert(sizeof(v) == sizeof(b2b->h) + sizeof(kIV));
OPENSSL_memcpy(v, b2b->h, sizeof(b2b->h));
OPENSSL_memcpy(&v[8], kIV, sizeof(kIV));
@@ -99,7 +103,7 @@ static void blake2b_transform(BLAKE2B_CTX *b2b,
blake2b_load(block, s[15]));
}
for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(b2b->h); i++) {
for (size_t i = 0; i < std::size(b2b->h); i++) {
b2b->h[i] ^= v[i];
b2b->h[i] ^= v[i + 8];
}
@@ -108,7 +112,7 @@ static void blake2b_transform(BLAKE2B_CTX *b2b,
void BLAKE2B256_Init(BLAKE2B_CTX *b2b) {
OPENSSL_memset(b2b, 0, sizeof(BLAKE2B_CTX));
static_assert(sizeof(kIV) == sizeof(b2b->h), "");
static_assert(sizeof(kIV) == sizeof(b2b->h));
OPENSSL_memcpy(&b2b->h, kIV, sizeof(kIV));
// https://tools.ietf.org/html/rfc7693#section-2.5
@@ -135,7 +139,7 @@ void BLAKE2B256_Update(BLAKE2B_CTX *b2b, const void *in_data, size_t len) {
return;
}
// More input remains therefore we must have filled |b2b->block|.
// More input remains therefore we must have filled `b2b->block`.
assert(b2b->block_used == BLAKE2B_CBLOCK);
blake2b_transform(b2b, b2b->block, BLAKE2B_CBLOCK,
/*is_final_block=*/0);
@@ -156,7 +160,7 @@ void BLAKE2B256_Final(uint8_t out[BLAKE2B256_DIGEST_LENGTH], BLAKE2B_CTX *b2b) {
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), "");
static_assert(BLAKE2B256_DIGEST_LENGTH <= sizeof(b2b->h));
memcpy(out, b2b->h, BLAKE2B256_DIGEST_LENGTH);
}
+15 -15
View File
@@ -1,16 +1,16 @@
/* Copyright 2015 The BoringSSL Authors
*
* 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. */
// Copyright 2015 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bn.h>
@@ -32,7 +32,7 @@ int BN_parse_asn1_unsigned(CBS *cbs, BIGNUM *ret) {
return 0;
}
return BN_bin2bn(CBS_data(&child), CBS_len(&child), ret) != NULL;
return BN_bin2bn(CBS_data(&child), CBS_len(&child), ret) != nullptr;
}
int BN_marshal_asn1(CBB *cbb, const BIGNUM *bn) {
@@ -45,7 +45,7 @@ int BN_marshal_asn1(CBB *cbb, const BIGNUM *bn) {
CBB child;
if (!CBB_add_asn1(cbb, &child, CBS_ASN1_INTEGER) ||
// The number must be padded with a leading zero if the high bit would
// otherwise be set or if |bn| is zero.
// otherwise be set or if `bn` is zero.
(BN_num_bits(bn) % 8 == 0 && !CBB_add_u8(&child, 0x00)) ||
!BN_bn2cbb_padded(&child, BN_num_bytes(bn), bn) ||
!CBB_flush(cbb)) {
+69 -78
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bn.h>
@@ -14,6 +19,8 @@
#include <limits.h>
#include <stdio.h>
#include <algorithm>
#include <CNIOBoringSSL_bio.h>
#include <CNIOBoringSSL_bytestring.h>
#include <CNIOBoringSSL_err.h>
@@ -22,6 +29,8 @@
#include "../fipsmodule/bn/internal.h"
using namespace bssl;
int BN_bn2cbb_padded(CBB *out, size_t len, const BIGNUM *in) {
uint8_t *ptr;
return CBB_add_space(out, &ptr, len) && BN_bn2bin_padded(ptr, len, in);
@@ -34,8 +43,8 @@ char *BN_bn2hex(const BIGNUM *bn) {
char *buf = reinterpret_cast<char *>(
OPENSSL_malloc(1 /* leading '-' */ + 1 /* zero is non-empty */ +
width * BN_BYTES * 2 + 1 /* trailing NUL */));
if (buf == NULL) {
return NULL;
if (buf == nullptr) {
return nullptr;
}
char *p = buf;
@@ -64,20 +73,20 @@ char *BN_bn2hex(const BIGNUM *bn) {
return buf;
}
// decode_hex decodes |in_len| bytes of hex data from |in| and updates |bn|.
// decode_hex decodes `in_len` bytes of hex data from `in` and updates `bn`.
static int decode_hex(BIGNUM *bn, const char *in, int in_len) {
if (in_len > INT_MAX / 4) {
OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG);
return 0;
}
// |in_len| is the number of hex digits.
// `in_len` is the number of hex digits.
if (!bn_expand(bn, in_len * 4)) {
return 0;
}
int i = 0;
while (in_len > 0) {
// Decode one |BN_ULONG| at a time.
// Decode one `BN_ULONG` at a time.
int todo = BN_BYTES * 2;
if (todo > in_len) {
todo = in_len;
@@ -88,7 +97,7 @@ static int decode_hex(BIGNUM *bn, const char *in, int in_len) {
for (j = todo; j > 0; j--) {
uint8_t hex = 0;
if (!OPENSSL_fromxdigit(&hex, in[in_len - j])) {
// This shouldn't happen. The caller checks |OPENSSL_isxdigit|.
// This shouldn't happen. The caller checks `OPENSSL_isxdigit`.
assert(0);
}
word = (word << 4) | hex;
@@ -102,12 +111,12 @@ static int decode_hex(BIGNUM *bn, const char *in, int in_len) {
return 1;
}
// decode_dec decodes |in_len| bytes of decimal data from |in| and updates |bn|.
// decode_dec decodes `in_len` bytes of decimal data from `in` and updates `bn`.
static int decode_dec(BIGNUM *bn, const char *in, int in_len) {
int i, j;
BN_ULONG l = 0;
// Decode |BN_DEC_NUM| digits at a time.
// Decode `BN_DEC_NUM` digits at a time.
j = BN_DEC_NUM - (in_len % BN_DEC_NUM);
if (j == BN_DEC_NUM) {
j = 0;
@@ -132,11 +141,11 @@ typedef int (*char_test_func)(int c);
static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode,
char_test_func want_char) {
BIGNUM *ret = NULL;
BIGNUM *ret = nullptr;
int neg = 0, i;
int num;
if (in == NULL || *in == 0) {
if (in == nullptr || *in == 0) {
return 0;
}
@@ -149,14 +158,14 @@ static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode,
}
num = i + neg;
if (outp == NULL) {
if (outp == nullptr) {
return num;
}
// in is the start of the hex digits, and it is 'i' long
if (*outp == NULL) {
if (*outp == nullptr) {
ret = BN_new();
if (ret == NULL) {
if (ret == nullptr) {
return 0;
}
} else {
@@ -177,7 +186,7 @@ static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode,
return num;
err:
if (*outp == NULL) {
if (*outp == nullptr) {
BN_free(ret);
}
@@ -191,33 +200,32 @@ int BN_hex2bn(BIGNUM **outp, const char *in) {
char *BN_bn2dec(const BIGNUM *a) {
// It is easier to print strings little-endian, so we assemble it in reverse
// and fix at the end.
BIGNUM *copy = NULL;
CBB cbb;
if (!CBB_init(&cbb, 16) || //
!CBB_add_u8(&cbb, 0 /* trailing NUL */)) {
goto err;
ScopedCBB cbb;
if (!CBB_init(cbb.get(), 16) || //
!CBB_add_u8(cbb.get(), 0 /* trailing NUL */)) {
return nullptr;
}
if (BN_is_zero(a)) {
if (!CBB_add_u8(&cbb, '0')) {
goto err;
if (!CBB_add_u8(cbb.get(), '0')) {
return nullptr;
}
} else {
copy = BN_dup(a);
if (copy == NULL) {
goto err;
UniquePtr<BIGNUM> copy(BN_dup(a));
if (copy == nullptr) {
return nullptr;
}
while (!BN_is_zero(copy)) {
BN_ULONG word = BN_div_word(copy, BN_DEC_CONV);
while (!BN_is_zero(copy.get())) {
BN_ULONG word = BN_div_word(copy.get(), BN_DEC_CONV);
if (word == (BN_ULONG)-1) {
goto err;
return nullptr;
}
const int add_leading_zeros = !BN_is_zero(copy);
const int add_leading_zeros = !BN_is_zero(copy.get());
for (int i = 0; i < BN_DEC_NUM && (add_leading_zeros || word != 0); i++) {
if (!CBB_add_u8(&cbb, '0' + word % 10)) {
goto err;
if (!CBB_add_u8(cbb.get(), '0' + word % 10)) {
return nullptr;
}
word /= 10;
}
@@ -226,30 +234,18 @@ char *BN_bn2dec(const BIGNUM *a) {
}
if (BN_is_negative(a) && //
!CBB_add_u8(&cbb, '-')) {
goto err;
!CBB_add_u8(cbb.get(), '-')) {
return nullptr;
}
uint8_t *data;
size_t len;
if (!CBB_finish(&cbb, &data, &len)) {
goto err;
if (!CBB_finish(cbb.get(), &data, &len)) {
return nullptr;
}
// Reverse the buffer.
for (size_t i = 0; i < len / 2; i++) {
uint8_t tmp = data[i];
data[i] = data[len - 1 - i];
data[len - 1 - i] = tmp;
}
BN_free(copy);
return (char *)data;
err:
BN_free(copy);
CBB_cleanup(&cbb);
return NULL;
std::reverse(data, data + len);
return reinterpret_cast<char *>(data);
}
int BN_dec2bn(BIGNUM **outp, const char *in) {
@@ -280,38 +276,33 @@ int BN_asc2bn(BIGNUM **outp, const char *in) {
}
int BN_print(BIO *bp, const BIGNUM *a) {
int i, j, v, z = 0;
int ret = 0;
if (a->neg && BIO_write(bp, "-", 1) != 1) {
goto end;
return 0;
}
if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) {
goto end;
return 0;
}
for (i = bn_minimal_width(a) - 1; i >= 0; i--) {
for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
int z = 0;
for (int i = bn_minimal_width(a) - 1; i >= 0; i--) {
for (int j = BN_BITS2 - 4; j >= 0; j -= 4) {
// strip leading zeros
v = ((int)(a->d[i] >> (long)j)) & 0x0f;
int v = ((int)(a->d[i] >> (long)j)) & 0x0f;
if (z || v != 0) {
if (BIO_write(bp, &hextable[v], 1) != 1) {
goto end;
return 0;
}
z = 1;
}
}
}
ret = 1;
end:
return ret;
return 1;
}
int BN_print_fp(FILE *fp, const BIGNUM *a) {
BIO *b = BIO_new_fp(fp, BIO_NOCLOSE);
if (b == NULL) {
if (b == nullptr) {
return 0;
}
@@ -341,7 +332,7 @@ size_t BN_bn2mpi(const BIGNUM *in, uint8_t *out) {
return 4;
}
if (out == NULL) {
if (out == nullptr) {
return 4 + len;
}
@@ -362,7 +353,7 @@ size_t BN_bn2mpi(const BIGNUM *in, uint8_t *out) {
BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) {
if (len < 4) {
OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
return NULL;
return nullptr;
}
const size_t in_len = ((size_t)in[0] << 24) | //
((size_t)in[1] << 16) | //
@@ -370,14 +361,14 @@ BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) {
((size_t)in[3]);
if (in_len != len - 4) {
OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
return NULL;
return nullptr;
}
int out_is_alloced = 0;
if (out == NULL) {
if (out == nullptr) {
out = BN_new();
if (out == NULL) {
return NULL;
if (out == nullptr) {
return nullptr;
}
out_is_alloced = 1;
}
@@ -388,11 +379,11 @@ BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) {
}
in += 4;
if (BN_bin2bn(in, in_len, out) == NULL) {
if (BN_bin2bn(in, in_len, out) == nullptr) {
if (out_is_alloced) {
BN_free(out);
}
return NULL;
return nullptr;
}
out->neg = ((*in) & 0x80) != 0;
if (out->neg) {
+102
View File
@@ -0,0 +1,102 @@
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bn.h>
#include <CNIOBoringSSL_err.h>
#include "../fipsmodule/bn/internal.h"
#include "../internal.h"
using namespace bssl;
int BN_mod_pow2(BIGNUM *r, const BIGNUM *a, size_t e) {
if (e == 0 || a->width == 0) {
BN_zero(r);
return 1;
}
size_t num_words = 1 + ((e - 1) / BN_BITS2);
// If `a` definitely has less than `e` bits, just BN_copy.
if ((size_t)a->width < num_words) {
return BN_copy(r, a) != nullptr;
}
// Otherwise, first make sure we have enough space in `r`.
// Note that this will fail if num_words > INT_MAX.
if (!bn_wexpand(r, num_words)) {
return 0;
}
// Copy the content of `a` into `r`.
OPENSSL_memcpy(r->d, a->d, num_words * sizeof(BN_ULONG));
// If `e` isn't word-aligned, we have to mask off some of our bits.
size_t top_word_exponent = e % (sizeof(BN_ULONG) * 8);
if (top_word_exponent != 0) {
r->d[num_words - 1] &= (((BN_ULONG)1) << top_word_exponent) - 1;
}
// Fill in the remaining fields of `r`.
r->neg = a->neg;
r->width = (int)num_words;
bn_set_minimal_width(r);
return 1;
}
int BN_nnmod_pow2(BIGNUM *r, const BIGNUM *a, size_t e) {
if (!BN_mod_pow2(r, a, e)) {
return 0;
}
// If the returned value was non-negative, we're done.
if (BN_is_zero(r) || !r->neg) {
return 1;
}
size_t num_words = 1 + (e - 1) / BN_BITS2;
// Expand `r` to the size of our modulus.
if (!bn_wexpand(r, num_words)) {
return 0;
}
// Clear the upper words of `r`.
OPENSSL_memset(&r->d[r->width], 0, (num_words - r->width) * BN_BYTES);
// Set parameters of `r`.
r->neg = 0;
r->width = (int)num_words;
// Now, invert every word. The idea here is that we want to compute 2^e-`x`,
// which is actually equivalent to the twos-complement representation of `x`
// in `e` bits, which is -x = ~x + 1.
for (int i = 0; i < r->width; i++) {
r->d[i] = ~r->d[i];
}
// If our exponent doesn't span the top word, we have to mask the rest.
size_t top_word_exponent = e % BN_BITS2;
if (top_word_exponent != 0) {
r->d[r->width - 1] &= (((BN_ULONG)1) << top_word_exponent) - 1;
}
// Keep the minimal-width invariant for `BIGNUM`.
bn_set_minimal_width(r);
// Finally, add one, for the reason described above.
return BN_add(r, r, BN_value_one());
}
@@ -0,0 +1,168 @@
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bn.h>
#include <assert.h>
#include <CNIOBoringSSL_err.h>
#include "../fipsmodule/bn/internal.h"
using namespace bssl;
int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) {
BN_CTXScope scope(ctx);
BIGNUM *rr;
if (r == a || r == p) {
rr = BN_CTX_get(ctx);
} else {
rr = r;
}
BIGNUM *v = BN_CTX_get(ctx);
if (rr == nullptr || v == nullptr) {
return 0;
}
if (BN_copy(v, a) == nullptr) {
return 0;
}
int bits = BN_num_bits(p);
if (BN_is_odd(p)) {
if (BN_copy(rr, a) == nullptr) {
return 0;
}
} else {
if (!BN_one(rr)) {
return 0;
}
}
for (int i = 1; i < bits; i++) {
if (!BN_sqr(v, v, ctx)) {
return 0;
}
if (BN_is_bit_set(p, i)) {
if (!BN_mul(rr, rr, v, ctx)) {
return 0;
}
}
}
if (r != rr && !BN_copy(r, rr)) {
return 0;
}
return 1;
}
static int mod_exp_even(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx) {
// No cryptographic operations require modular exponentiation with an even
// modulus. We support it for backwards compatibility with any applications
// that may have relied on the operation, but optimize for simplicity over
// performance with straightforward square-and-multiply routine.
int bits = BN_num_bits(p);
if (bits == 0) {
return BN_one(r);
}
// Make a copy of `a`, in case it aliases `r`.
BN_CTXScope scope(ctx);
BIGNUM *tmp = BN_CTX_get(ctx);
if (tmp == nullptr || !BN_copy(tmp, a)) {
return 0;
}
assert(BN_is_bit_set(p, bits - 1));
if (!BN_copy(r, tmp)) {
return 0;
}
for (int i = bits - 2; i >= 0; i--) {
if (!BN_mod_sqr(r, r, m, ctx) ||
(BN_is_bit_set(p, i) && !BN_mod_mul(r, r, tmp, m, ctx))) {
return 0;
}
}
return 1;
}
int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
BN_CTX *ctx) {
if (m->neg) {
OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
return 0;
}
if (a->neg || BN_ucmp(a, m) >= 0) {
if (!BN_nnmod(r, a, m, ctx)) {
return 0;
}
a = r;
}
if (BN_is_odd(m)) {
return BN_mod_exp_mont(r, a, p, m, ctx, nullptr);
}
return mod_exp_even(r, a, p, m, ctx);
}
int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx,
const BN_MONT_CTX *mont) {
// BN_mod_exp_mont requires reduced inputs.
if (bn_minimal_width(m) == 1) {
a %= m->d[0];
}
UniquePtr<BIGNUM> a_bignum(BN_new());
if (a_bignum == nullptr || !BN_set_word(a_bignum.get(), a)) {
OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR);
return 0;
}
return BN_mod_exp_mont(rr, a_bignum.get(), p, m, ctx, mont);
}
int BN_mod_exp2_mont(BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1,
const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m,
BN_CTX *ctx, const BN_MONT_CTX *mont) {
// Allocate a montgomery context if it was not supplied by the caller.
UniquePtr<BN_MONT_CTX> new_mont;
if (mont == nullptr) {
new_mont.reset(BN_MONT_CTX_new_for_modulus(m, ctx));
if (new_mont == nullptr) {
return 0;
}
mont = new_mont.get();
}
// BN_mod_mul_montgomery removes one Montgomery factor, so passing one
// Montgomery-encoded and one non-Montgomery-encoded value gives a
// non-Montgomery-encoded result.
UniquePtr<BIGNUM> tmp(BN_new());
if (tmp == nullptr || //
!BN_mod_exp_mont(rr, a1, p1, m, ctx, mont) ||
!BN_mod_exp_mont(tmp.get(), a2, p2, m, ctx, mont) ||
!BN_to_montgomery(rr, rr, mont, ctx) ||
!BN_mod_mul_montgomery(rr, rr, tmp.get(), mont, ctx)) {
return 0;
}
return 1;
}
+93
View File
@@ -0,0 +1,93 @@
// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bn.h>
#include <CNIOBoringSSL_err.h>
int BN_sqrt(BIGNUM *out_sqrt, const BIGNUM *in, BN_CTX *ctx) {
BIGNUM *estimate, *tmp, *delta, *last_delta, *tmp2;
int ok = 0, last_delta_valid = 0;
if (in->neg) {
OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
return 0;
}
if (BN_is_zero(in)) {
BN_zero(out_sqrt);
return 1;
}
bssl::BN_CTXScope scope(ctx);
if (out_sqrt == in) {
estimate = BN_CTX_get(ctx);
} else {
estimate = out_sqrt;
}
tmp = BN_CTX_get(ctx);
last_delta = BN_CTX_get(ctx);
delta = BN_CTX_get(ctx);
if (estimate == nullptr || tmp == nullptr || last_delta == nullptr ||
delta == nullptr) {
goto err;
}
// We estimate that the square root of an n-bit number is 2^{n/2}.
if (!BN_lshift(estimate, BN_value_one(), BN_num_bits(in)/2)) {
goto err;
}
// This is Newton's method for finding a root of the equation `estimate`^2 -
// `in` = 0.
for (;;) {
// `estimate` = 1/2 * (`estimate` + `in`/`estimate`)
if (!BN_div(tmp, nullptr, in, estimate, ctx) ||
!BN_add(tmp, tmp, estimate) || !BN_rshift1(estimate, tmp) ||
// `tmp` = `estimate`^2
!BN_sqr(tmp, estimate, ctx) ||
// `delta` = `in` - `tmp`
!BN_sub(delta, in, tmp)) {
OPENSSL_PUT_ERROR(BN, ERR_R_BN_LIB);
goto err;
}
delta->neg = 0;
// The difference between `in` and `estimate` squared is required to always
// decrease. This ensures that the loop always terminates, but I don't have
// a proof that it always finds the square root for a given square.
if (last_delta_valid && BN_cmp(delta, last_delta) >= 0) {
break;
}
last_delta_valid = 1;
tmp2 = last_delta;
last_delta = delta;
delta = tmp2;
}
if (BN_cmp(tmp, in) != 0) {
OPENSSL_PUT_ERROR(BN, BN_R_NOT_A_SQUARE);
goto err;
}
ok = 1;
err:
if (ok && out_sqrt == in && !BN_copy(out_sqrt, estimate)) {
ok = 0;
}
return ok;
}
+19 -13
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_buf.h>
@@ -15,18 +20,19 @@
#include <CNIOBoringSSL_mem.h>
#include "../internal.h"
#include "../mem_internal.h"
BUF_MEM *BUF_MEM_new(void) {
return reinterpret_cast<BUF_MEM *>(OPENSSL_zalloc(sizeof(BUF_MEM)));
}
using namespace bssl;
BUF_MEM *BUF_MEM_new() { return New<BUF_MEM>(); }
void BUF_MEM_free(BUF_MEM *buf) {
if (buf == nullptr) {
return;
}
OPENSSL_free(buf->data);
OPENSSL_free(buf);
Delete(buf);
}
int BUF_MEM_reserve(BUF_MEM *buf, size_t cap) {
@@ -48,7 +54,7 @@ int BUF_MEM_reserve(BUF_MEM *buf, size_t cap) {
char *new_buf =
reinterpret_cast<char *>(OPENSSL_realloc(buf->data, alloc_size));
if (new_buf == NULL) {
if (new_buf == nullptr) {
return 0;
}
@@ -1,16 +1,16 @@
/* Copyright 2016 The BoringSSL Authors
*
* 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. */
// Copyright 2016 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bytestring.h>
@@ -25,24 +25,25 @@
#include "../internal.h"
int CBB_finish_i2d(CBB *cbb, uint8_t **outp) {
using namespace bssl;
int bssl::CBB_finish_i2d(CBB *cbb, uint8_t **outp) {
assert(!cbb->is_child);
assert(cbb->u.base.can_resize);
uint8_t *der;
size_t der_len;
if (!CBB_finish(cbb, &der, &der_len)) {
CBB_cleanup(cbb);
return -1;
}
if (der_len > INT_MAX) {
OPENSSL_free(der);
return -1;
}
if (outp != NULL) {
if (*outp == NULL) {
if (outp != nullptr) {
if (*outp == nullptr) {
*outp = der;
der = NULL;
der = nullptr;
} else {
OPENSSL_memcpy(*outp, der, der_len);
*outp += der_len;
+35 -33
View File
@@ -1,16 +1,16 @@
/* Copyright 2014 The BoringSSL Authors
*
* 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. */
// Copyright 2014 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bytestring.h>
@@ -20,10 +20,12 @@
#include "internal.h"
using namespace bssl;
// 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
// is_string_type returns one if `tag` is a string type and zero otherwise. It
// ignores the constructed bit.
static int is_string_type(CBS_ASN1_TAG tag) {
// While BER supports constructed BIT STRINGS, OpenSSL misparses them. To
@@ -48,10 +50,10 @@ static int is_string_type(CBS_ASN1_TAG tag) {
}
}
// cbs_find_ber walks an ASN.1 structure in |orig_in| and sets |*ber_found|
// cbs_find_ber walks an ASN.1 structure in `orig_in` and sets `*ber_found`
// depending on whether an indefinite length element or constructed string was
// found. The value of |orig_in| is not changed. It returns one on success (i.e.
// |*ber_found| was set) and zero on error.
// 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) {
if (depth > kMaxDepth) {
return 0;
@@ -92,8 +94,8 @@ static int cbs_find_ber(const CBS *orig_in, int *ber_found, uint32_t depth) {
return 1;
}
// cbs_get_eoc returns one if |cbs| begins with an "end of contents" (EOC) value
// and zero otherwise. If an EOC was found, it advances |cbs| past it.
// cbs_get_eoc returns one if `cbs` begins with an "end of contents" (EOC) value
// and zero otherwise. If an EOC was found, it advances `cbs` past it.
static int cbs_get_eoc(CBS *cbs) {
if (CBS_len(cbs) >= 2 &&
CBS_data(cbs)[0] == 0 && CBS_data(cbs)[1] == 0) {
@@ -102,11 +104,11 @@ static int cbs_get_eoc(CBS *cbs) {
return 0;
}
// cbs_convert_ber reads BER data from |in| and writes DER data to |out|. If
// |string_tag| is non-zero, then all elements must match |string_tag| up to the
// constructed bit and primitive element bodies are written to |out| without
// cbs_convert_ber reads BER data from `in` and writes DER data to `out`. If
// `string_tag` is non-zero, then all elements must match `string_tag` up to the
// constructed bit and primitive element bodies are written to `out` without
// element headers. This is used when concatenating the fragments of a
// constructed string. If |looking_for_eoc| is set then any EOC elements found
// constructed string. If `looking_for_eoc` is set then any EOC elements found
// will cause the function to return after consuming it. It returns one on
// success and zero on error.
static int cbs_convert_ber(CBS *in, CBB *out, CBS_ASN1_TAG string_tag,
@@ -128,13 +130,13 @@ static int cbs_convert_ber(CBS *in, CBB *out, CBS_ASN1_TAG string_tag,
int indefinite;
CBB *out_contents, out_contents_storage;
if (!CBS_get_any_ber_asn1_element(in, &contents, &tag, &header_len,
/*out_ber_found=*/NULL, &indefinite)) {
/*out_ber_found=*/nullptr, &indefinite)) {
return 0;
}
if (string_tag != 0) {
// This is part of a constructed string. All elements must match
// |string_tag| up to the constructed bit and get appended to |out|
// `string_tag` up to the constructed bit and get appended to `out`
// without a child element.
if ((tag & ~CBS_ASN1_CONSTRUCTED) != string_tag) {
return 0;
@@ -189,7 +191,7 @@ static int cbs_convert_ber(CBS *in, CBB *out, CBS_ASN1_TAG string_tag,
return looking_for_eoc == 0;
}
int CBS_asn1_ber_to_der(CBS *in, CBS *out, uint8_t **out_storage) {
int bssl::CBS_asn1_ber_to_der(CBS *in, CBS *out, uint8_t **out_storage) {
CBB cbb;
// First, do a quick walk to find any indefinite-length elements. Most of the
@@ -200,10 +202,10 @@ int CBS_asn1_ber_to_der(CBS *in, CBS *out, uint8_t **out_storage) {
}
if (!conversion_needed) {
if (!CBS_get_any_asn1_element(in, out, NULL, NULL)) {
if (!CBS_get_any_asn1_element(in, out, nullptr, nullptr)) {
return 0;
}
*out_storage = NULL;
*out_storage = nullptr;
return 1;
}
@@ -219,21 +221,21 @@ int CBS_asn1_ber_to_der(CBS *in, CBS *out, uint8_t **out_storage) {
return 1;
}
int CBS_get_asn1_implicit_string(CBS *in, CBS *out, uint8_t **out_storage,
CBS_ASN1_TAG outer_tag,
CBS_ASN1_TAG inner_tag) {
int bssl::CBS_get_asn1_implicit_string(CBS *in, CBS *out, uint8_t **out_storage,
CBS_ASN1_TAG outer_tag,
CBS_ASN1_TAG inner_tag) {
assert(!(outer_tag & CBS_ASN1_CONSTRUCTED));
assert(!(inner_tag & CBS_ASN1_CONSTRUCTED));
assert(is_string_type(inner_tag));
if (CBS_peek_asn1_tag(in, outer_tag)) {
// Normal implicitly-tagged string.
*out_storage = NULL;
*out_storage = nullptr;
return CBS_get_asn1(in, out, outer_tag);
}
// Otherwise, try to parse an implicitly-tagged constructed string.
// |CBS_asn1_ber_to_der| is assumed to have run, so only allow one level deep
// `CBS_asn1_ber_to_der` is assumed to have run, so only allow one level deep
// of nesting.
CBB result;
CBS child;
+197 -112
View File
@@ -1,34 +1,42 @@
/* Copyright 2014 The BoringSSL Authors
*
* 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. */
// Copyright 2014 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bytestring.h>
#include <assert.h>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_mem.h>
#include "../internal.h"
#include "../mem_internal.h"
#include "internal.h"
using namespace bssl;
void CBB_zero(CBB *cbb) { OPENSSL_memset(cbb, 0, sizeof(CBB)); }
static void cbb_init(CBB *cbb, uint8_t *buf, size_t cap, int can_resize) {
cbb->is_child = 0;
cbb->child = NULL;
cbb->child = nullptr;
cbb->u.base.buf = buf;
cbb->u.base.len = 0;
cbb->u.base.cap = cap;
@@ -40,7 +48,7 @@ int CBB_init(CBB *cbb, size_t initial_capacity) {
CBB_zero(cbb);
uint8_t *buf = reinterpret_cast<uint8_t *>(OPENSSL_malloc(initial_capacity));
if (initial_capacity > 0 && buf == NULL) {
if (initial_capacity > 0 && buf == nullptr) {
return 0;
}
@@ -55,8 +63,8 @@ int CBB_init_fixed(CBB *cbb, uint8_t *buf, size_t len) {
}
void CBB_cleanup(CBB *cbb) {
// Child |CBB|s are non-owning. They are implicitly discarded and should not
// be used with |CBB_cleanup| or |ScopedCBB|.
// Child `CBB`s are non-owning. They are implicitly discarded and should not
// be used with `CBB_cleanup` or `ScopedCBB`.
assert(!cbb->is_child);
if (cbb->is_child) {
return;
@@ -64,12 +72,14 @@ void CBB_cleanup(CBB *cbb) {
if (cbb->u.base.can_resize) {
OPENSSL_free(cbb->u.base.buf);
cbb->u.base.buf = nullptr;
}
}
static int cbb_buffer_reserve(struct cbb_buffer_st *base, uint8_t **out,
size_t len) {
if (base == NULL) {
if (base == nullptr) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
@@ -92,7 +102,7 @@ static int cbb_buffer_reserve(struct cbb_buffer_st *base, uint8_t **out,
}
uint8_t *newbuf =
reinterpret_cast<uint8_t *>(OPENSSL_realloc(base->buf, newcap));
if (newbuf == NULL) {
if (newbuf == nullptr) {
goto err;
}
@@ -116,7 +126,7 @@ static int cbb_buffer_add(struct cbb_buffer_st *base, uint8_t **out,
if (!cbb_buffer_reserve(base, out, len)) {
return 0;
}
// This will not overflow or |cbb_buffer_reserve| would have failed.
// This will not overflow or `cbb_buffer_reserve` would have failed.
base->len += len;
return 1;
}
@@ -131,18 +141,19 @@ int CBB_finish(CBB *cbb, uint8_t **out_data, size_t *out_len) {
return 0;
}
if (cbb->u.base.can_resize && (out_data == NULL || out_len == NULL)) {
// |out_data| and |out_len| can only be NULL if the CBB is fixed.
if (cbb->u.base.can_resize && (out_data == nullptr || out_len == nullptr)) {
// `out_data` and `out_len` can only be NULL if the CBB is fixed.
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (out_data != NULL) {
if (out_data != nullptr) {
*out_data = cbb->u.base.buf;
}
if (out_len != NULL) {
if (out_len != nullptr) {
*out_len = cbb->u.base.len;
}
cbb->u.base.buf = NULL;
cbb->u.base.buf = nullptr;
CBB_cleanup(cbb);
return 1;
}
@@ -155,41 +166,42 @@ static struct cbb_buffer_st *cbb_get_base(CBB *cbb) {
}
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.
// 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.
// 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
// 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.
// 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
// warning does not know `cbb->child` will not be read once `error` is set
// above.
cbb->child = NULL;
cbb->child = nullptr;
}
// CBB_flush recurses and then writes out any pending length prefix. The
// current length of the underlying base is taken to be the length of the
// length-prefixed data.
int CBB_flush(CBB *cbb) {
// If |base| has hit an error, the buffer is in an undefined state, so
// fail all following calls. In particular, |cbb->child| may point to invalid
// If `base` has hit an error, the buffer is in an undefined state, so
// fail all following calls. In particular, `cbb->child` may point to invalid
// memory.
struct cbb_buffer_st *base = cbb_get_base(cbb);
if (base == NULL || base->error) {
if (base == nullptr || base->error) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (cbb->child == NULL) {
if (cbb->child == nullptr) {
// Nothing to flush.
return 1;
}
@@ -200,8 +212,11 @@ int CBB_flush(CBB *cbb) {
size_t child_start = child->offset + child->pending_len_len;
size_t len;
if (!CBB_flush(cbb->child) || child_start < child->offset ||
base->len < child_start) {
if (!CBB_flush(cbb->child)) {
goto err;
}
if (child_start < child->offset || base->len < child_start) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_INTERNAL_ERROR);
goto err;
}
@@ -241,7 +256,7 @@ int CBB_flush(CBB *cbb) {
if (len_len != 1) {
// We need to move the contents along in order to make space.
size_t extra_bytes = len_len - 1;
if (!cbb_buffer_add(base, NULL, extra_bytes)) {
if (!cbb_buffer_add(base, nullptr, extra_bytes)) {
goto err;
}
OPENSSL_memmove(base->buf + child_start + extra_bytes,
@@ -260,8 +275,8 @@ int CBB_flush(CBB *cbb) {
goto err;
}
child->base = NULL;
cbb->child = NULL;
child->base = nullptr;
cbb->child = nullptr;
return 1;
@@ -270,8 +285,8 @@ err:
return 0;
}
const uint8_t *CBB_data(const CBB *cbb) {
assert(cbb->child == NULL);
uint8_t *CBB_data(const CBB *cbb) {
assert(cbb->child == nullptr);
if (cbb->is_child) {
return cbb->u.child.base->buf + cbb->u.child.offset +
cbb->u.child.pending_len_len;
@@ -280,7 +295,7 @@ const uint8_t *CBB_data(const CBB *cbb) {
}
size_t CBB_len(const CBB *cbb) {
assert(cbb->child == NULL);
assert(cbb->child == nullptr);
if (cbb->is_child) {
assert(cbb->u.child.offset + cbb->u.child.pending_len_len <=
cbb->u.child.base->len);
@@ -292,7 +307,7 @@ size_t CBB_len(const CBB *cbb) {
static int cbb_add_child(CBB *cbb, CBB *out_child, uint8_t len_len,
int is_asn1) {
assert(cbb->child == NULL);
assert(cbb->child == nullptr);
assert(!is_asn1 || len_len == 1);
struct cbb_buffer_st *base = cbb_get_base(cbb);
size_t offset = base->len;
@@ -335,7 +350,7 @@ int CBB_add_u24_length_prefixed(CBB *cbb, CBB *out_contents) {
return cbb_add_length_prefixed(cbb, out_contents, 3);
}
// add_base128_integer encodes |v| as a big-endian base-128 integer where the
// add_base128_integer encodes `v` as a big-endian base-128 integer where the
// high bit of each byte indicates where there is more data. This is the
// encoding used in DER for both high tag number form and OID components.
static int add_base128_integer(CBB *cbb, uint64_t v) {
@@ -361,6 +376,13 @@ static int add_base128_integer(CBB *cbb, uint64_t v) {
return 1;
}
int bssl::cbb_add_decimal_ascii(CBB *out, uint64_t v) {
char buf[DECIMAL_SIZE(uint64_t) + 1];
snprintf(buf, sizeof(buf), "%" PRIu64, v);
return CBB_add_bytes(out, reinterpret_cast<const uint8_t *>(buf),
strlen(buf));
}
int CBB_add_asn1(CBB *cbb, CBB *out_contents, CBS_ASN1_TAG tag) {
if (!CBB_flush(cbb)) {
return 0;
@@ -379,7 +401,7 @@ int CBB_add_asn1(CBB *cbb, CBB *out_contents, CBS_ASN1_TAG tag) {
return 0;
}
// Reserve one byte of length prefix. |CBB_flush| will finish it later.
// Reserve one byte of length prefix. `CBB_flush` will finish it later.
return cbb_add_child(cbb, out_contents, /*len_len=*/1, /*is_asn1=*/1);
}
@@ -419,7 +441,8 @@ int CBB_reserve(CBB *cbb, uint8_t **out_data, size_t len) {
int CBB_did_write(CBB *cbb, size_t len) {
struct cbb_buffer_st *base = cbb_get_base(cbb);
size_t newlen = base->len + len;
if (cbb->child != NULL || newlen < base->len || newlen > base->cap) {
if (cbb->child != nullptr || newlen < base->len || newlen > base->cap) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
base->len = newlen;
@@ -437,8 +460,9 @@ static int cbb_add_u(CBB *cbb, uint64_t v, size_t len_len) {
v >>= 8;
}
// |v| must fit in |len_len| bytes.
// `v` must fit in `len_len` bytes.
if (v != 0) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW);
cbb_on_error(cbb);
return 0;
}
@@ -462,14 +486,23 @@ int CBB_add_u32le(CBB *cbb, uint32_t value) {
return CBB_add_u32(cbb, CRYPTO_bswap4(value));
}
int CBB_add_u48(CBB *cbb, uint64_t value) { return cbb_add_u(cbb, value, 6); }
int CBB_add_u64(CBB *cbb, uint64_t value) { return cbb_add_u(cbb, value, 8); }
int CBB_add_u64le(CBB *cbb, uint64_t value) {
return CBB_add_u64(cbb, CRYPTO_bswap8(value));
}
void CBB_discard(CBB *cbb, size_t len) {
BSSL_CHECK(cbb->child == nullptr);
BSSL_CHECK(len <= CBB_len(cbb));
struct cbb_buffer_st *base = cbb_get_base(cbb);
base->len -= len;
}
void CBB_discard_child(CBB *cbb) {
if (cbb->child == NULL) {
if (cbb->child == nullptr) {
return;
}
@@ -477,8 +510,21 @@ void CBB_discard_child(CBB *cbb) {
assert(cbb->child->is_child);
base->len = cbb->child->u.child.offset;
cbb->child->u.child.base = NULL;
cbb->child = NULL;
cbb->child->u.child.base = nullptr;
cbb->child = nullptr;
}
int CBB_add_asn1_element(CBB *cbb, CBS_ASN1_TAG tag, const uint8_t *data,
size_t data_len) {
CBB child;
if (!CBB_add_asn1(cbb, &child, tag) ||
!CBB_add_bytes(&child, data, data_len) || //
!CBB_flush(cbb)) {
cbb_on_error(cbb);
return 0;
}
return 1;
}
int CBB_add_asn1_uint64(CBB *cbb, uint64_t value) {
@@ -557,14 +603,7 @@ err:
}
int CBB_add_asn1_octet_string(CBB *cbb, const uint8_t *data, size_t data_len) {
CBB child;
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;
}
return 1;
return CBB_add_asn1_element(cbb, CBS_ASN1_OCTETSTRING, data, data_len);
}
int CBB_add_asn1_bool(CBB *cbb, int value) {
@@ -578,9 +617,9 @@ int CBB_add_asn1_bool(CBB *cbb, int value) {
return 1;
}
// parse_dotted_decimal parses one decimal component from |cbs|, where |cbs| is
// parse_dotted_decimal parses one decimal component from `cbs`, where `cbs` is
// an OID literal, e.g., "1.2.840.113554.4.1.72585". It consumes both the
// component and the dot, so |cbs| may be passed into the function again for the
// 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) {
if (!CBS_get_u64_decimal(cbs, out)) {
@@ -608,8 +647,8 @@ int CBB_add_asn1_oid_from_text(CBB *cbb, const char *text, size_t len) {
return 0;
}
// The first component is encoded as 40 * |a| + |b|. This assumes that |a| is
// 0, 1, or 2 and that, when it is 0 or 1, |b| is at most 39.
// The first component is encoded as 40 * `a` + `b`. This assumes that `a` is
// 0, 1, or 2 and that, when it is 0 or 1, `b` is at most 39.
if (a > 2 || (a < 2 && b > 39) || b > UINT64_MAX - 80 ||
!add_base128_integer(cbb, 40u * a + b)) {
return 0;
@@ -625,23 +664,56 @@ int CBB_add_asn1_oid_from_text(CBB *cbb, const char *text, size_t len) {
return 1;
}
static int compare_set_of_element(const void *a_ptr, const void *b_ptr) {
// See X.690, section 11.6 for the ordering. They are sorted in ascending
// order by their DER encoding.
const CBS *a = reinterpret_cast<const CBS *>(a_ptr),
*b = reinterpret_cast<const CBS *>(b_ptr);
size_t a_len = CBS_len(a), b_len = CBS_len(b);
size_t min_len = a_len < b_len ? a_len : b_len;
int ret = OPENSSL_memcmp(CBS_data(a), CBS_data(b), min_len);
if (ret != 0) {
return ret;
}
if (a_len == b_len) {
int CBB_add_asn1_relative_oid_from_text(CBB *cbb, const char *text,
size_t len) {
if (!CBB_flush(cbb)) {
return 0;
}
// If one is a prefix of the other, the shorter one sorts first. (This is not
// actually reachable. No DER encoding is a prefix of another DER encoding.)
return a_len < b_len ? -1 : 1;
// Relative OIDs must have at least one component.
if (!len) {
return 0;
}
CBS cbs;
CBS_init(&cbs, reinterpret_cast<const uint8_t *>(text), len);
while (CBS_len(&cbs) > 0) {
uint64_t a;
if (!parse_dotted_decimal(&cbs, &a) || !add_base128_integer(cbb, a)) {
return 0;
}
}
return 1;
}
int CBB_add_asn1_relative_oid_from_der_to_text(CBB *cbb, const uint8_t *data,
size_t data_len) {
CBS der;
CBS_init(&der, data, data_len);
// Relative OIDs must have at least one component.
uint64_t v;
if (!CBS_get_asn1_oid_component(&der, &v) || !cbb_add_decimal_ascii(cbb, v)) {
return 0;
}
while (CBS_len(&der) != 0) {
if (!CBS_get_asn1_oid_component(&der, &v) || !CBB_add_u8(cbb, '.') ||
!cbb_add_decimal_ascii(cbb, v)) {
return 0;
}
}
return 1;
}
int CBB_add_asn1_oid_component(CBB *cbb, uint64_t value) {
if (!CBB_flush(cbb)) {
return 0;
}
return add_base128_integer(cbb, value);
}
int CBB_flush_asn1_set_of(CBB *cbb) {
@@ -649,11 +721,10 @@ int CBB_flush_asn1_set_of(CBB *cbb) {
return 0;
}
CBS cbs;
size_t num_children = 0;
CBS_init(&cbs, CBB_data(cbb), CBB_len(cbb));
CBS cbs(CBBAsSpan(cbb));
while (CBS_len(&cbs) != 0) {
if (!CBS_get_any_asn1_element(&cbs, NULL, NULL, NULL)) {
if (!CBS_get_any_asn1_element(&cbs, nullptr, nullptr, nullptr)) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
@@ -665,38 +736,52 @@ int CBB_flush_asn1_set_of(CBB *cbb) {
}
// 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 =
reinterpret_cast<uint8_t *>(OPENSSL_memdup(CBB_data(cbb), buf_len));
CBS *children =
reinterpret_cast<CBS *>(OPENSSL_calloc(num_children, sizeof(CBS)));
uint8_t *out;
size_t offset = 0;
if (buf == NULL || children == NULL) {
goto err;
// remain valid as we rewrite `cbb`.
Array<uint8_t> copy;
Array<CBS> children;
if (!copy.CopyFrom(CBBAsSpan(cbb)) || //
!children.Init(num_children)) {
return 0;
}
CBS_init(&cbs, buf, buf_len);
cbs = CBS(copy);
for (size_t i = 0; i < num_children; i++) {
if (!CBS_get_any_asn1_element(&cbs, &children[i], NULL, NULL)) {
goto err;
if (!CBS_get_any_asn1_element(&cbs, &children[i], nullptr, nullptr)) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_INTERNAL_ERROR);
return 0;
}
}
qsort(children, num_children, sizeof(CBS), compare_set_of_element);
std::sort(children.begin(), children.end(), [](CBS a, CBS b) -> bool {
// See X.690, section 11.6 for the ordering. They are sorted in ascending
// order by their DER encoding. First compare the common prefix.
size_t a_len = CBS_len(&a), b_len = CBS_len(&b);
int cmp =
OPENSSL_memcmp(CBS_data(&a), CBS_data(&b), std::min(a_len, b_len));
if (cmp != 0) {
return cmp < 0;
}
// If one is a prefix of the other, the shorter one sorts first. (They're
// actually always equal length. DER encodings are prefix-free.)
return a_len < b_len;
});
// Write the contents back in the new order.
out = (uint8_t *)CBB_data(cbb);
uint8_t *out = const_cast<uint8_t *>(CBB_data(cbb));
size_t offset = 0;
for (size_t i = 0; i < num_children; i++) {
OPENSSL_memcpy(out + offset, CBS_data(&children[i]), CBS_len(&children[i]));
offset += CBS_len(&children[i]);
}
assert(offset == buf_len);
ret = 1;
err:
OPENSSL_free(buf);
OPENSSL_free(children);
return ret;
assert(offset == copy.size());
return 1;
}
bool bssl::CBBFinishArray(CBB *cbb, Array<uint8_t> *out) {
uint8_t *ptr;
size_t len;
if (!CBB_finish(cbb, &ptr, &len)) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_INTERNAL_ERROR);
return false;
}
out->Reset(ptr, len);
return true;
}
+138 -65
View File
@@ -1,16 +1,16 @@
/* Copyright 2014 The BoringSSL Authors
*
* 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. */
// Copyright 2014 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_asn1.h>
#include <CNIOBoringSSL_bytestring.h>
@@ -18,7 +18,6 @@
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <string.h>
#include "../asn1/internal.h"
@@ -26,6 +25,8 @@
#include "internal.h"
using namespace bssl;
static int cbs_get(CBS *cbs, const uint8_t **p, size_t n) {
if (cbs->len < n) {
return 0;
@@ -44,14 +45,14 @@ int CBS_skip(CBS *cbs, size_t len) {
int CBS_stow(const CBS *cbs, uint8_t **out_ptr, size_t *out_len) {
OPENSSL_free(*out_ptr);
*out_ptr = NULL;
*out_ptr = nullptr;
*out_len = 0;
if (cbs->len == 0) {
return 1;
}
*out_ptr = reinterpret_cast<uint8_t *>(OPENSSL_memdup(cbs->data, cbs->len));
if (*out_ptr == NULL) {
if (*out_ptr == nullptr) {
return 0;
}
*out_len = cbs->len;
@@ -59,15 +60,15 @@ int CBS_stow(const CBS *cbs, uint8_t **out_ptr, size_t *out_len) {
}
int CBS_strdup(const CBS *cbs, char **out_ptr) {
if (*out_ptr != NULL) {
if (*out_ptr != nullptr) {
OPENSSL_free(*out_ptr);
}
*out_ptr = OPENSSL_strndup((const char *)cbs->data, cbs->len);
return (*out_ptr != NULL);
return (*out_ptr != nullptr);
}
int CBS_contains_zero_byte(const CBS *cbs) {
return OPENSSL_memchr(cbs->data, 0, cbs->len) != NULL;
return OPENSSL_memchr(cbs->data, 0, cbs->len) != nullptr;
}
int CBS_mem_equal(const CBS *cbs, const uint8_t *data, size_t len) {
@@ -144,6 +145,8 @@ int CBS_get_u32le(CBS *cbs, uint32_t *out) {
return 1;
}
int CBS_get_u48(CBS *cbs, uint64_t *out) { return cbs_get_u(cbs, out, 6); }
int CBS_get_u64(CBS *cbs, uint64_t *out) { return cbs_get_u(cbs, out, 8); }
int CBS_get_u64le(CBS *cbs, uint64_t *out) {
@@ -186,7 +189,7 @@ static int cbs_get_length_prefixed(CBS *cbs, CBS *out, size_t len_len) {
if (!cbs_get_u(cbs, &len, len_len)) {
return 0;
}
// If |len_len| <= 3 then we know that |len| will fit into a |size_t|, even on
// If `len_len` <= 3 then we know that `len` will fit into a `size_t`, even on
// 32-bit systems.
assert(len_len <= 3);
return CBS_get_bytes(cbs, out, len);
@@ -207,12 +210,48 @@ int CBS_get_u24_length_prefixed(CBS *cbs, CBS *out) {
int CBS_get_until_first(CBS *cbs, CBS *out, uint8_t c) {
const uint8_t *split = reinterpret_cast<const uint8_t *>(
OPENSSL_memchr(CBS_data(cbs), c, CBS_len(cbs)));
if (split == NULL) {
if (split == nullptr) {
return 0;
}
return CBS_get_bytes(cbs, out, split - CBS_data(cbs));
}
int CBS_get_until_first_of(CBS *cbs, CBS *out, const char *chars) {
size_t pos = 0;
while (pos < CBS_len(cbs)) {
uint8_t c = CBS_data(cbs)[pos];
// Special-case for \0 characters. We don't want to match on a null byte,
// even though strchr will happily return the \0 at the end of `chars`.
if (!c || !strchr(chars, c)) {
pos++;
} else {
break;
}
}
if (pos == CBS_len(cbs)) {
return 0;
}
return CBS_get_bytes(cbs, out, pos);
}
int CBS_get_until_first_not_of(CBS *cbs, CBS *out, const char *chars) {
size_t pos = 0;
while (pos < CBS_len(cbs)) {
uint8_t c = CBS_data(cbs)[pos];
// Special-case for \0 characters. We don't want to match on a null byte,
// even though strchr will happily return the \0 at the end of `chars`.
if (c && strchr(chars, c)) {
pos++;
} else {
break;
}
}
if (pos == CBS_len(cbs)) {
return 0;
}
return CBS_get_bytes(cbs, out, pos);
}
int CBS_get_u64_decimal(CBS *cbs, uint64_t *out) {
uint64_t v = 0;
int seen_digit = 0;
@@ -237,10 +276,7 @@ int CBS_get_u64_decimal(CBS *cbs, uint64_t *out) {
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.
static int parse_base128_integer(CBS *cbs, uint64_t *out) {
int CBS_get_asn1_oid_component(CBS *cbs, uint64_t *out) {
uint64_t v = 0;
uint8_t b;
do {
@@ -279,8 +315,9 @@ static int parse_asn1_tag(CBS *cbs, CBS_ASN1_TAG *out) {
CBS_ASN1_TAG tag = ((CBS_ASN1_TAG)tag_byte & 0xe0) << CBS_ASN1_TAG_SHIFT;
CBS_ASN1_TAG tag_number = tag_byte & 0x1f;
if (tag_number == 0x1f) {
// High tag numbers are encoded in the same format as OID components.
uint64_t v;
if (!parse_base128_integer(cbs, &v) ||
if (!CBS_get_asn1_oid_component(cbs, &v) ||
// Check the tag number is within our supported bounds.
v > CBS_ASN1_TAG_NUMBER_MASK ||
// Small tag numbers should have used low tag number form, even in BER.
@@ -309,22 +346,22 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
CBS header = *cbs;
CBS throwaway;
if (out == NULL) {
if (out == nullptr) {
out = &throwaway;
}
if (ber_ok) {
*out_ber_found = 0;
*out_indefinite = 0;
} else {
assert(out_ber_found == NULL);
assert(out_indefinite == NULL);
assert(out_ber_found == nullptr);
assert(out_indefinite == nullptr);
}
CBS_ASN1_TAG tag;
if (!parse_asn1_tag(&header, &tag)) {
return 0;
}
if (out_tag != NULL) {
if (out_tag != nullptr) {
*out_tag = tag;
}
@@ -341,7 +378,7 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
if ((length_byte & 0x80) == 0) {
// Short form length.
len = ((size_t)length_byte) + header_len;
if (out_header_len != NULL) {
if (out_header_len != nullptr) {
*out_header_len = header_len;
}
} else {
@@ -353,7 +390,7 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
if (ber_ok && (tag & CBS_ASN1_CONSTRUCTED) != 0 && num_bytes == 0) {
// indefinite length
if (out_header_len != NULL) {
if (out_header_len != nullptr) {
*out_header_len = header_len;
}
*out_ber_found = 1;
@@ -373,7 +410,7 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
// ITU-T X.690 section 10.1 (DER length forms) requires encoding the
// length with the minimum number of octets. BER could, technically, have
// 125 superfluous zero bytes. We do not attempt to handle that and still
// require that the length fit in a |uint32_t| for BER.
// require that the length fit in a `uint32_t` for BER.
if (len64 < 128) {
// Length should have used short-form encoding.
if (ber_ok) {
@@ -396,7 +433,7 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
return 0;
}
len += header_len + num_bytes;
if (out_header_len != NULL) {
if (out_header_len != nullptr) {
*out_header_len = header_len + num_bytes;
}
}
@@ -410,7 +447,7 @@ int CBS_get_any_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag) {
return 0;
}
if (!CBS_skip(out, header_len)) {
if (out && !CBS_skip(out, header_len)) {
assert(0);
return 0;
}
@@ -420,7 +457,8 @@ int CBS_get_any_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag) {
int CBS_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
size_t *out_header_len) {
return cbs_get_any_asn1_element(cbs, out, out_tag, out_header_len, NULL, NULL,
return cbs_get_any_asn1_element(cbs, out, out_tag, out_header_len, nullptr,
nullptr,
/*ber_ok=*/0);
}
@@ -440,7 +478,7 @@ static int cbs_get_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG tag_value,
CBS_ASN1_TAG tag;
CBS throwaway;
if (out == NULL) {
if (out == nullptr) {
out = &throwaway;
}
@@ -465,15 +503,29 @@ int CBS_get_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG tag_value) {
return cbs_get_asn1(cbs, out, tag_value, 0 /* include header */);
}
int CBS_peek_asn1_tag(const CBS *cbs, CBS_ASN1_TAG tag_value) {
CBS_ASN1_TAG CBS_peek_any_asn1_tag(const CBS *cbs) {
CBS copy = *cbs;
CBS_ASN1_TAG actual_tag;
return parse_asn1_tag(&copy, &actual_tag) && tag_value == actual_tag;
CBS_ASN1_TAG tag;
if (!parse_asn1_tag(&copy, &tag)) {
return 0;
}
return tag;
}
int CBS_peek_asn1_tag(const CBS *cbs, CBS_ASN1_TAG tag_value) {
CBS_ASN1_TAG actual_tag = CBS_peek_any_asn1_tag(cbs);
// The caller should never pass zero as |tag_value|, but return zero if they
// did.
return actual_tag != 0 && actual_tag == tag_value;
}
int CBS_get_asn1_uint64(CBS *cbs, uint64_t *out) {
return CBS_get_asn1_uint64_with_tag(cbs, out, CBS_ASN1_INTEGER);
}
int CBS_get_asn1_uint64_with_tag(CBS *cbs, uint64_t *out, CBS_ASN1_TAG tag) {
CBS bytes;
if (!CBS_get_asn1(cbs, &bytes, CBS_ASN1_INTEGER) ||
if (!CBS_get_asn1(cbs, &bytes, tag) ||
!CBS_is_unsigned_asn1_integer(&bytes)) {
return 0;
}
@@ -494,9 +546,13 @@ int CBS_get_asn1_uint64(CBS *cbs, uint64_t *out) {
}
int CBS_get_asn1_int64(CBS *cbs, int64_t *out) {
return CBS_get_asn1_int64_with_tag(cbs, out, CBS_ASN1_INTEGER);
}
int CBS_get_asn1_int64_with_tag(CBS *cbs, int64_t *out, CBS_ASN1_TAG tag) {
int is_negative;
CBS bytes;
if (!CBS_get_asn1(cbs, &bytes, CBS_ASN1_INTEGER) ||
if (!CBS_get_asn1(cbs, &bytes, tag) ||
!CBS_is_valid_asn1_integer(&bytes, &is_negative)) {
return 0;
}
@@ -538,7 +594,7 @@ int CBS_get_optional_asn1(CBS *cbs, CBS *out, int *out_present,
present = 1;
}
if (out_present != NULL) {
if (out_present != nullptr) {
*out_present = present;
}
@@ -559,7 +615,7 @@ int CBS_get_optional_asn1_octet_string(CBS *cbs, CBS *out, int *out_present,
return 0;
}
} else {
CBS_init(out, NULL, 0);
CBS_init(out, nullptr, 0);
}
if (out_present) {
*out_present = present;
@@ -655,7 +711,7 @@ int CBS_is_valid_asn1_integer(const CBS *cbs, int *out_is_negative) {
if (!CBS_get_u8(&copy, &first_byte)) {
return 0; // INTEGERs may not be empty.
}
if (out_is_negative != NULL) {
if (out_is_negative != nullptr) {
*out_is_negative = (first_byte & 0x80) != 0;
}
if (!CBS_get_u8(&copy, &second_byte)) {
@@ -673,12 +729,6 @@ int CBS_is_unsigned_asn1_integer(const CBS *cbs) {
return CBS_is_valid_asn1_integer(cbs, &is_negative) && !is_negative;
}
static int add_decimal(CBB *out, uint64_t v) {
char buf[DECIMAL_SIZE(uint64_t) + 1];
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.
@@ -688,9 +738,9 @@ int CBS_is_valid_asn1_oid(const CBS *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
// `CBS_get_asn1_oid_component`). 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;
@@ -711,23 +761,23 @@ char *CBS_asn1_oid_to_text(const CBS *cbs) {
// The first component is 40 * value1 + value2, where value1 is 0, 1, or 2.
uint64_t v;
if (!parse_base128_integer(&copy, &v)) {
if (!CBS_get_asn1_oid_component(&copy, &v)) {
goto err;
}
if (v >= 80) {
if (!CBB_add_bytes(&cbb, (const uint8_t *)"2.", 2) ||
!add_decimal(&cbb, v - 80)) {
!cbb_add_decimal_ascii(&cbb, v - 80)) {
goto err;
}
} else if (!add_decimal(&cbb, v / 40) || !CBB_add_u8(&cbb, '.') ||
!add_decimal(&cbb, v % 40)) {
} else if (!cbb_add_decimal_ascii(&cbb, v / 40) || !CBB_add_u8(&cbb, '.') ||
!cbb_add_decimal_ascii(&cbb, v % 40)) {
goto err;
}
while (CBS_len(&copy) != 0) {
if (!parse_base128_integer(&copy, &v) || !CBB_add_u8(&cbb, '.') ||
!add_decimal(&cbb, v)) {
if (!CBS_get_asn1_oid_component(&copy, &v) || !CBB_add_u8(&cbb, '.') ||
!cbb_add_decimal_ascii(&cbb, v)) {
goto err;
}
}
@@ -742,7 +792,30 @@ char *CBS_asn1_oid_to_text(const CBS *cbs) {
err:
CBB_cleanup(&cbb);
return NULL;
return nullptr;
}
int CBS_is_valid_asn1_relative_oid(const CBS *cbs) {
return CBS_is_valid_asn1_oid(cbs);
}
char *CBS_asn1_relative_oid_to_text(const CBS *cbs) {
ScopedCBB cbb;
if (!CBB_init(cbb.get(), 32)) {
return nullptr;
}
if (!CBB_add_asn1_relative_oid_from_der_to_text(cbb.get(), CBS_data(cbs),
CBS_len(cbs))) {
return nullptr;
}
uint8_t *txt;
size_t txt_len;
if (!CBB_add_u8(cbb.get(), '\0') || !CBB_finish(cbb.get(), &txt, &txt_len)) {
return nullptr;
}
return reinterpret_cast<char *>(txt);
}
static int cbs_get_two_digits(CBS *cbs, int *out) {
@@ -838,10 +911,10 @@ static int CBS_parse_rfc5280_time_internal(const CBS *cbs, int is_gentime,
case 'Z':
break; // We correctly have 'Z' on the end as per spec.
case '+':
offset_sign = 1;
offset_sign = -1;
break; // Should not be allowed per RFC 5280.
case '-':
offset_sign = -1;
offset_sign = 1;
break; // Should not be allowed per RFC 5280.
default:
return 0; // Reject anything else after the time.
@@ -850,7 +923,7 @@ static int CBS_parse_rfc5280_time_internal(const CBS *cbs, int is_gentime,
// If allow_timezone_offset is non-zero, allow for a four digit timezone
// offset to be specified even though this is not allowed by RFC 5280. We are
// permissive of this for UTCTimes due to the unfortunate existence of
// artisinally rolled long lived certificates that were baked into places that
// artisanally rolled long lived certificates that were baked into places that
// are now difficult to change. These certificates were generated with the
// 'openssl' command that permissively allowed the creation of certificates
// with notBefore and notAfter times specified as strings for direct
@@ -878,7 +951,7 @@ static int CBS_parse_rfc5280_time_internal(const CBS *cbs, int is_gentime,
return 0; // Reject invalid lengths.
}
if (out_tm != NULL) {
if (out_tm != nullptr) {
// Fill in the tm fields corresponding to what we validated.
out_tm->tm_year = year - 1900;
out_tm->tm_mon = month - 1;
@@ -1,39 +1,43 @@
/* Copyright 2014 The BoringSSL Authors
*
* 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. */
// Copyright 2014 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSSL_HEADER_BYTESTRING_INTERNAL_H
#define OPENSSL_HEADER_BYTESTRING_INTERNAL_H
#ifndef OPENSSL_HEADER_CRYPTO_BYTESTRING_INTERNAL_H
#define OPENSSL_HEADER_CRYPTO_BYTESTRING_INTERNAL_H
#include <CNIOBoringSSL_base.h>
#include <CNIOBoringSSL_asn1.h>
#include <CNIOBoringSSL_bytestring.h>
#include <CNIOBoringSSL_err.h>
#if defined(__cplusplus)
extern "C" {
#endif
#include <type_traits>
#include "../mem_internal.h"
// CBS_asn1_ber_to_der reads a BER element from |in|. If it finds
BSSL_NAMESPACE_BEGIN
// CBS_asn1_ber_to_der reads a BER element from `in`. If it finds
// indefinite-length elements or constructed strings then it converts the BER
// data to DER, sets |out| to the converted contents and |*out_storage| to a
// buffer which the caller must release with |OPENSSL_free|. Otherwise, it sets
// |out| to the original BER element in |in| and |*out_storage| to NULL.
// Additionally, |*in| will be advanced over the BER element.
// data to DER, sets `out` to the converted contents and `*out_storage` to a
// buffer which the caller must release with `OPENSSL_free`. Otherwise, it sets
// `out` to the original BER element in `in` and `*out_storage` to NULL.
// Additionally, `*in` will be advanced over the BER element.
//
// This function should successfully process any valid BER input, however it
// will not convert all of BER's deviations from DER. BER is ambiguous between
// implicitly-tagged SEQUENCEs of strings and implicitly-tagged constructed
// strings. Implicitly-tagged strings must be parsed with
// |CBS_get_ber_implicitly_tagged_string| instead of |CBS_get_asn1|. The caller
// `CBS_get_ber_implicitly_tagged_string` instead of `CBS_get_asn1`. The caller
// must also account for BER variations in the contents of a primitive.
//
// It returns one on success and zero otherwise.
@@ -41,15 +45,15 @@ OPENSSL_EXPORT int CBS_asn1_ber_to_der(CBS *in, CBS *out,
uint8_t **out_storage);
// CBS_get_asn1_implicit_string parses a BER string of primitive type
// |inner_tag| implicitly-tagged with |outer_tag|. It sets |out| to the
// contents. If concatenation was needed, it sets |*out_storage| to a buffer
// which the caller must release with |OPENSSL_free|. Otherwise, it sets
// |*out_storage| to NULL.
// `inner_tag` implicitly-tagged with `outer_tag`. It sets `out` to the
// contents. If concatenation was needed, it sets `*out_storage` to a buffer
// which the caller must release with `OPENSSL_free`. Otherwise, it sets
// `*out_storage` to NULL.
//
// This function does not parse all of BER. It requires the string be
// definite-length. Constructed strings are allowed, but all children of the
// outermost element must be primitive. The caller should use
// |CBS_asn1_ber_to_der| before running this function.
// `CBS_asn1_ber_to_der` before running this function.
//
// It returns one on success and zero otherwise.
OPENSSL_EXPORT int CBS_get_asn1_implicit_string(CBS *in, CBS *out,
@@ -57,18 +61,74 @@ OPENSSL_EXPORT int CBS_get_asn1_implicit_string(CBS *in, CBS *out,
CBS_ASN1_TAG outer_tag,
CBS_ASN1_TAG inner_tag);
// CBB_finish_i2d calls |CBB_finish| on |cbb| which must have been initialized
// with |CBB_init|. If |outp| is not NULL then the result is written to |*outp|
// and |*outp| is advanced just past the output. It returns the number of bytes
// in the result, whether written or not, or a negative value on error. On
// error, it calls |CBB_cleanup| on |cbb|.
// CBB_finish_i2d calls `CBB_finish` on `cbb` which must have been initialized
// with `CBB_init`. If `outp` is not NULL then the result is written to `*outp`
// and `*outp` is advanced just past the output. It returns the number of bytes
// in the result, whether written or not, or a negative value on error.
//
// This function may be used to help implement legacy i2d ASN.1 functions.
int CBB_finish_i2d(CBB *cbb, uint8_t **outp);
OPENSSL_EXPORT int CBB_finish_i2d(CBB *cbb, uint8_t **outp);
// CBBAsSpan returns a span containing `cbb`'s contents. It does not flush
// `cbb`. The span is valid until the next operation to `cbb`.
//
// To avoid unfinalized length prefixes, it is a fatal error to call this on a
// CBB with any active children.
inline Span<uint8_t> CBBAsSpan(const CBB *cbb) {
return Span(CBB_data(cbb), CBB_len(cbb));
}
#if defined(__cplusplus)
} // extern C
#endif
// CBBFinishArray behaves like `CBB_finish` but stores the result in an Array.
OPENSSL_EXPORT bool CBBFinishArray(CBB *cbb, Array<uint8_t> *out);
#endif // OPENSSL_HEADER_BYTESTRING_INTERNAL_H
// D2IFromCBS takes a functor of type `Unique<T>(CBS*)` and implements the d2i
// calling convention. For compatibility with functions that don't tag their
// return value (e.g. public APIs), `T*(CBS)` is also accepted. The callback can
// assume that the `CBS`'s length fits in `long`. The callback should not access
// `out`, `inp`, or `len` directly.
template <typename T, typename CBSFunc>
inline T *D2IFromCBS(T **out, const uint8_t **inp, long len, CBSFunc func) {
static_assert(std::is_invocable_v<CBSFunc, CBS *>);
static_assert(
std::is_same_v<std::invoke_result_t<CBSFunc, CBS *>, UniquePtr<T>> ||
std::is_same_v<std::invoke_result_t<CBSFunc, CBS *>, T *>);
if (len < 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BUFFER_TOO_SMALL);
return nullptr;
}
CBS cbs;
CBS_init(&cbs, *inp, len);
UniquePtr<T> ret(func(&cbs));
if (ret == nullptr) {
return nullptr;
}
if (out != nullptr) {
UniquePtr<T> free_out(*out);
*out = ret.get();
}
*inp = CBS_data(&cbs);
return ret.release();
}
// I2DFromCBB takes a functor of type `bool(CBB*)` and implements the i2d
// calling convention. It internally makes a `CBB` with the specified initial
// capacity. The callback should not access `outp` directly.
template <typename CBBFunc>
inline int I2DFromCBB(size_t initial_capacity, uint8_t **outp, CBBFunc func) {
static_assert(std::is_invocable_v<CBBFunc, CBB *>);
static_assert(std::is_same_v<std::invoke_result_t<CBBFunc, CBB *>, bool>);
ScopedCBB cbb;
if (!CBB_init(cbb.get(), initial_capacity) || !func(cbb.get())) {
return -1;
}
return CBB_finish_i2d(cbb.get(), outp);
}
// cbb_add_decimal_ascii adds the characters of an ASCII string representation
// of `v` as a decimal value to `out` (without a terminating NUL byte). It
// returns one on success and zero on error.
int cbb_add_decimal_ascii(CBB *out, uint64_t v);
BSSL_NAMESPACE_END
#endif // OPENSSL_HEADER_CRYPTO_BYTESTRING_INTERNAL_H
@@ -1,16 +1,16 @@
/* Copyright 2018 The BoringSSL Authors
*
* 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. */
// Copyright 2018 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_bytestring.h>
@@ -33,10 +33,10 @@ static int is_valid_code_point(uint32_t v) {
return 1;
}
// BOTTOM_BITS returns a byte with the bottom |n| bits set.
// BOTTOM_BITS returns a byte with the bottom `n` bits set.
#define BOTTOM_BITS(n) (uint8_t)((1u << (n)) - 1)
// TOP_BITS returns a byte with the top |n| bits set.
// 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) {
+18 -16
View File
@@ -1,16 +1,16 @@
/* Copyright 2014 The BoringSSL Authors
*
* 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. */
// Copyright 2014 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Adapted from the public domain, estream code by D. Bernstein.
@@ -24,6 +24,8 @@
// sigma contains the ChaCha constants, which happen to be an ASCII string.
using namespace bssl;
static const uint8_t sigma[16] = { 'e', 'x', 'p', 'a', 'n', 'd', ' ', '3',
'2', '-', 'b', 'y', 't', 'e', ' ', 'k' };
@@ -38,8 +40,8 @@ static const uint8_t sigma[16] = { 'e', 'x', 'p', 'a', 'n', 'd', ' ', '3',
x[c] += x[d]; \
x[b] = CRYPTO_rotl_u32(x[b] ^ x[c], 7);
void CRYPTO_hchacha20(uint8_t out[32], const uint8_t key[32],
const uint8_t nonce[16]) {
void bssl::CRYPTO_hchacha20(uint8_t out[32], const uint8_t key[32],
const uint8_t nonce[16]) {
uint32_t x[16];
OPENSSL_memcpy(x, sigma, sizeof(sigma));
OPENSSL_memcpy(&x[4], key, 32);
@@ -148,7 +150,7 @@ void CRYPTO_chacha_20(uint8_t *out, const uint8_t *in, size_t in_len,
#else
// chacha_core performs 20 rounds of ChaCha on the input words in
// |input| and writes the 64 output bytes to |output|.
// `input` and writes the 64 output bytes to `output`.
static void chacha_core(uint8_t output[64], const uint32_t input[16]) {
uint32_t x[16];
int i;
+40 -39
View File
@@ -1,28 +1,26 @@
/* Copyright 2018 The BoringSSL Authors
*
* 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. */
// Copyright 2018 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSSL_HEADER_CHACHA_INTERNAL
#define OPENSSL_HEADER_CHACHA_INTERNAL
#ifndef OPENSSL_HEADER_CRYPTO_CHACHA_INTERNAL_H
#define OPENSSL_HEADER_CRYPTO_CHACHA_INTERNAL_H
#include <CNIOBoringSSL_base.h>
#include "../internal.h"
#if defined(__cplusplus)
extern "C" {
#endif
BSSL_NAMESPACE_BEGIN
// CRYPTO_hchacha20 computes the HChaCha20 function, which should only be used
// as part of XChaCha20.
@@ -37,10 +35,11 @@ void CRYPTO_hchacha20(uint8_t out[32], const uint8_t key[32],
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();
return len > 0 && 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]);
extern "C" 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))
@@ -51,8 +50,9 @@ void ChaCha20_ctr32_ssse3(uint8_t *out, const uint8_t *in, size_t in_len,
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]);
extern "C" 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
@@ -60,8 +60,9 @@ void ChaCha20_ctr32_neon(uint8_t *out, const uint8_t *in, size_t in_len,
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]);
extern "C" 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
inline int ChaCha20_ctr32_ssse3_4x_capable(size_t len) {
@@ -69,34 +70,34 @@ inline int ChaCha20_ctr32_ssse3_4x_capable(size_t len) {
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]);
extern "C" 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
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]);
extern "C" 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
// 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
// `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]);
extern "C" 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
BSSL_NAMESPACE_END
#if defined(__cplusplus)
} // extern C
#endif
#endif // OPENSSL_HEADER_CHACHA_INTERNAL
#endif // OPENSSL_HEADER_CRYPTO_CHACHA_INTERNAL_H
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_cipher.h>
@@ -15,12 +20,9 @@
#include <CNIOBoringSSL_mem.h>
#define PKCS5_SALT_LEN 8
int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md,
const uint8_t *salt, const uint8_t *data, size_t data_len,
const uint8_t salt[8], const uint8_t *data, size_t data_len,
unsigned count, uint8_t *key, uint8_t *iv) {
EVP_MD_CTX c;
uint8_t md_buf[EVP_MAX_MD_SIZE];
unsigned addmd = 0;
unsigned mds = 0, i;
@@ -32,36 +34,36 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md,
assert(nkey <= EVP_MAX_KEY_LENGTH);
assert(niv <= EVP_MAX_IV_LENGTH);
if (data == NULL) {
if (data == nullptr) {
return nkey;
}
EVP_MD_CTX_init(&c);
bssl::ScopedEVP_MD_CTX c;
for (;;) {
if (!EVP_DigestInit_ex(&c, md, NULL)) {
if (!EVP_DigestInit_ex(c.get(), md, nullptr)) {
goto err;
}
if (addmd++) {
if (!EVP_DigestUpdate(&c, md_buf, mds)) {
if (!EVP_DigestUpdate(c.get(), md_buf, mds)) {
goto err;
}
}
if (!EVP_DigestUpdate(&c, data, data_len)) {
if (!EVP_DigestUpdate(c.get(), data, data_len)) {
goto err;
}
if (salt != NULL) {
if (!EVP_DigestUpdate(&c, salt, PKCS5_SALT_LEN)) {
if (salt != nullptr) {
if (!EVP_DigestUpdate(c.get(), salt, 8)) {
goto err;
}
}
if (!EVP_DigestFinal_ex(&c, md_buf, &mds)) {
if (!EVP_DigestFinal_ex(c.get(), md_buf, &mds)) {
goto err;
}
for (i = 1; i < count; i++) {
if (!EVP_DigestInit_ex(&c, md, NULL) ||
!EVP_DigestUpdate(&c, md_buf, mds) ||
!EVP_DigestFinal_ex(&c, md_buf, &mds)) {
if (!EVP_DigestInit_ex(c.get(), md, nullptr) ||
!EVP_DigestUpdate(c.get(), md_buf, mds) ||
!EVP_DigestFinal_ex(c.get(), md_buf, &mds)) {
goto err;
}
}
@@ -72,7 +74,7 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md,
if (nkey == 0 || i == mds) {
break;
}
if (key != NULL) {
if (key != nullptr) {
*(key++) = md_buf[i];
}
nkey--;
@@ -85,7 +87,7 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md,
if (niv == 0 || i == mds) {
break;
}
if (iv != NULL) {
if (iv != nullptr) {
*(iv++) = md_buf[i];
}
niv--;
@@ -99,7 +101,6 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md,
rv = EVP_CIPHER_key_length(type);
err:
EVP_MD_CTX_cleanup(&c);
OPENSSL_cleanse(md_buf, EVP_MAX_MD_SIZE);
return rv;
}
@@ -1,16 +1,16 @@
/* Copyright 2017 The BoringSSL Authors
*
* 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. */
// Copyright 2017 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_aead.h>
@@ -19,12 +19,15 @@
#include <CNIOBoringSSL_cipher.h>
#include <CNIOBoringSSL_crypto.h>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_sha.h>
#include <CNIOBoringSSL_sha2.h>
#include <CNIOBoringSSL_span.h>
#include "../fipsmodule/aes/internal.h"
#include "../fipsmodule/cipher/internal.h"
using namespace bssl;
#define EVP_AEAD_AES_CTR_HMAC_SHA256_TAG_LEN SHA256_DIGEST_LENGTH
#define EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN 12
@@ -39,7 +42,7 @@ struct aead_aes_ctr_hmac_sha256_ctx {
SHA256_CTX outer_init_state;
};
static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >=
static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >=
sizeof(struct aead_aes_ctr_hmac_sha256_ctx),
"AEAD state is too small");
static_assert(alignof(union evp_aead_ctx_st_state) >=
@@ -96,8 +99,8 @@ static int aead_aes_ctr_hmac_sha256_init(EVP_AEAD_CTX *ctx, const uint8_t *key,
return 0;
}
aes_ctx->ctr =
aes_ctr_set_key(&aes_ctx->ks.ks, NULL, &aes_ctx->block, key, aes_key_len);
aes_ctx->ctr = aes_ctr_set_key(&aes_ctx->ks.ks, nullptr, &aes_ctx->block, key,
aes_key_len);
ctx->tag_len = tag_len;
hmac_init(&aes_ctx->inner_init_state, &aes_ctx->outer_init_state,
key + aes_key_len);
@@ -121,19 +124,22 @@ static void hmac_update_uint64(SHA256_CTX *sha256, uint64_t value) {
static void hmac_calculate(uint8_t out[SHA256_DIGEST_LENGTH],
const SHA256_CTX *inner_init_state,
const SHA256_CTX *outer_init_state,
const uint8_t *ad, size_t ad_len,
const uint8_t *nonce, const uint8_t *ciphertext,
size_t ciphertext_len) {
Span<const CRYPTO_IVEC> aadvecs,
const uint8_t *nonce,
Span<const CRYPTO_IOVEC> iovecs, bool encrypt) {
size_t ad_len = bssl::iovec::TotalLength(aadvecs);
SHA256_CTX sha256;
OPENSSL_memcpy(&sha256, inner_init_state, sizeof(sha256));
hmac_update_uint64(&sha256, ad_len);
hmac_update_uint64(&sha256, ciphertext_len);
hmac_update_uint64(&sha256, bssl::iovec::TotalLength(iovecs));
SHA256_Update(&sha256, nonce, EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN);
SHA256_Update(&sha256, ad, ad_len);
for (const CRYPTO_IVEC &aadvec : aadvecs) {
SHA256_Update(&sha256, aadvec.in, aadvec.len);
}
// Pad with zeros to the end of the SHA-256 block.
const unsigned num_padding =
(SHA256_CBLOCK - ((sizeof(uint64_t)*2 +
(SHA256_CBLOCK - ((sizeof(uint64_t) * 2 +
EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN + ad_len) %
SHA256_CBLOCK)) %
SHA256_CBLOCK;
@@ -141,7 +147,9 @@ static void hmac_calculate(uint8_t out[SHA256_DIGEST_LENGTH],
OPENSSL_memset(padding, 0, num_padding);
SHA256_Update(&sha256, padding, num_padding);
SHA256_Update(&sha256, ciphertext, ciphertext_len);
for (const CRYPTO_IOVEC &iovec : iovecs) {
SHA256_Update(&sha256, encrypt ? iovec.out : iovec.in, iovec.len);
}
uint8_t inner_digest[SHA256_DIGEST_LENGTH];
SHA256_Final(inner_digest, &sha256);
@@ -152,10 +160,8 @@ static void hmac_calculate(uint8_t out[SHA256_DIGEST_LENGTH],
}
static void aead_aes_ctr_hmac_sha256_crypt(
const struct aead_aes_ctr_hmac_sha256_ctx *aes_ctx, uint8_t *out,
const uint8_t *in, size_t len, const uint8_t *nonce) {
// Since the AEAD operation is one-shot, keeping a buffer of unused keystream
// bytes is pointless. However, |CRYPTO_ctr128_encrypt_ctr32| requires it.
const struct aead_aes_ctr_hmac_sha256_ctx *aes_ctx,
Span<const CRYPTO_IOVEC> iovecs, const uint8_t *nonce) {
uint8_t partial_block_buffer[AES_BLOCK_SIZE];
unsigned partial_block_offset = 0;
OPENSSL_memset(partial_block_buffer, 0, sizeof(partial_block_buffer));
@@ -164,74 +170,85 @@ static void aead_aes_ctr_hmac_sha256_crypt(
OPENSSL_memcpy(counter, nonce, EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN);
OPENSSL_memset(counter + EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN, 0, 4);
CRYPTO_ctr128_encrypt_ctr32(in, out, len, &aes_ctx->ks.ks, counter,
partial_block_buffer, &partial_block_offset,
aes_ctx->ctr);
for (const CRYPTO_IOVEC &iovec : iovecs) {
CRYPTO_ctr128_encrypt_ctr32(iovec.in, iovec.out, iovec.len, &aes_ctx->ks.ks,
counter, partial_block_buffer,
&partial_block_offset, aes_ctx->ctr);
}
}
static int aead_aes_ctr_hmac_sha256_seal_scatter(
const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag,
size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce,
size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in,
size_t extra_in_len, const uint8_t *ad, size_t ad_len) {
static int aead_aes_ctr_hmac_sha256_sealv(const EVP_AEAD_CTX *ctx,
Span<const CRYPTO_IOVEC> iovecs,
Span<uint8_t> out_tag,
size_t *out_tag_len,
Span<const uint8_t> nonce,
Span<const CRYPTO_IVEC> aadvecs) {
const struct aead_aes_ctr_hmac_sha256_ctx *aes_ctx =
(struct aead_aes_ctr_hmac_sha256_ctx *) &ctx->state;
const uint64_t in_len_64 = in_len;
(struct aead_aes_ctr_hmac_sha256_ctx *)&ctx->state;
const uint64_t in_len_64 = bssl::iovec::TotalLength(iovecs);
if (in_len_64 >= (UINT64_C(1) << 32) * AES_BLOCK_SIZE) {
// This input is so large it would overflow the 32-bit block counter.
// This input is so large it would overflow the 32-bit block counter.
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
return 0;
}
if (max_out_tag_len < ctx->tag_len) {
if (out_tag.size() < ctx->tag_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL);
return 0;
}
if (nonce_len != EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN) {
if (nonce.size() != EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
aead_aes_ctr_hmac_sha256_crypt(aes_ctx, out, in, in_len, nonce);
aead_aes_ctr_hmac_sha256_crypt(aes_ctx, iovecs, nonce.data());
uint8_t hmac_result[SHA256_DIGEST_LENGTH];
hmac_calculate(hmac_result, &aes_ctx->inner_init_state,
&aes_ctx->outer_init_state, ad, ad_len, nonce, out, in_len);
OPENSSL_memcpy(out_tag, hmac_result, ctx->tag_len);
&aes_ctx->outer_init_state, aadvecs, nonce.data(), iovecs,
/*encrypt=*/true);
CopyToPrefix(Span(hmac_result).first(ctx->tag_len), out_tag);
*out_tag_len = ctx->tag_len;
return 1;
}
static int aead_aes_ctr_hmac_sha256_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) {
static int aead_aes_ctr_hmac_sha256_openv_detached(
const EVP_AEAD_CTX *ctx, Span<const CRYPTO_IOVEC> iovecs,
Span<const uint8_t> nonce, Span<const uint8_t> in_tag,
Span<const CRYPTO_IVEC> aadvecs) {
const struct aead_aes_ctr_hmac_sha256_ctx *aes_ctx =
(struct aead_aes_ctr_hmac_sha256_ctx *) &ctx->state;
(struct aead_aes_ctr_hmac_sha256_ctx *)&ctx->state;
const uint64_t in_len_64 = bssl::iovec::TotalLength(iovecs);
if (in_tag_len != ctx->tag_len) {
if (in_len_64 >= (UINT64_C(1) << 32) * AES_BLOCK_SIZE) {
// This input is so large it would overflow the 32-bit block counter.
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
if (nonce_len != EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN) {
if (in_tag.size() != ctx->tag_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
if (nonce.size() != EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
uint8_t hmac_result[SHA256_DIGEST_LENGTH];
hmac_calculate(hmac_result, &aes_ctx->inner_init_state,
&aes_ctx->outer_init_state, ad, ad_len, nonce, in,
in_len);
if (CRYPTO_memcmp(hmac_result, in_tag, ctx->tag_len) != 0) {
&aes_ctx->outer_init_state, aadvecs, nonce.data(), iovecs,
/*encrypt=*/false);
if (CRYPTO_memcmp(hmac_result, in_tag.data(), ctx->tag_len) != 0) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
aead_aes_ctr_hmac_sha256_crypt(aes_ctx, out, in, in_len, nonce);
aead_aes_ctr_hmac_sha256_crypt(aes_ctx, iovecs, nonce.data());
return 1;
}
@@ -241,16 +258,15 @@ static const EVP_AEAD aead_aes_128_ctr_hmac_sha256 = {
12, // nonce length
EVP_AEAD_AES_CTR_HMAC_SHA256_TAG_LEN, // overhead
EVP_AEAD_AES_CTR_HMAC_SHA256_TAG_LEN, // max tag length
0, // seal_scatter_supports_extra_in
aead_aes_ctr_hmac_sha256_init,
NULL /* init_with_direction */,
nullptr /* init_with_direction */,
aead_aes_ctr_hmac_sha256_cleanup,
NULL /* open */,
aead_aes_ctr_hmac_sha256_seal_scatter,
aead_aes_ctr_hmac_sha256_open_gather,
NULL /* get_iv */,
NULL /* tag_len */,
nullptr /* openv */,
aead_aes_ctr_hmac_sha256_sealv,
aead_aes_ctr_hmac_sha256_openv_detached,
nullptr /* get_iv */,
nullptr /* tag_len */,
};
static const EVP_AEAD aead_aes_256_ctr_hmac_sha256 = {
@@ -258,22 +274,21 @@ static const EVP_AEAD aead_aes_256_ctr_hmac_sha256 = {
12, // nonce length
EVP_AEAD_AES_CTR_HMAC_SHA256_TAG_LEN, // overhead
EVP_AEAD_AES_CTR_HMAC_SHA256_TAG_LEN, // max tag length
0, // seal_scatter_supports_extra_in
aead_aes_ctr_hmac_sha256_init,
NULL /* init_with_direction */,
nullptr /* init_with_direction */,
aead_aes_ctr_hmac_sha256_cleanup,
NULL /* open */,
aead_aes_ctr_hmac_sha256_seal_scatter,
aead_aes_ctr_hmac_sha256_open_gather,
NULL /* get_iv */,
NULL /* tag_len */,
nullptr /* openv */,
aead_aes_ctr_hmac_sha256_sealv,
aead_aes_ctr_hmac_sha256_openv_detached,
nullptr /* get_iv */,
nullptr /* tag_len */,
};
const EVP_AEAD *EVP_aead_aes_128_ctr_hmac_sha256(void) {
const EVP_AEAD *EVP_aead_aes_128_ctr_hmac_sha256() {
return &aead_aes_128_ctr_hmac_sha256;
}
const EVP_AEAD *EVP_aead_aes_256_ctr_hmac_sha256(void) {
const EVP_AEAD *EVP_aead_aes_256_ctr_hmac_sha256() {
return &aead_aes_256_ctr_hmac_sha256;
}
@@ -0,0 +1,351 @@
// Copyright 2025 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_aead.h>
#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
#include <CNIOBoringSSL_aes.h>
#include <CNIOBoringSSL_base.h>
#include <CNIOBoringSSL_cipher.h>
#include <CNIOBoringSSL_crypto.h>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_span.h>
#include "../fipsmodule/cipher/internal.h"
#include "../internal.h"
using namespace bssl;
// Implementation of AES-EAX defined in
// https://www.iacr.org/archive/fse2004/30170391/30170391.pdf.
#define EVP_AEAD_AES_EAX_TAG_LEN AES_BLOCK_SIZE
struct aead_aes_eax_ctx {
union {
double align;
AES_KEY ks;
} ks;
uint8_t b[AES_BLOCK_SIZE];
uint8_t p[AES_BLOCK_SIZE];
};
static void mult_by_X(uint8_t out[AES_BLOCK_SIZE],
const uint8_t in[AES_BLOCK_SIZE]) {
const crypto_word_t in_hi = CRYPTO_load_word_be(in);
for (size_t i = 0; i < AES_BLOCK_SIZE - 1; ++i) {
out[i] = (in[i] << 1) | (in[i + 1] >> 7);
}
// Carry over 0x87 if msb is 1, 0x00 if msb is 0.
out[AES_BLOCK_SIZE - 1] = in[AES_BLOCK_SIZE - 1] << 1;
const uint8_t p = 0x87;
constant_time_conditional_memxor(out + AES_BLOCK_SIZE - 1, &p, /*n=*/1,
constant_time_msb_w(in_hi));
}
static int aead_aes_eax_init(EVP_AEAD_CTX *ctx, const uint8_t *key,
size_t key_len, size_t tag_len) {
struct aead_aes_eax_ctx *aes_ctx = (struct aead_aes_eax_ctx *)&ctx->state;
if (key_len != 16 && key_len != 32) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_KEY_LENGTH);
return 0;
}
if (tag_len == EVP_AEAD_DEFAULT_TAG_LENGTH) {
tag_len = EVP_AEAD_AES_EAX_TAG_LEN;
}
if (tag_len != EVP_AEAD_AES_EAX_TAG_LEN) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_TAG_SIZE);
return 0;
}
if (AES_set_encrypt_key(key, /*bits=*/key_len * 8, &aes_ctx->ks.ks) != 0) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_AES_KEY_SETUP_FAILED);
return 0;
}
ctx->tag_len = tag_len;
// L <- Ek(0^n).
OPENSSL_memset(aes_ctx->b, 0, sizeof(aes_ctx->b));
AES_encrypt(aes_ctx->b, aes_ctx->b, &aes_ctx->ks.ks);
// B <- 2L.
mult_by_X(aes_ctx->b, aes_ctx->b);
// P <- 4L = 2B.
mult_by_X(aes_ctx->p, aes_ctx->b);
return 1;
}
static void aead_aes_eax_cleanup(EVP_AEAD_CTX *ctx) {}
// Implements the CBK function in the paper.
static void cbk_block(const struct aead_aes_eax_ctx *aes_ctx,
const uint8_t in[AES_BLOCK_SIZE],
uint8_t out[AES_BLOCK_SIZE]) {
CRYPTO_xor16(out, in, out);
AES_encrypt(out, out, &aes_ctx->ks.ks);
}
// Precondition: in_len <= AES_BLOCK_SIZE.
static void pad(const struct aead_aes_eax_ctx *aes_ctx,
uint8_t out[AES_BLOCK_SIZE], const uint8_t *in, size_t in_len) {
assert(in_len <= AES_BLOCK_SIZE);
if (in_len == AES_BLOCK_SIZE) {
CRYPTO_xor16(out, aes_ctx->b, in);
return;
}
OPENSSL_memset(out, 0, AES_BLOCK_SIZE);
OPENSSL_memcpy(out, in, in_len);
out[in_len] = 0x80;
CRYPTO_xor16(out, aes_ctx->p, out);
}
template <typename IVEC>
static void omac_with_tag(const struct aead_aes_eax_ctx *aes_ctx,
uint8_t out[AES_BLOCK_SIZE], Span<const IVEC> ivecs,
uint8_t tag) {
OPENSSL_memset(out, 0, AES_BLOCK_SIZE);
out[AES_BLOCK_SIZE - 1] = tag;
size_t in_len = bssl::iovec::TotalLength(ivecs);
if (in_len == 0) {
// CBK(pad(M;B,P)) = CBK(B). Avoiding padding to skip a copy.
cbk_block(aes_ctx, aes_ctx->b, out);
return;
}
// CBK(M1) = Ek(M1 ^ 0^n)
AES_encrypt(out, out, &aes_ctx->ks.ks);
bssl::iovec::ForEachBlockRange<AES_BLOCK_SIZE>(
ivecs,
[&](const uint8_t *in, size_t len) {
while (len >= AES_BLOCK_SIZE) {
// Full blocks, no padding needed.
cbk_block(aes_ctx, in, out);
in += AES_BLOCK_SIZE;
len -= AES_BLOCK_SIZE;
}
BSSL_CHECK(len == 0);
return true;
},
[&](const uint8_t *in, size_t len) {
// Remaining blocks.
while (len > AES_BLOCK_SIZE) {
// Full blocks, no padding needed.
cbk_block(aes_ctx, in, out);
in += AES_BLOCK_SIZE;
len -= AES_BLOCK_SIZE;
}
// Last partial block.
uint8_t padded_block[AES_BLOCK_SIZE];
pad(aes_ctx, padded_block, in, len);
cbk_block(aes_ctx, padded_block, out);
return true;
});
}
static void omac_with_tag_iovec_out(const struct aead_aes_eax_ctx *aes_ctx,
uint8_t out[AES_BLOCK_SIZE],
Span<const CRYPTO_IOVEC> iovecs,
uint8_t tag) {
OPENSSL_memset(out, 0, AES_BLOCK_SIZE);
out[AES_BLOCK_SIZE - 1] = tag;
size_t in_len = bssl::iovec::TotalLength(iovecs);
if (in_len == 0) {
// CBK(pad(M;B,P)) = CBK(B). Avoiding padding to skip a copy.
cbk_block(aes_ctx, aes_ctx->b, out);
return;
}
// CBK(M1) = Ek(M1 ^ 0^n)
AES_encrypt(out, out, &aes_ctx->ks.ks);
bssl::iovec::ForEachOutBlockRange<AES_BLOCK_SIZE>(
iovecs,
[&](const uint8_t *in, size_t len) {
while (len >= AES_BLOCK_SIZE) {
// Full blocks, no padding needed.
cbk_block(aes_ctx, in, out);
in += AES_BLOCK_SIZE;
len -= AES_BLOCK_SIZE;
}
BSSL_CHECK(len == 0);
return true;
},
[&](const uint8_t *in, size_t len) {
while (len > AES_BLOCK_SIZE) {
// Full blocks, no padding needed.
cbk_block(aes_ctx, in, out);
in += AES_BLOCK_SIZE;
len -= AES_BLOCK_SIZE;
}
// Last partial block.
uint8_t padded_block[AES_BLOCK_SIZE];
pad(aes_ctx, padded_block, in, len);
cbk_block(aes_ctx, padded_block, out);
return true;
});
}
// Encrypts/decrypts `in_len` bytes from `in` to `out` using AES-CTR with `n` as
// the IV.
static void aes_ctr(const struct aead_aes_eax_ctx *aes_ctx,
Span<const CRYPTO_IOVEC> iovecs,
const uint8_t n[AES_BLOCK_SIZE]) {
uint8_t ivec[AES_BLOCK_SIZE];
OPENSSL_memcpy(ivec, n, AES_BLOCK_SIZE);
uint8_t ecount_buf[AES_BLOCK_SIZE];
unsigned int num = 0;
for (const CRYPTO_IOVEC &iovec : iovecs) {
AES_ctr128_encrypt(iovec.in, iovec.out, iovec.len, &aes_ctx->ks.ks, ivec,
ecount_buf, &num);
}
}
static int aead_aes_eax_sealv(const EVP_AEAD_CTX *ctx,
Span<const CRYPTO_IOVEC> iovecs,
Span<uint8_t> out_tag, size_t *out_tag_len,
Span<const uint8_t> nonce,
Span<const CRYPTO_IVEC> aadvecs) {
// We use the full 128 bits of the nonce as counter, so no need to check the
// plaintext size.
if (out_tag.size() < ctx->tag_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL);
return 0;
}
if (nonce.size() != 12 && nonce.size() != 16) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
const struct aead_aes_eax_ctx *aes_ctx =
(struct aead_aes_eax_ctx *)&ctx->state;
// N <- OMAC(0 || nonce)
uint8_t n[AES_BLOCK_SIZE];
CRYPTO_IVEC noncevec[1];
noncevec[0].in = nonce.data();
noncevec[0].len = nonce.size();
omac_with_tag(aes_ctx, n, Span<const CRYPTO_IVEC>(noncevec), /*tag=*/0);
// H <- OMAC(1 || ad)
uint8_t h[AES_BLOCK_SIZE];
omac_with_tag(aes_ctx, h, aadvecs, /*tag=*/1);
// C <- CTR^{N}_{K}(M)
aes_ctr(aes_ctx, iovecs, n);
// MAC <- OMAC(2 || C)
omac_with_tag_iovec_out(aes_ctx, out_tag.data(), iovecs, /*tag=*/2);
// MAC <- N ^ C ^ H
CRYPTO_xor16(out_tag.data(), n, out_tag.data());
CRYPTO_xor16(out_tag.data(), h, out_tag.data());
*out_tag_len = ctx->tag_len;
return 1;
}
static int aead_aes_eax_openv_detached(const EVP_AEAD_CTX *ctx,
Span<const CRYPTO_IOVEC> iovecs,
Span<const uint8_t> nonce,
Span<const uint8_t> in_tag,
Span<const CRYPTO_IVEC> aadvecs) {
const uint64_t ad_len_64 = bssl::iovec::TotalLength(aadvecs);
if (ad_len_64 >= (UINT64_C(1) << 61)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
return 0;
}
if (in_tag.size() != EVP_AEAD_AES_EAX_TAG_LEN) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
if (nonce.size() != 12 && nonce.size() != 16) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
const struct aead_aes_eax_ctx *aes_ctx =
(struct aead_aes_eax_ctx *)&ctx->state;
// N <- OMAC(0 || nonce)
uint8_t n[AES_BLOCK_SIZE];
CRYPTO_IVEC noncevec[1];
noncevec[0].in = nonce.data();
noncevec[0].len = nonce.size();
omac_with_tag(aes_ctx, n, Span<const CRYPTO_IVEC>(noncevec),
/*tag=*/0);
// H <- OMAC(1 || ad)
uint8_t h[AES_BLOCK_SIZE];
omac_with_tag(aes_ctx, h, aadvecs, /*tag=*/1);
// MAC <- OMAC(2 || C)
uint8_t mac[AES_BLOCK_SIZE];
omac_with_tag(aes_ctx, mac, iovecs, /*tag=*/2);
// MAC <- N ^ C ^ H
CRYPTO_xor16(mac, n, mac);
CRYPTO_xor16(mac, h, mac);
if (CRYPTO_memcmp(mac, in_tag.data(), in_tag.size()) != 0) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
// M <- CTR^{N}_{K}(C)
aes_ctr(aes_ctx, iovecs, n);
return 1;
}
static const EVP_AEAD aead_aes_128_eax = {
16, // AES key size
16, // nonce length
EVP_AEAD_AES_EAX_TAG_LEN, // overhead
EVP_AEAD_AES_EAX_TAG_LEN, // max tag length
aead_aes_eax_init,
nullptr, // init_with_direction
aead_aes_eax_cleanup,
nullptr, // openv
aead_aes_eax_sealv,
aead_aes_eax_openv_detached,
nullptr, // get_iv
nullptr, // tag_len
};
static const EVP_AEAD aead_aes_256_eax = {
32, // AES key size
16, // nonce length
EVP_AEAD_AES_EAX_TAG_LEN, // overhead
EVP_AEAD_AES_EAX_TAG_LEN, // max tag length
aead_aes_eax_init,
nullptr, // init_with_direction
aead_aes_eax_cleanup,
nullptr, // openv
aead_aes_eax_sealv,
aead_aes_eax_openv_detached,
nullptr, // get_iv
nullptr, // tag_len
};
const EVP_AEAD *EVP_aead_aes_128_eax() { return &aead_aes_128_eax; }
const EVP_AEAD *EVP_aead_aes_256_eax() { return &aead_aes_256_eax; }
File diff suppressed because it is too large. Load diff
@@ -1,16 +1,16 @@
/* Copyright 2014 The BoringSSL Authors
*
* 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. */
// Copyright 2014 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_aead.h>
@@ -22,17 +22,20 @@
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_poly1305.h>
#include <CNIOBoringSSL_span.h>
#include "internal.h"
#include "../chacha/internal.h"
#include "../fipsmodule/cipher/internal.h"
#include "../internal.h"
#include "internal.h"
using namespace bssl;
struct aead_chacha20_poly1305_ctx {
uint8_t key[32];
};
static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >=
static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >=
sizeof(struct aead_chacha20_poly1305_ctx),
"AEAD state is too small");
static_assert(alignof(union evp_aead_ctx_st_state) >=
@@ -76,186 +79,252 @@ static void poly1305_update_length(poly1305_state *poly1305, size_t data_len) {
CRYPTO_poly1305_update(poly1305, length_bytes, sizeof(length_bytes));
}
// calc_tag fills |tag| with the authentication tag for the given inputs.
static void calc_tag(uint8_t tag[POLY1305_TAG_LEN], const uint8_t *key,
const uint8_t nonce[12], const uint8_t *ad, size_t ad_len,
const uint8_t *ciphertext, size_t ciphertext_len,
const uint8_t *ciphertext_extra,
size_t ciphertext_extra_len) {
// calc_tag_pre prepares filling `tag` with the authentication tag for the given
// inputs.
static size_t calc_tag_pre(poly1305_state *ctx, const uint8_t key[32],
const uint8_t nonce[12],
Span<const CRYPTO_IVEC> aadvecs) {
alignas(16) uint8_t poly1305_key[32];
OPENSSL_memset(poly1305_key, 0, sizeof(poly1305_key));
CRYPTO_chacha_20(poly1305_key, poly1305_key, sizeof(poly1305_key), key, nonce,
0);
static const uint8_t padding[16] = { 0 }; // Padding is all zeros.
poly1305_state ctx;
CRYPTO_poly1305_init(&ctx, poly1305_key);
CRYPTO_poly1305_update(&ctx, ad, ad_len);
static const uint8_t padding[16] = {0}; // Padding is all zeros.
CRYPTO_poly1305_init(ctx, poly1305_key);
size_t ad_len = 0;
for (const CRYPTO_IVEC &aadvec : aadvecs) {
CRYPTO_poly1305_update(ctx, aadvec.in, aadvec.len);
ad_len += aadvec.len;
}
if (ad_len % 16 != 0) {
CRYPTO_poly1305_update(&ctx, padding, sizeof(padding) - (ad_len % 16));
CRYPTO_poly1305_update(ctx, padding, sizeof(padding) - (ad_len % 16));
}
CRYPTO_poly1305_update(&ctx, ciphertext, ciphertext_len);
CRYPTO_poly1305_update(&ctx, ciphertext_extra, ciphertext_extra_len);
const size_t ciphertext_total = ciphertext_len + ciphertext_extra_len;
if (ciphertext_total % 16 != 0) {
CRYPTO_poly1305_update(&ctx, padding,
sizeof(padding) - (ciphertext_total % 16));
}
poly1305_update_length(&ctx, ad_len);
poly1305_update_length(&ctx, ciphertext_total);
CRYPTO_poly1305_finish(&ctx, tag);
return ad_len;
}
static int chacha20_poly1305_seal_scatter(
const uint8_t *key, uint8_t *out, uint8_t *out_tag,
size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce,
size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in,
size_t extra_in_len, const uint8_t *ad, size_t ad_len, size_t tag_len) {
if (extra_in_len + tag_len < tag_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
return 0;
static void calc_tag_post(poly1305_state *ctx, uint8_t tag[POLY1305_TAG_LEN],
size_t ciphertext_total, size_t ad_len) {
static const uint8_t padding[16] = {0}; // Padding is all zeros.
if (ciphertext_total % 16 != 0) {
CRYPTO_poly1305_update(ctx, padding,
sizeof(padding) - (ciphertext_total % 16));
}
if (max_out_tag_len < tag_len + extra_in_len) {
poly1305_update_length(ctx, ad_len);
poly1305_update_length(ctx, ciphertext_total);
CRYPTO_poly1305_finish(ctx, tag);
}
static int chacha20_poly1305_sealv(const uint8_t *key,
Span<const CRYPTO_IOVEC> iovecs,
Span<uint8_t> out_tag, size_t *out_tag_len,
Span<const uint8_t> nonce,
Span<const CRYPTO_IVEC> aadvecs,
size_t tag_len) {
if (out_tag.size() < tag_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL);
return 0;
}
if (nonce_len != 12) {
if (nonce.size() != 12) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
// |CRYPTO_chacha_20| uses a 32-bit block counter. Therefore we disallow
// `CRYPTO_chacha_20` uses a 32-bit block counter. Therefore we disallow
// individual operations that work on more than 256GB at a time.
// |in_len_64| is needed because, on 32-bit platforms, size_t is only
// `in_len_64` is needed because, on 32-bit platforms, size_t is only
// 32-bits and this produces a warning because it's always false.
// Casting to uint64_t inside the conditional is not sufficient to stop
// the warning.
const uint64_t in_len_64 = in_len;
const uint64_t in_len_64 = bssl::iovec::TotalLength(iovecs);
if (in_len_64 >= (UINT64_C(1) << 32) * 64 - 64) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
return 0;
}
if (max_out_tag_len < tag_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL);
return 0;
}
// The the extra input is given, it is expected to be very short and so is
// encrypted byte-by-byte first.
if (extra_in_len) {
static const size_t kChaChaBlockSize = 64;
uint32_t block_counter = (uint32_t)(1 + (in_len / kChaChaBlockSize));
size_t offset = in_len % kChaChaBlockSize;
uint8_t block[64 /* kChaChaBlockSize */];
for (size_t done = 0; done < extra_in_len; block_counter++) {
memset(block, 0, sizeof(block));
CRYPTO_chacha_20(block, block, sizeof(block), key, nonce,
block_counter);
for (size_t i = offset; i < sizeof(block) && done < extra_in_len;
i++, done++) {
out_tag[done] = extra_in[done] ^ block[i];
}
offset = 0;
}
}
union chacha20_poly1305_seal_data data;
if (chacha20_poly1305_asm_capable()) {
if (chacha20_poly1305_asm_capable() && iovecs.size() <= 2 &&
aadvecs.size() <= 1) {
OPENSSL_memcpy(data.in.key, key, 32);
data.in.counter = 0;
OPENSSL_memcpy(data.in.nonce, nonce, 12);
data.in.extra_ciphertext = out_tag;
data.in.extra_ciphertext_len = extra_in_len;
chacha20_poly1305_seal(out, in, in_len, ad, ad_len, &data);
CopySpan(nonce, data.in.nonce);
if (iovecs.size() >= 2) {
// `chacha20_poly1305_seal` only supports one extra input and expects it
// to have been encrypted ahead of time. (Historically it was only used
// for very short inputs.)
constexpr size_t kChaChaBlockSize = 64;
uint32_t block_counter =
(uint32_t)(1 + (iovecs[0].len / kChaChaBlockSize));
size_t offset = iovecs[0].len % kChaChaBlockSize;
size_t done = 0;
if (offset != 0) {
uint8_t block[kChaChaBlockSize];
memset(block, 0, sizeof(block));
CRYPTO_chacha_20(block, block, sizeof(block), key, nonce.data(),
block_counter);
for (size_t i = offset; i < sizeof(block) && done < iovecs[1].len;
i++, done++) {
iovecs[1].out[done] = iovecs[1].in[done] ^ block[i];
}
++block_counter;
}
if (done < iovecs[1].len) {
CRYPTO_chacha_20(iovecs[1].out + done, iovecs[1].in + done,
iovecs[1].len - done, key, nonce.data(),
block_counter);
}
// TODO(crbug.com/473454967): Support more than 1 extra ciphertext.
data.in.extra_ciphertext = iovecs[1].out;
data.in.extra_ciphertext_len = iovecs[1].len;
} else {
data.in.extra_ciphertext = nullptr;
data.in.extra_ciphertext_len = 0;
}
chacha20_poly1305_seal(iovecs.size() >= 1 ? iovecs[0].out : nullptr,
iovecs.size() >= 1 ? iovecs[0].in : nullptr,
iovecs.size() >= 1 ? iovecs[0].len : 0,
aadvecs.size() >= 1 ? aadvecs[0].in : nullptr,
aadvecs.size() >= 1 ? aadvecs[0].len : 0, &data);
} else {
CRYPTO_chacha_20(out, in, in_len, key, nonce, 1);
calc_tag(data.out.tag, key, nonce, ad, ad_len, out, in_len, out_tag,
extra_in_len);
poly1305_state ctx;
size_t ad_len = calc_tag_pre(&ctx, key, nonce.data(), aadvecs);
size_t ciphertext_total = 0;
size_t block = 1;
bssl::iovec::ForEachBlockRange<64, /*WriteOut=*/true>(
iovecs,
[&](const uint8_t *in, uint8_t *out, size_t len) {
// TODO(crbug.com/473454967): Maybe just provide asm version of this?
// Here, len is always a multiple of 64.
CRYPTO_chacha_20(out, in, len, key, nonce.data(), block);
CRYPTO_poly1305_update(&ctx, out, len);
ciphertext_total += len;
block += len / 64;
return true;
},
[&](const uint8_t *in, uint8_t *out, size_t len) {
// Here, len may be anything. If an asm version can't handle that,
// it will be worth splitting off multiples of 64 here.
CRYPTO_chacha_20(out, in, len, key, nonce.data(), block);
CRYPTO_poly1305_update(&ctx, out, len);
ciphertext_total += len;
return true;
});
calc_tag_post(&ctx, data.out.tag, ciphertext_total, ad_len);
}
OPENSSL_memcpy(out_tag + extra_in_len, data.out.tag, tag_len);
*out_tag_len = extra_in_len + tag_len;
CopyToPrefix(Span(data.out.tag).first(tag_len), out_tag);
*out_tag_len = tag_len;
return 1;
}
static int aead_chacha20_poly1305_seal_scatter(
const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag,
size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce,
size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in,
size_t extra_in_len, const uint8_t *ad, size_t ad_len) {
static int aead_chacha20_poly1305_sealv(const EVP_AEAD_CTX *ctx,
Span<const CRYPTO_IOVEC> iovecs,
Span<uint8_t> out_tag,
size_t *out_tag_len,
Span<const uint8_t> nonce,
Span<const CRYPTO_IVEC> aadvecs) {
const struct aead_chacha20_poly1305_ctx *c20_ctx =
(struct aead_chacha20_poly1305_ctx *)&ctx->state;
return chacha20_poly1305_seal_scatter(
c20_ctx->key, out, out_tag, out_tag_len, max_out_tag_len, nonce,
nonce_len, in, in_len, extra_in, extra_in_len, ad, ad_len, ctx->tag_len);
return chacha20_poly1305_sealv(c20_ctx->key, iovecs, out_tag, out_tag_len,
nonce, aadvecs, ctx->tag_len);
}
static int aead_xchacha20_poly1305_seal_scatter(
const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag,
size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce,
size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in,
size_t extra_in_len, const uint8_t *ad, size_t ad_len) {
static int aead_xchacha20_poly1305_sealv(const EVP_AEAD_CTX *ctx,
Span<const CRYPTO_IOVEC> iovecs,
Span<uint8_t> out_tag,
size_t *out_tag_len,
Span<const uint8_t> nonce,
Span<const CRYPTO_IVEC> aadvecs) {
const struct aead_chacha20_poly1305_ctx *c20_ctx =
(struct aead_chacha20_poly1305_ctx *)&ctx->state;
if (nonce_len != 24) {
if (nonce.size() != 24) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
alignas(4) uint8_t derived_key[32];
alignas(4) uint8_t derived_nonce[12];
CRYPTO_hchacha20(derived_key, c20_ctx->key, nonce);
CRYPTO_hchacha20(derived_key, c20_ctx->key, nonce.data());
OPENSSL_memset(derived_nonce, 0, 4);
OPENSSL_memcpy(&derived_nonce[4], &nonce[16], 8);
return chacha20_poly1305_seal_scatter(
derived_key, out, out_tag, out_tag_len, max_out_tag_len,
derived_nonce, sizeof(derived_nonce), in, in_len, extra_in, extra_in_len,
ad, ad_len, ctx->tag_len);
return chacha20_poly1305_sealv(derived_key, iovecs, out_tag, out_tag_len,
derived_nonce, aadvecs, ctx->tag_len);
}
static int chacha20_poly1305_open_gather(
const uint8_t *key, 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, size_t tag_len) {
if (nonce_len != 12) {
static int chacha20_poly1305_openv_detached(const uint8_t *key,
Span<const CRYPTO_IOVEC> iovecs,
Span<const uint8_t> nonce,
Span<const uint8_t> in_tag,
Span<const CRYPTO_IVEC> aadvecs,
size_t tag_len) {
if (nonce.size() != 12) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
if (in_tag_len != tag_len) {
if (in_tag.size() != tag_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
// |CRYPTO_chacha_20| uses a 32-bit block counter. Therefore we disallow
// `CRYPTO_chacha_20` uses a 32-bit block counter. Therefore we disallow
// individual operations that work on more than 256GB at a time.
// |in_len_64| is needed because, on 32-bit platforms, size_t is only
// `in_len_64` is needed because, on 32-bit platforms, size_t is only
// 32-bits and this produces a warning because it's always false.
// Casting to uint64_t inside the conditional is not sufficient to stop
// the warning.
const uint64_t in_len_64 = in_len;
const uint64_t in_len_64 = bssl::iovec::TotalLength(iovecs);
if (in_len_64 >= (UINT64_C(1) << 32) * 64 - 64) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
return 0;
}
union chacha20_poly1305_open_data data;
if (chacha20_poly1305_asm_capable()) {
if (chacha20_poly1305_asm_capable() && iovecs.size() <= 1 &&
aadvecs.size() <= 1) {
// TODO(crbug.com/473454967): Support more than 1 ciphertext segment.
OPENSSL_memcpy(data.in.key, key, 32);
data.in.counter = 0;
OPENSSL_memcpy(data.in.nonce, nonce, 12);
chacha20_poly1305_open(out, in, in_len, ad, ad_len, &data);
CopySpan(nonce, data.in.nonce);
chacha20_poly1305_open(iovecs.size() >= 1 ? iovecs[0].out : nullptr,
iovecs.size() >= 1 ? iovecs[0].in : nullptr,
iovecs.size() >= 1 ? iovecs[0].len : 0,
aadvecs.size() >= 1 ? aadvecs[0].in : nullptr,
aadvecs.size() >= 1 ? aadvecs[0].len : 0, &data);
} else {
calc_tag(data.out.tag, key, nonce, ad, ad_len, in, in_len, NULL, 0);
CRYPTO_chacha_20(out, in, in_len, key, nonce, 1);
poly1305_state ctx;
size_t ad_len = calc_tag_pre(&ctx, key, nonce.data(), aadvecs);
size_t ciphertext_total = 0;
size_t block = 1;
bssl::iovec::ForEachBlockRange<64, /*WriteOut=*/true>(
iovecs,
[&](const uint8_t *in, uint8_t *out, size_t len) {
// TODO(crbug.com/473454967): Maybe just provide asm version of this?
// Here, len is always a multiple of 64.
CRYPTO_poly1305_update(&ctx, in, len);
CRYPTO_chacha_20(out, in, len, key, nonce.data(), block);
ciphertext_total += len;
block += len / 64;
return true;
},
[&](const uint8_t *in, uint8_t *out, size_t len) {
// Here, len may be anything. If an asm version can't handle that,
// it will be worth splitting off multiples of 64 here.
CRYPTO_poly1305_update(&ctx, in, len);
CRYPTO_chacha_20(out, in, len, key, nonce.data(), block);
ciphertext_total += len;
return true;
});
calc_tag_post(&ctx, data.out.tag, ciphertext_total, ad_len);
}
if (CRYPTO_memcmp(data.out.tag, in_tag, tag_len) != 0) {
if (CRYPTO_memcmp(data.out.tag, in_tag.data(), tag_len) != 0) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
@@ -263,39 +332,37 @@ static int chacha20_poly1305_open_gather(
return 1;
}
static int aead_chacha20_poly1305_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) {
static int aead_chacha20_poly1305_openv_detached(
const EVP_AEAD_CTX *ctx, Span<const CRYPTO_IOVEC> iovecs,
Span<const uint8_t> nonce, Span<const uint8_t> in_tag,
Span<const CRYPTO_IVEC> aadvecs) {
const struct aead_chacha20_poly1305_ctx *c20_ctx =
(struct aead_chacha20_poly1305_ctx *)&ctx->state;
return chacha20_poly1305_open_gather(c20_ctx->key, out, nonce, nonce_len, in,
in_len, in_tag, in_tag_len, ad, ad_len,
ctx->tag_len);
return chacha20_poly1305_openv_detached(c20_ctx->key, iovecs, nonce, in_tag,
aadvecs, ctx->tag_len);
}
static int aead_xchacha20_poly1305_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) {
static int aead_xchacha20_poly1305_openv_detached(
const EVP_AEAD_CTX *ctx, Span<const CRYPTO_IOVEC> iovecs,
Span<const uint8_t> nonce, Span<const uint8_t> in_tag,
Span<const CRYPTO_IVEC> aadvecs) {
const struct aead_chacha20_poly1305_ctx *c20_ctx =
(struct aead_chacha20_poly1305_ctx *)&ctx->state;
if (nonce_len != 24) {
if (nonce.size() != 24) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
alignas(4) uint8_t derived_key[32];
alignas(4) uint8_t derived_nonce[12];
CRYPTO_hchacha20(derived_key, c20_ctx->key, nonce);
CRYPTO_hchacha20(derived_key, c20_ctx->key, nonce.data());
OPENSSL_memset(derived_nonce, 0, 4);
OPENSSL_memcpy(&derived_nonce[4], &nonce[16], 8);
return chacha20_poly1305_open_gather(
derived_key, out, derived_nonce, sizeof(derived_nonce), in, in_len,
in_tag, in_tag_len, ad, ad_len, ctx->tag_len);
return chacha20_poly1305_openv_detached(derived_key, iovecs, derived_nonce,
in_tag, aadvecs, ctx->tag_len);
}
static const EVP_AEAD aead_chacha20_poly1305 = {
@@ -303,16 +370,15 @@ static const EVP_AEAD aead_chacha20_poly1305 = {
12, // nonce len
POLY1305_TAG_LEN, // overhead
POLY1305_TAG_LEN, // max tag length
1, // seal_scatter_supports_extra_in
aead_chacha20_poly1305_init,
NULL, // init_with_direction
nullptr, // init_with_direction
aead_chacha20_poly1305_cleanup,
NULL /* open */,
aead_chacha20_poly1305_seal_scatter,
aead_chacha20_poly1305_open_gather,
NULL, // get_iv
NULL, // tag_len
nullptr, // openv
aead_chacha20_poly1305_sealv,
aead_chacha20_poly1305_openv_detached,
nullptr, // get_iv
nullptr, // tag_len
};
static const EVP_AEAD aead_xchacha20_poly1305 = {
@@ -320,22 +386,19 @@ static const EVP_AEAD aead_xchacha20_poly1305 = {
24, // nonce len
POLY1305_TAG_LEN, // overhead
POLY1305_TAG_LEN, // max tag length
1, // seal_scatter_supports_extra_in
aead_chacha20_poly1305_init,
NULL, // init_with_direction
nullptr, // init_with_direction
aead_chacha20_poly1305_cleanup,
NULL /* open */,
aead_xchacha20_poly1305_seal_scatter,
aead_xchacha20_poly1305_open_gather,
NULL, // get_iv
NULL, // tag_len
nullptr, // openv
aead_xchacha20_poly1305_sealv,
aead_xchacha20_poly1305_openv_detached,
nullptr, // get_iv
nullptr, // tag_len
};
const EVP_AEAD *EVP_aead_chacha20_poly1305(void) {
return &aead_chacha20_poly1305;
}
const EVP_AEAD *EVP_aead_chacha20_poly1305() { return &aead_chacha20_poly1305; }
const EVP_AEAD *EVP_aead_xchacha20_poly1305(void) {
const EVP_AEAD *EVP_aead_xchacha20_poly1305() {
return &aead_xchacha20_poly1305;
}
+58 -37
View File
@@ -1,11 +1,18 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stddef.h>
#include <CNIOBoringSSL_cipher.h>
#include <CNIOBoringSSL_des.h>
@@ -16,6 +23,8 @@
#include "internal.h"
using namespace bssl;
typedef struct {
union {
double align;
@@ -30,10 +39,10 @@ static int des_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key,
return 1;
}
static int des_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
size_t in_len) {
static int des_cbc_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out,
const uint8_t *in, size_t len) {
EVP_DES_KEY *dat = (EVP_DES_KEY *)ctx->cipher_data;
DES_ncbc_encrypt_ex(in, out, in_len, &dat->ks.ks, ctx->iv, ctx->encrypt);
DES_ncbc_encrypt_ex(in, out, len, &dat->ks.ks, ctx->iv, ctx->encrypt);
return 1;
}
@@ -45,22 +54,24 @@ static const EVP_CIPHER evp_des_cbc = {
/*ctx_size=*/sizeof(EVP_DES_KEY),
/*flags=*/EVP_CIPH_CBC_MODE,
/*init=*/des_init_key,
/*cipher=*/des_cbc_cipher,
/*cipher_update=*/des_cbc_cipher_update,
/*cipher_final=*/nullptr,
/*update_aad=*/nullptr,
/*cleanup=*/nullptr,
/*ctrl=*/nullptr,
};
const EVP_CIPHER *EVP_des_cbc(void) { return &evp_des_cbc; }
const EVP_CIPHER *EVP_des_cbc() { return &evp_des_cbc; }
static int des_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
size_t in_len) {
if (in_len < ctx->cipher->block_size) {
static int des_ecb_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out,
const uint8_t *in, size_t len) {
if (len < ctx->cipher->block_size) {
return 1;
}
in_len -= ctx->cipher->block_size;
len -= ctx->cipher->block_size;
EVP_DES_KEY *dat = (EVP_DES_KEY *)ctx->cipher_data;
for (size_t i = 0; i <= in_len; i += ctx->cipher->block_size) {
for (size_t i = 0; i <= len; i += ctx->cipher->block_size) {
DES_ecb_encrypt_ex(in + i, out + i, &dat->ks.ks, ctx->encrypt);
}
return 1;
@@ -74,12 +85,14 @@ static const EVP_CIPHER evp_des_ecb = {
/*ctx_size=*/sizeof(EVP_DES_KEY),
/*flags=*/EVP_CIPH_ECB_MODE,
/*init=*/des_init_key,
/*cipher=*/des_ecb_cipher,
/*cipher_update=*/des_ecb_cipher_update,
/*cipher_final=*/nullptr,
/*update_aad=*/nullptr,
/*cleanup=*/nullptr,
/*ctrl=*/nullptr,
};
const EVP_CIPHER *EVP_des_ecb(void) { return &evp_des_ecb; }
const EVP_CIPHER *EVP_des_ecb() { return &evp_des_ecb; }
typedef struct {
union {
@@ -97,10 +110,10 @@ static int des_ede3_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key,
return 1;
}
static int des_ede3_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out,
const uint8_t *in, size_t in_len) {
static int des_ede3_cbc_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out,
const uint8_t *in, size_t len) {
DES_EDE_KEY *dat = (DES_EDE_KEY *)ctx->cipher_data;
DES_ede3_cbc_encrypt_ex(in, out, in_len, &dat->ks.ks[0], &dat->ks.ks[1],
DES_ede3_cbc_encrypt_ex(in, out, len, &dat->ks.ks[0], &dat->ks.ks[1],
&dat->ks.ks[2], ctx->iv, ctx->encrypt);
return 1;
}
@@ -113,12 +126,14 @@ static const EVP_CIPHER evp_des_ede3_cbc = {
/*ctx_size=*/sizeof(DES_EDE_KEY),
/*flags=*/EVP_CIPH_CBC_MODE,
/*init=*/des_ede3_init_key,
/*cipher=*/des_ede3_cbc_cipher,
/*cipher_update=*/des_ede3_cbc_cipher_update,
/*cipher_final=*/nullptr,
/*update_aad=*/nullptr,
/*cleanup=*/nullptr,
/*ctrl=*/nullptr,
};
const EVP_CIPHER *EVP_des_ede3_cbc(void) { return &evp_des_ede3_cbc; }
const EVP_CIPHER *EVP_des_ede3_cbc() { 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) {
@@ -138,22 +153,24 @@ static const EVP_CIPHER evp_des_ede_cbc = {
/*ctx_size=*/sizeof(DES_EDE_KEY),
/*flags=*/EVP_CIPH_CBC_MODE,
/*init=*/des_ede_init_key,
/*cipher=*/des_ede3_cbc_cipher,
/*cipher_update=*/des_ede3_cbc_cipher_update,
/*cipher_final=*/nullptr,
/*update_aad=*/nullptr,
/*cleanup=*/nullptr,
/*ctrl=*/nullptr,
};
const EVP_CIPHER *EVP_des_ede_cbc(void) { return &evp_des_ede_cbc; }
const EVP_CIPHER *EVP_des_ede_cbc() { return &evp_des_ede_cbc; }
static int des_ede_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out,
const uint8_t *in, size_t in_len) {
if (in_len < ctx->cipher->block_size) {
static int des_ede_ecb_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out,
const uint8_t *in, size_t len) {
if (len < ctx->cipher->block_size) {
return 1;
}
in_len -= ctx->cipher->block_size;
len -= ctx->cipher->block_size;
DES_EDE_KEY *dat = (DES_EDE_KEY *)ctx->cipher_data;
for (size_t i = 0; i <= in_len; i += ctx->cipher->block_size) {
for (size_t i = 0; i <= len; i += ctx->cipher->block_size) {
DES_ecb3_encrypt_ex(in + i, out + i, &dat->ks.ks[0], &dat->ks.ks[1],
&dat->ks.ks[2], ctx->encrypt);
}
@@ -168,12 +185,14 @@ static const EVP_CIPHER evp_des_ede = {
/*ctx_size=*/sizeof(DES_EDE_KEY),
/*flags=*/EVP_CIPH_ECB_MODE,
/*init=*/des_ede_init_key,
/*cipher=*/des_ede_ecb_cipher,
/*cipher_update=*/des_ede_ecb_cipher_update,
/*cipher_final=*/nullptr,
/*update_aad=*/nullptr,
/*cleanup=*/nullptr,
/*ctrl=*/nullptr,
};
const EVP_CIPHER *EVP_des_ede(void) { return &evp_des_ede; }
const EVP_CIPHER *EVP_des_ede() { return &evp_des_ede; }
static const EVP_CIPHER evp_des_ede3 = {
/*nid=*/NID_des_ede3_ecb,
@@ -183,11 +202,13 @@ static const EVP_CIPHER evp_des_ede3 = {
/*ctx_size=*/sizeof(DES_EDE_KEY),
/*flags=*/EVP_CIPH_ECB_MODE,
/*init=*/des_ede3_init_key,
/*cipher=*/des_ede_ecb_cipher,
/*cipher_update=*/des_ede_ecb_cipher_update,
/*cipher_final=*/nullptr,
/*update_aad=*/nullptr,
/*cleanup=*/nullptr,
/*ctrl=*/nullptr,
};
const EVP_CIPHER *EVP_des_ede3(void) { return &evp_des_ede3; }
const EVP_CIPHER *EVP_des_ede3() { return &evp_des_ede3; }
const EVP_CIPHER *EVP_des_ede3_ecb(void) { return EVP_des_ede3(); }
const EVP_CIPHER *EVP_des_ede3_ecb() { return EVP_des_ede3(); }
+22 -13
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_cipher.h>
@@ -17,15 +22,17 @@
#include "../internal.h"
using namespace bssl;
static int null_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key,
const uint8_t *iv, int enc) {
return 1;
}
static int null_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
size_t in_len) {
static int null_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out,
const uint8_t *in, size_t len) {
if (in != out) {
OPENSSL_memcpy(out, in, in_len);
OPENSSL_memcpy(out, in, len);
}
return 1;
}
@@ -38,9 +45,11 @@ static const EVP_CIPHER n_cipher = {
/*ctx_size=*/0,
/*flags=*/0,
/*init=*/null_init_key,
/*cipher=*/null_cipher,
/*cipher_update=*/null_cipher_update,
/*cipher_final=*/nullptr,
/*update_aad=*/nullptr,
/*cleanup=*/nullptr,
/*ctrl=*/nullptr,
};
const EVP_CIPHER *EVP_enc_null(void) { return &n_cipher; }
const EVP_CIPHER *EVP_enc_null() { return &n_cipher; }
+56 -36
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_cipher.h>
#include <CNIOBoringSSL_nid.h>
@@ -95,7 +100,7 @@ typedef struct rc2_key_st {
uint16_t data[64];
} RC2_KEY;
static void RC2_encrypt(uint32_t *d, RC2_KEY *key) {
static void rc2_encrypt(uint32_t *d, RC2_KEY *key) {
int i, n;
uint16_t *p0, *p1;
uint16_t x0, x1, x2, x3, t;
@@ -139,7 +144,7 @@ static void RC2_encrypt(uint32_t *d, RC2_KEY *key) {
d[1] = (uint32_t)(x2 & 0xffff) | ((uint32_t)(x3 & 0xffff) << 16L);
}
static void RC2_decrypt(uint32_t *d, RC2_KEY *key) {
static void rc2_decrypt(uint32_t *d, RC2_KEY *key) {
int i, n;
uint16_t *p0, *p1;
uint16_t x0, x1, x2, x3, t;
@@ -184,7 +189,7 @@ static void RC2_decrypt(uint32_t *d, RC2_KEY *key) {
d[1] = (uint32_t)(x2 & 0xffff) | ((uint32_t)(x3 & 0xffff) << 16L);
}
static void RC2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length,
static void rc2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length,
RC2_KEY *ks, uint8_t *iv, int encrypt) {
uint32_t tin0, tin1;
uint32_t tout0, tout1, xor0, xor1;
@@ -202,7 +207,7 @@ static void RC2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length,
tin1 ^= tout1;
tin[0] = tin0;
tin[1] = tin1;
RC2_encrypt(tin, ks);
rc2_encrypt(tin, ks);
tout0 = tin[0];
l2c(tout0, out);
tout1 = tin[1];
@@ -214,7 +219,7 @@ static void RC2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length,
tin1 ^= tout1;
tin[0] = tin0;
tin[1] = tin1;
RC2_encrypt(tin, ks);
rc2_encrypt(tin, ks);
tout0 = tin[0];
l2c(tout0, out);
tout1 = tin[1];
@@ -231,7 +236,7 @@ static void RC2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length,
tin[0] = tin0;
c2l(in, tin1);
tin[1] = tin1;
RC2_decrypt(tin, ks);
rc2_decrypt(tin, ks);
tout0 = tin[0] ^ xor0;
tout1 = tin[1] ^ xor1;
l2c(tout0, out);
@@ -244,7 +249,7 @@ static void RC2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length,
tin[0] = tin0;
c2l(in, tin1);
tin[1] = tin1;
RC2_decrypt(tin, ks);
rc2_decrypt(tin, ks);
tout0 = tin[0] ^ xor0;
tout1 = tin[1] ^ xor1;
l2cn(tout0, tout1, out, l + 8);
@@ -282,18 +287,23 @@ static const uint8_t key_table[256] = {
0xfe, 0x7f, 0xc1, 0xad,
};
static void RC2_set_key(RC2_KEY *key, int len, const uint8_t *data, int bits) {
int i, j;
static int rc2_set_key(RC2_KEY *key, size_t len, const uint8_t *data,
int bits) {
size_t i, j;
uint8_t *k;
uint16_t *ki;
unsigned int c, d;
k = (uint8_t *)&key->data[0];
*k = 0; // for if there is a zero length key
if (len == 0) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_KEY_LENGTH);
return 0;
}
if (len > 128) {
len = 128;
}
if (bits <= 0) {
bits = 1024;
}
@@ -321,16 +331,20 @@ static void RC2_set_key(RC2_KEY *key, int len, const uint8_t *data, int bits) {
d = key_table[k[i] & c];
k[i] = d;
while (i--) {
while (i > 0) {
--i;
d = key_table[k[i + j] ^ d];
k[i] = d;
}
// copy from bytes into uint16_t's
ki = &(key->data[63]);
for (i = 127; i >= 0; i -= 2) {
*(ki--) = ((k[i] << 8) | k[i - 1]) & 0xffff;
for (i = 0; i < 64; ++i) {
j = 63 - i;
key->data[j] = ((k[2 * j + 1] << 8) | k[2 * j]) & 0xffff;
}
return 1;
}
typedef struct {
@@ -341,24 +355,26 @@ typedef struct {
static int rc2_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key,
const uint8_t *iv, int enc) {
EVP_RC2_KEY *rc2_key = (EVP_RC2_KEY *)ctx->cipher_data;
RC2_set_key(&rc2_key->ks, EVP_CIPHER_CTX_key_length(ctx), key,
rc2_key->key_bits);
if (!rc2_set_key(&rc2_key->ks, EVP_CIPHER_CTX_key_length(ctx), key,
rc2_key->key_bits)) {
return 0;
}
return 1;
}
static int rc2_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
size_t inl) {
static int rc2_cbc_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out,
const uint8_t *in, size_t len) {
EVP_RC2_KEY *key = (EVP_RC2_KEY *)ctx->cipher_data;
static const size_t kChunkSize = 0x10000;
while (inl >= kChunkSize) {
RC2_cbc_encrypt(in, out, kChunkSize, &key->ks, ctx->iv, ctx->encrypt);
inl -= kChunkSize;
while (len >= kChunkSize) {
rc2_cbc_encrypt(in, out, kChunkSize, &key->ks, ctx->iv, ctx->encrypt);
len -= kChunkSize;
in += kChunkSize;
out += kChunkSize;
}
if (inl) {
RC2_cbc_encrypt(in, out, inl, &key->ks, ctx->iv, ctx->encrypt);
if (len) {
rc2_cbc_encrypt(in, out, len, &key->ks, ctx->iv, ctx->encrypt);
}
return 1;
}
@@ -371,7 +387,7 @@ static int rc2_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) {
key->key_bits = EVP_CIPHER_CTX_key_length(ctx) * 8;
return 1;
case EVP_CTRL_SET_RC2_KEY_BITS:
// Should be overridden by later call to |EVP_CTRL_INIT|, but
// Should be overridden by later call to `EVP_CTRL_INIT`, but
// people call it, so it may as well work.
key->key_bits = arg;
return 1;
@@ -389,12 +405,14 @@ static const EVP_CIPHER rc2_40_cbc = {
/*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,
/*cipher_update=*/rc2_cbc_cipher_update,
/*cipher_final=*/nullptr,
/*update_aad=*/nullptr,
/*cleanup=*/nullptr,
/*ctrl=*/rc2_ctrl,
};
const EVP_CIPHER *EVP_rc2_40_cbc(void) { return &rc2_40_cbc; }
const EVP_CIPHER *EVP_rc2_40_cbc() { return &rc2_40_cbc; }
static const EVP_CIPHER rc2_cbc = {
/*nid=*/NID_rc2_cbc,
@@ -404,9 +422,11 @@ static const EVP_CIPHER rc2_cbc = {
/*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,
/*cipher_update=*/rc2_cbc_cipher_update,
/*cipher_final=*/nullptr,
/*update_aad=*/nullptr,
/*cleanup=*/nullptr,
/*ctrl=*/rc2_ctrl,
};
const EVP_CIPHER *EVP_rc2_cbc(void) { return &rc2_cbc; }
const EVP_CIPHER *EVP_rc2_cbc() { return &rc2_cbc; }
+20 -13
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <assert.h>
#include <string.h>
@@ -25,11 +30,11 @@ static int rc4_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key,
return 1;
}
static int rc4_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
size_t in_len) {
static int rc4_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out,
const uint8_t *in, size_t len) {
RC4_KEY *rc4key = (RC4_KEY *)ctx->cipher_data;
RC4(rc4key, in_len, in, out);
RC4(rc4key, len, in, out);
return 1;
}
@@ -41,9 +46,11 @@ static const EVP_CIPHER rc4 = {
/*ctx_size=*/sizeof(RC4_KEY),
/*flags=*/EVP_CIPH_VARIABLE_LENGTH,
/*init=*/rc4_init_key,
/*cipher=*/rc4_cipher,
/*cipher_update=*/rc4_cipher_update,
/*cipher_final=*/nullptr,
/*update_aad=*/nullptr,
/*cleanup=*/nullptr,
/*ctrl=*/nullptr,
};
const EVP_CIPHER *EVP_rc4(void) { return &rc4; }
const EVP_CIPHER *EVP_rc4() { return &rc4; }
+276 -260
View File
@@ -1,16 +1,16 @@
/* Copyright 2014 The BoringSSL Authors
*
* 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. */
// Copyright 2014 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <assert.h>
#include <limits.h>
@@ -23,15 +23,19 @@
#include <CNIOBoringSSL_md5.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_sha.h>
#include <CNIOBoringSSL_span.h>
#include "../fipsmodule/cipher/internal.h"
#include "../internal.h"
#include "../mem_internal.h"
#include "internal.h"
using namespace bssl;
typedef struct {
EVP_CIPHER_CTX cipher_ctx;
HMAC_CTX hmac_ctx;
HMAC_CTX *hmac_ctx;
// mac_key is the portion of the key used for the MAC. It is retained
// separately for the constant-time CBC code.
uint8_t mac_key[EVP_MAX_MD_SIZE];
@@ -43,7 +47,7 @@ typedef struct {
static_assert(EVP_MAX_MD_SIZE < 256, "mac_key_len does not fit in uint8_t");
static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >= sizeof(AEAD_TLS_CTX),
static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >= sizeof(AEAD_TLS_CTX),
"AEAD state is too small");
static_assert(alignof(union evp_aead_ctx_st_state) >= alignof(AEAD_TLS_CTX),
"AEAD state has insufficient alignment");
@@ -51,15 +55,14 @@ static_assert(alignof(union evp_aead_ctx_st_state) >= alignof(AEAD_TLS_CTX),
static void aead_tls_cleanup(EVP_AEAD_CTX *ctx) {
AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state;
EVP_CIPHER_CTX_cleanup(&tls_ctx->cipher_ctx);
HMAC_CTX_cleanup(&tls_ctx->hmac_ctx);
HMAC_CTX_free(tls_ctx->hmac_ctx);
}
static int aead_tls_init(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len,
size_t tag_len, enum evp_aead_direction_t dir,
const EVP_CIPHER *cipher, const EVP_MD *md,
char implicit_iv) {
if (tag_len != EVP_AEAD_DEFAULT_TAG_LENGTH &&
tag_len != EVP_MD_size(md)) {
if (tag_len != EVP_AEAD_DEFAULT_TAG_LENGTH && tag_len != EVP_MD_size(md)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_TAG_SIZE);
return 0;
}
@@ -72,20 +75,25 @@ static int aead_tls_init(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len,
size_t mac_key_len = EVP_MD_size(md);
size_t enc_key_len = EVP_CIPHER_key_length(cipher);
assert(mac_key_len + enc_key_len +
(implicit_iv ? EVP_CIPHER_iv_length(cipher) : 0) == key_len);
(implicit_iv ? EVP_CIPHER_iv_length(cipher) : 0) ==
key_len);
AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state;
tls_ctx->hmac_ctx = HMAC_CTX_new();
if (!tls_ctx->hmac_ctx) {
return 0;
}
EVP_CIPHER_CTX_init(&tls_ctx->cipher_ctx);
HMAC_CTX_init(&tls_ctx->hmac_ctx);
assert(mac_key_len <= EVP_MAX_MD_SIZE);
OPENSSL_memcpy(tls_ctx->mac_key, key, mac_key_len);
tls_ctx->mac_key_len = (uint8_t)mac_key_len;
tls_ctx->implicit_iv = implicit_iv;
if (!EVP_CipherInit_ex(&tls_ctx->cipher_ctx, cipher, NULL, &key[mac_key_len],
implicit_iv ? &key[mac_key_len + enc_key_len] : NULL,
dir == evp_aead_seal) ||
!HMAC_Init_ex(&tls_ctx->hmac_ctx, key, mac_key_len, md, NULL)) {
if (!EVP_CipherInit_ex(
&tls_ctx->cipher_ctx, cipher, nullptr, &key[mac_key_len],
implicit_iv ? &key[mac_key_len + enc_key_len] : nullptr,
dir == evp_aead_seal) ||
!HMAC_Init_ex(tls_ctx->hmac_ctx, key, mac_key_len, md, nullptr)) {
aead_tls_cleanup(ctx);
return 0;
}
@@ -94,33 +102,24 @@ static int aead_tls_init(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len,
return 1;
}
static size_t aead_tls_tag_len(const EVP_AEAD_CTX *ctx, const size_t in_len,
const size_t extra_in_len) {
assert(extra_in_len == 0);
static size_t aead_tls_tag_len(const EVP_AEAD_CTX *ctx, const size_t in_len) {
const AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state;
assert(EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE);
const size_t hmac_len = HMAC_size(&tls_ctx->hmac_ctx);
if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) != EVP_CIPH_CBC_MODE) {
// The NULL cipher.
return hmac_len;
}
const size_t hmac_len = HMAC_size(tls_ctx->hmac_ctx);
const size_t block_size = EVP_CIPHER_CTX_block_size(&tls_ctx->cipher_ctx);
// An overflow of |in_len + hmac_len| doesn't affect the result mod
// |block_size|, provided that |block_size| is a smaller power of two.
assert(block_size != 0 && (block_size & (block_size - 1)) == 0);
const size_t pad_len = block_size - (in_len + hmac_len) % block_size;
// An overflow of `in_len + hmac_len` doesn't affect the result mod
// `block_size`, provided that `block_size` is a smaller power of two.
assert(block_size == 8 /*3DES*/ || block_size == 16 /*AES*/);
const size_t pad_len = block_size - ((in_len + hmac_len) & (block_size - 1));
return hmac_len + pad_len;
}
static int aead_tls_seal_scatter(const EVP_AEAD_CTX *ctx, uint8_t *out,
uint8_t *out_tag, size_t *out_tag_len,
const size_t max_out_tag_len,
const uint8_t *nonce, const size_t nonce_len,
const uint8_t *in, const size_t in_len,
const uint8_t *extra_in,
const size_t extra_in_len, const uint8_t *ad,
const size_t ad_len) {
static int aead_tls_sealv(const EVP_AEAD_CTX *ctx,
Span<const CRYPTO_IOVEC> iovecs,
Span<uint8_t> out_tag, size_t *out_tag_len,
Span<const uint8_t> nonce,
Span<const CRYPTO_IVEC> aadvecs) {
AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state;
if (!tls_ctx->cipher_ctx.encrypt) {
@@ -129,114 +128,147 @@ static int aead_tls_seal_scatter(const EVP_AEAD_CTX *ctx, uint8_t *out,
return 0;
}
if (in_len > INT_MAX) {
// EVP_CIPHER takes int as input.
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
return 0;
}
if (max_out_tag_len < aead_tls_tag_len(ctx, in_len, extra_in_len)) {
size_t in_len = bssl::iovec::TotalLength(iovecs);
if (out_tag.size() < aead_tls_tag_len(ctx, in_len)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL);
return 0;
}
if (nonce_len != EVP_AEAD_nonce_length(ctx->aead)) {
if (nonce.size() != EVP_AEAD_nonce_length(ctx->aead)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE);
return 0;
}
size_t ad_len = bssl::iovec::TotalLength(aadvecs);
if (ad_len != 13 - 2 /* length bytes */) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_AD_SIZE);
return 0;
}
// To allow for CBC mode which changes cipher length, |ad| doesn't include the
// To allow for CBC mode which changes cipher length, `ad` doesn't include the
// length for legacy ciphers.
uint8_t ad_extra[2];
ad_extra[0] = (uint8_t)(in_len >> 8);
ad_extra[1] = (uint8_t)(in_len & 0xff);
CRYPTO_store_u16_be(ad_extra, static_cast<uint16_t>(in_len));
// Compute the MAC. This must be first in case the operation is being done
// in-place.
uint8_t mac[EVP_MAX_MD_SIZE];
if (!HMAC_Init_ex(tls_ctx->hmac_ctx, nullptr, 0, nullptr, nullptr)) {
return 0;
}
for (const CRYPTO_IVEC &aadvec : aadvecs) {
if (!HMAC_Update(tls_ctx->hmac_ctx, aadvec.in, aadvec.len)) {
return 0;
}
}
if (!HMAC_Update(tls_ctx->hmac_ctx, ad_extra, sizeof(ad_extra))) {
return 0;
}
for (const CRYPTO_IOVEC &iovec : iovecs) {
if (!HMAC_Update(tls_ctx->hmac_ctx, iovec.in, iovec.len)) {
return 0;
}
}
unsigned mac_len;
if (!HMAC_Init_ex(&tls_ctx->hmac_ctx, NULL, 0, NULL, NULL) ||
!HMAC_Update(&tls_ctx->hmac_ctx, ad, ad_len) ||
!HMAC_Update(&tls_ctx->hmac_ctx, ad_extra, sizeof(ad_extra)) ||
!HMAC_Update(&tls_ctx->hmac_ctx, in, in_len) ||
!HMAC_Final(&tls_ctx->hmac_ctx, mac, &mac_len)) {
if (!HMAC_Final(tls_ctx->hmac_ctx, mac, &mac_len)) {
return 0;
}
// Configure the explicit IV.
if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE &&
!tls_ctx->implicit_iv &&
!EVP_EncryptInit_ex(&tls_ctx->cipher_ctx, NULL, NULL, NULL, nonce)) {
assert(EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE);
if (!tls_ctx->implicit_iv &&
!EVP_EncryptInit_ex(&tls_ctx->cipher_ctx, nullptr, nullptr, nullptr,
nonce.data())) {
return 0;
}
size_t block_size = EVP_CIPHER_CTX_block_size(&tls_ctx->cipher_ctx);
assert(block_size == 8 /*3DES*/ || block_size == 16 /*AES*/);
// Encrypt the input.
int len;
if (!EVP_EncryptUpdate(&tls_ctx->cipher_ctx, out, &len, in, (int)in_len)) {
size_t len = 0;
size_t tag_len = 0;
if (!bssl::iovec::ForEachBlockRange_Dynamic</*WriteOut=*/true>(
block_size, iovecs,
[&](const uint8_t *in, uint8_t *out, size_t chunk_len) {
// Complete block(s).
size_t out_len;
if (!EVP_EncryptUpdate_ex(&tls_ctx->cipher_ctx, out, &out_len,
chunk_len, in, chunk_len)) {
return false;
}
assert(out_len == chunk_len);
len += out_len;
return true;
},
[&](const uint8_t *in, uint8_t *out, size_t chunk_len) {
// Final chunk, possibly with a partial block.
size_t out_len;
if (!EVP_EncryptUpdate_ex(&tls_ctx->cipher_ctx, out, &out_len,
chunk_len, in, chunk_len)) {
return false;
}
len += out_len;
size_t remaining = chunk_len - out_len;
assert(remaining < block_size);
if (remaining == 0) {
return true;
}
// Feed the MAC into the cipher in two steps. First complete the
// final partial block from encrypting the input and split the
// result between `out` and `out_tag`. Then feed the rest.
const size_t early_mac_len = block_size - remaining;
assert(early_mac_len < block_size);
assert(len + block_size - early_mac_len == in_len);
uint8_t buf[EVP_MAX_BLOCK_LENGTH];
size_t buf_len;
if (!EVP_EncryptUpdate_ex(&tls_ctx->cipher_ctx, buf, &buf_len,
sizeof(buf), mac, early_mac_len)) {
return false;
}
assert(buf_len == block_size);
OPENSSL_memcpy(out + out_len, buf, remaining);
OPENSSL_memcpy(out_tag.data(), buf + remaining, early_mac_len);
tag_len = early_mac_len;
return true;
})) {
return 0;
}
unsigned block_size = EVP_CIPHER_CTX_block_size(&tls_ctx->cipher_ctx);
// Feed the MAC into the cipher in two steps. First complete the final partial
// block from encrypting the input and split the result between |out| and
// |out_tag|. Then feed the rest.
const size_t early_mac_len = (block_size - (in_len % block_size)) % block_size;
if (early_mac_len != 0) {
assert(len + block_size - early_mac_len == in_len);
uint8_t buf[EVP_MAX_BLOCK_LENGTH];
int buf_len;
if (!EVP_EncryptUpdate(&tls_ctx->cipher_ctx, buf, &buf_len, mac,
(int)early_mac_len)) {
return 0;
}
assert(buf_len == (int)block_size);
OPENSSL_memcpy(out + len, buf, block_size - early_mac_len);
OPENSSL_memcpy(out_tag, buf + block_size - early_mac_len, early_mac_len);
}
size_t tag_len = early_mac_len;
if (!EVP_EncryptUpdate(&tls_ctx->cipher_ctx, out_tag + tag_len, &len,
mac + tag_len, mac_len - tag_len)) {
if (!EVP_EncryptUpdate_ex(&tls_ctx->cipher_ctx, out_tag.data() + tag_len,
&len, out_tag.size() - tag_len, mac + tag_len,
mac_len - tag_len)) {
return 0;
}
tag_len += len;
if (block_size > 1) {
assert(block_size <= 256);
assert(EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE);
// Compute padding and feed that into the cipher.
uint8_t padding[256];
unsigned padding_len = block_size - ((in_len + mac_len) % block_size);
OPENSSL_memset(padding, padding_len - 1, padding_len);
if (!EVP_EncryptUpdate(&tls_ctx->cipher_ctx, out_tag + tag_len, &len,
padding, (int)padding_len)) {
return 0;
}
tag_len += len;
// Compute padding and feed that into the cipher.
uint8_t padding[256];
unsigned padding_len = block_size - ((in_len + mac_len) & (block_size - 1));
OPENSSL_memset(padding, padding_len - 1, padding_len);
if (!EVP_EncryptUpdate_ex(&tls_ctx->cipher_ctx, out_tag.data() + tag_len,
&len, out_tag.size() - tag_len, padding,
padding_len)) {
return 0;
}
tag_len += len;
if (!EVP_EncryptFinal_ex(&tls_ctx->cipher_ctx, out_tag + tag_len, &len)) {
if (!EVP_EncryptFinal_ex2(&tls_ctx->cipher_ctx, out_tag.data() + tag_len,
&len, out_tag.size() - tag_len)) {
return 0;
}
assert(len == 0); // Padding is explicit.
assert(tag_len == aead_tls_tag_len(ctx, in_len, extra_in_len));
assert(tag_len == aead_tls_tag_len(ctx, in_len));
*out_tag_len = tag_len;
return 1;
}
static int aead_tls_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_tls_openv(const EVP_AEAD_CTX *ctx,
Span<const CRYPTO_IOVEC> iovecs,
size_t *out_total_bytes, Span<const uint8_t> nonce,
Span<const CRYPTO_IVEC> aadvecs) {
AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state;
if (tls_ctx->cipher_ctx.encrypt) {
@@ -245,144 +277,135 @@ static int aead_tls_open(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len,
return 0;
}
if (in_len < HMAC_size(&tls_ctx->hmac_ctx)) {
size_t in_len = bssl::iovec::TotalLength(iovecs);
if (in_len < HMAC_size(tls_ctx->hmac_ctx)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
if (max_out_len < in_len) {
// This requires that the caller provide space for the MAC, even though it
// will always be removed on return.
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL);
return 0;
}
if (nonce_len != EVP_AEAD_nonce_length(ctx->aead)) {
if (nonce.size() != EVP_AEAD_nonce_length(ctx->aead)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE);
return 0;
}
size_t ad_len = bssl::iovec::TotalLength(aadvecs);
if (ad_len != 13 - 2 /* length bytes */) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_AD_SIZE);
return 0;
}
if (in_len > INT_MAX) {
// EVP_CIPHER takes int as input.
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
return 0;
}
// Configure the explicit IV.
if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE &&
!tls_ctx->implicit_iv &&
!EVP_DecryptInit_ex(&tls_ctx->cipher_ctx, NULL, NULL, NULL, nonce)) {
assert(EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE);
if (!tls_ctx->implicit_iv &&
!EVP_DecryptInit_ex(&tls_ctx->cipher_ctx, nullptr, nullptr, nullptr,
nonce.data())) {
return 0;
}
// Decrypt to get the plaintext + MAC + padding.
size_t total = 0;
int len;
if (!EVP_DecryptUpdate(&tls_ctx->cipher_ctx, out, &len, in, (int)in_len)) {
return 0;
size_t block_size = EVP_CIPHER_CTX_block_size(&tls_ctx->cipher_ctx);
auto decrypt_update = [&](const uint8_t *in, uint8_t *out, size_t len) {
size_t out_len;
if (!EVP_DecryptUpdate_ex(&tls_ctx->cipher_ctx, out, &out_len, len, in,
len)) {
return false;
}
CONSTTIME_SECRET(out, out_len);
if (out_len != len) {
// A byte sequence that was not a multiple of the block size was provided
// as ciphertext. This is generally invalid and thus should be rejected.
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return false;
}
total += len;
return true;
};
if (!bssl::iovec::ForEachBlockRange_Dynamic</*WriteOut=*/true>(
block_size, iovecs, decrypt_update, decrypt_update)) {
return false;
}
total += len;
if (!EVP_DecryptFinal_ex(&tls_ctx->cipher_ctx, out + total, &len)) {
return 0;
}
total += len;
assert(total == in_len);
CONSTTIME_SECRET(out, total);
const size_t mac_len = HMAC_size(tls_ctx->hmac_ctx);
// Split the decrypted record into `iovecs_without_trailer` and `trailer`,
// based on the public lower bound of where the plaintext ends. The plaintext
// is followed by `mac_len` and then at most 256 bytes of padding.
bssl::iovec::MaybeInplaceArray iovecs_without_trailer;
if (!iovecs_without_trailer.CopyFrom(iovecs)) {
return 0;
}
uint8_t trailer_buf[EVP_MAX_MD_SIZE + 256];
const size_t trailer_len = std::min(in_len, mac_len + 256);
std::optional<Span<const uint8_t>> trailer =
bssl::iovec::GetAndRemoveOutSuffix(Span(trailer_buf).first(trailer_len),
Span(iovecs_without_trailer));
BSSL_CHECK(trailer.has_value());
// Remove CBC padding. Code from here on is timing-sensitive with respect to
// |padding_ok| and |data_plus_mac_len| for CBC ciphers.
size_t data_plus_mac_len;
// `padding_ok`, `trailer_minus_padding`, and derived values.
crypto_word_t padding_ok;
if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE) {
if (!EVP_tls_cbc_remove_padding(
&padding_ok, &data_plus_mac_len, out, total,
EVP_CIPHER_CTX_block_size(&tls_ctx->cipher_ctx),
HMAC_size(&tls_ctx->hmac_ctx))) {
// Publicly invalid. This can be rejected in non-constant time.
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
} else {
padding_ok = CONSTTIME_TRUE_W;
data_plus_mac_len = total;
// |data_plus_mac_len| = |total| = |in_len| at this point. |in_len| has
// already been checked against the MAC size at the top of the function.
assert(data_plus_mac_len >= HMAC_size(&tls_ctx->hmac_ctx));
}
size_t data_len = data_plus_mac_len - HMAC_size(&tls_ctx->hmac_ctx);
// At this point, if the padding is valid, the first |data_plus_mac_len| bytes
// after |out| are the plaintext and MAC. Otherwise, |data_plus_mac_len| is
// still large enough to extract a MAC, but it will be irrelevant.
// To allow for CBC mode which changes cipher length, |ad| doesn't include the
// length for legacy ciphers.
uint8_t ad_fixed[13];
OPENSSL_memcpy(ad_fixed, ad, 11);
ad_fixed[11] = (uint8_t)(data_len >> 8);
ad_fixed[12] = (uint8_t)(data_len & 0xff);
ad_len += 2;
// Compute the MAC and extract the one in the record.
uint8_t mac[EVP_MAX_MD_SIZE];
size_t mac_len;
uint8_t record_mac_tmp[EVP_MAX_MD_SIZE];
uint8_t *record_mac;
if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE &&
EVP_tls_cbc_record_digest_supported(tls_ctx->hmac_ctx.md)) {
if (!EVP_tls_cbc_digest_record(tls_ctx->hmac_ctx.md, mac, &mac_len,
ad_fixed, out, data_len, total,
tls_ctx->mac_key, tls_ctx->mac_key_len)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
assert(mac_len == HMAC_size(&tls_ctx->hmac_ctx));
record_mac = record_mac_tmp;
EVP_tls_cbc_copy_mac(record_mac, mac_len, out, data_plus_mac_len, total);
} else {
// We should support the constant-time path for all CBC-mode ciphers
// implemented.
assert(EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) != EVP_CIPH_CBC_MODE);
unsigned mac_len_u;
if (!HMAC_Init_ex(&tls_ctx->hmac_ctx, NULL, 0, NULL, NULL) ||
!HMAC_Update(&tls_ctx->hmac_ctx, ad_fixed, ad_len) ||
!HMAC_Update(&tls_ctx->hmac_ctx, out, data_len) ||
!HMAC_Final(&tls_ctx->hmac_ctx, mac, &mac_len_u)) {
return 0;
}
mac_len = mac_len_u;
assert(mac_len == HMAC_size(&tls_ctx->hmac_ctx));
record_mac = &out[data_len];
}
// Perform the MAC check and the padding check in constant-time. It should be
// safe to simply perform the padding check first, but it would not be under a
// different choice of MAC location on padding failure. See
// EVP_tls_cbc_remove_padding.
crypto_word_t good =
constant_time_eq_int(CRYPTO_memcmp(record_mac, mac, mac_len), 0);
good &= padding_ok;
CONSTTIME_DECLASSIFY(&good, sizeof(good));
if (!good) {
size_t trailer_minus_padding;
if (!EVP_tls_cbc_remove_padding(&padding_ok, &trailer_minus_padding,
trailer->data(), trailer->size(), block_size,
mac_len)) {
// Publicly invalid. This can be rejected in non-constant time.
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
CONSTTIME_DECLASSIFY(&data_len, sizeof(data_len));
CONSTTIME_DECLASSIFY(out, data_len);
// If the padding is valid, `trailer->first(trailer_minus_padding)` is the
// last bytes of plaintext and the MAC. Otherwise, it is still large enough to
// extract a MAC, but it will be irrelevant. Note that `trailer_minus_padding`
// is secret.
declassify_assert(trailer_minus_padding >= mac_len);
size_t data_in_trailer_len = trailer_minus_padding - mac_len;
size_t max_data_in_trailer_len = trailer->size() - mac_len;
size_t data_len = total - trailer->size() + data_in_trailer_len;
// To allow for CBC mode which changes cipher length, `ad_len` doesn't
// include the length for legacy ciphers.
uint8_t ad_extra[2];
CRYPTO_store_u16_be(ad_extra, static_cast<uint16_t>(data_len));
// Compute the MAC and extract the one in the record.
uint8_t mac[EVP_MAX_MD_SIZE];
size_t got_mac_len;
assert(EVP_tls_cbc_record_digest_supported(tls_ctx->hmac_ctx->md));
if (!EVP_tls_cbc_digest_record(
tls_ctx->hmac_ctx->md, mac, &got_mac_len, ad_extra, aadvecs,
iovecs_without_trailer, trailer->first(max_data_in_trailer_len),
data_in_trailer_len, tls_ctx->mac_key, tls_ctx->mac_key_len)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
assert(got_mac_len == mac_len);
uint8_t record_mac[EVP_MAX_MD_SIZE];
EVP_tls_cbc_copy_mac(record_mac, mac_len, trailer->data(),
trailer_minus_padding, trailer->size());
// Perform the MAC check and the padding check in constant-time. It should be
// safe to simply perform the padding check first, but it would not be under a
// different choice of MAC location on padding failure. See
// EVP_tls_cbc_remove_padding. The value barrier seems to be necessary to
// prevent a branch in Clang.
crypto_word_t good = value_barrier_w(
constant_time_eq_int(CRYPTO_memcmp(record_mac, mac, mac_len), 0));
good &= padding_ok;
if (!constant_time_declassify_w(good)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
// End of timing-sensitive code.
CONSTTIME_DECLASSIFY(&data_len, sizeof(data_len));
for (const CRYPTO_IOVEC &iovec : iovecs) {
CONSTTIME_DECLASSIFY(iovec.out, iovec.len);
}
*out_len = data_len;
*out_total_bytes = data_len;
return 1;
}
@@ -456,15 +479,14 @@ static const EVP_AEAD aead_aes_128_cbc_sha1_tls = {
16, // nonce len (IV)
16 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1)
SHA_DIGEST_LENGTH, // max tag length
0, // seal_scatter_supports_extra_in
NULL, // init
nullptr, // init
aead_aes_128_cbc_sha1_tls_init,
aead_tls_cleanup,
aead_tls_open,
aead_tls_seal_scatter,
NULL, // open_gather
NULL, // get_iv
aead_tls_openv,
aead_tls_sealv,
nullptr, // openv_detached
nullptr, // get_iv
aead_tls_tag_len,
};
@@ -473,14 +495,13 @@ static const EVP_AEAD aead_aes_128_cbc_sha1_tls_implicit_iv = {
0, // nonce len
16 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1)
SHA_DIGEST_LENGTH, // max tag length
0, // seal_scatter_supports_extra_in
NULL, // init
nullptr, // init
aead_aes_128_cbc_sha1_tls_implicit_iv_init,
aead_tls_cleanup,
aead_tls_open,
aead_tls_seal_scatter,
NULL, // open_gather
aead_tls_openv,
aead_tls_sealv,
nullptr, // openv_detached
aead_tls_get_iv, // get_iv
aead_tls_tag_len,
};
@@ -490,15 +511,14 @@ static const EVP_AEAD aead_aes_128_cbc_sha256_tls = {
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
nullptr, // 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_openv,
aead_tls_sealv,
nullptr, // openv_detached
nullptr, // get_iv
aead_tls_tag_len,
};
@@ -507,15 +527,14 @@ static const EVP_AEAD aead_aes_256_cbc_sha1_tls = {
16, // nonce len (IV)
16 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1)
SHA_DIGEST_LENGTH, // max tag length
0, // seal_scatter_supports_extra_in
NULL, // init
nullptr, // init
aead_aes_256_cbc_sha1_tls_init,
aead_tls_cleanup,
aead_tls_open,
aead_tls_seal_scatter,
NULL, // open_gather
NULL, // get_iv
aead_tls_openv,
aead_tls_sealv,
nullptr, // openv_detached
nullptr, // get_iv
aead_tls_tag_len,
};
@@ -524,14 +543,13 @@ static const EVP_AEAD aead_aes_256_cbc_sha1_tls_implicit_iv = {
0, // nonce len
16 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1)
SHA_DIGEST_LENGTH, // max tag length
0, // seal_scatter_supports_extra_in
NULL, // init
nullptr, // init
aead_aes_256_cbc_sha1_tls_implicit_iv_init,
aead_tls_cleanup,
aead_tls_open,
aead_tls_seal_scatter,
NULL, // open_gather
aead_tls_openv,
aead_tls_sealv,
nullptr, // openv_detached
aead_tls_get_iv, // get_iv
aead_tls_tag_len,
};
@@ -541,15 +559,14 @@ static const EVP_AEAD aead_des_ede3_cbc_sha1_tls = {
8, // nonce len (IV)
8 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1)
SHA_DIGEST_LENGTH, // max tag length
0, // seal_scatter_supports_extra_in
NULL, // init
nullptr, // init
aead_des_ede3_cbc_sha1_tls_init,
aead_tls_cleanup,
aead_tls_open,
aead_tls_seal_scatter,
NULL, // open_gather
NULL, // get_iv
aead_tls_openv,
aead_tls_sealv,
nullptr, // openv_detached
nullptr, // get_iv
aead_tls_tag_len,
};
@@ -558,42 +575,41 @@ static const EVP_AEAD aead_des_ede3_cbc_sha1_tls_implicit_iv = {
0, // nonce len
8 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1)
SHA_DIGEST_LENGTH, // max tag length
0, // seal_scatter_supports_extra_in
NULL, // init
nullptr, // init
aead_des_ede3_cbc_sha1_tls_implicit_iv_init,
aead_tls_cleanup,
aead_tls_open,
aead_tls_seal_scatter,
NULL, // open_gather
aead_tls_openv,
aead_tls_sealv,
nullptr, // openv_detached
aead_tls_get_iv, // get_iv
aead_tls_tag_len,
};
const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls(void) {
const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls() {
return &aead_aes_128_cbc_sha1_tls;
}
const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls_implicit_iv(void) {
const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls_implicit_iv() {
return &aead_aes_128_cbc_sha1_tls_implicit_iv;
}
const EVP_AEAD *EVP_aead_aes_128_cbc_sha256_tls(void) {
const EVP_AEAD *EVP_aead_aes_128_cbc_sha256_tls() {
return &aead_aes_128_cbc_sha256_tls;
}
const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls(void) {
const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls() {
return &aead_aes_256_cbc_sha1_tls;
}
const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls_implicit_iv(void) {
const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls_implicit_iv() {
return &aead_aes_256_cbc_sha1_tls_implicit_iv;
}
const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls(void) {
const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls() {
return &aead_des_ede3_cbc_sha1_tls;
}
const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls_implicit_iv(void) {
const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls_implicit_iv() {
return &aead_des_ede3_cbc_sha1_tls_implicit_iv;
}
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_cipher.h>
@@ -23,7 +28,7 @@
static const struct {
int nid;
const char *name;
const EVP_CIPHER *(*func)(void);
const EVP_CIPHER *(*func)();
} kCiphers[] = {
{NID_aes_128_cbc, "aes-128-cbc", EVP_aes_128_cbc},
{NID_aes_128_ctr, "aes-128-ctr", EVP_aes_128_ctr},
@@ -50,31 +55,31 @@ static const struct {
};
const EVP_CIPHER *EVP_get_cipherbynid(int nid) {
for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kCiphers); i++) {
if (kCiphers[i].nid == nid) {
return kCiphers[i].func();
for (const auto &cipher : kCiphers) {
if (cipher.nid == nid) {
return cipher.func();
}
}
return NULL;
return nullptr;
}
const EVP_CIPHER *EVP_get_cipherbyname(const char *name) {
if (name == NULL) {
return NULL;
if (name == nullptr) {
return nullptr;
}
// This is not a name used by OpenSSL, but tcpdump registers it with
// |EVP_add_cipher_alias|. Our |EVP_add_cipher_alias| is a no-op, so we
// `EVP_add_cipher_alias`. Our `EVP_add_cipher_alias` is a no-op, so we
// support the name here.
if (OPENSSL_strcasecmp(name, "3des") == 0) {
name = "des-ede3-cbc";
}
for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kCiphers); i++) {
if (OPENSSL_strcasecmp(kCiphers[i].name, name) == 0) {
return kCiphers[i].func();
for (const auto &cipher : kCiphers) {
if (OPENSSL_strcasecmp(cipher.name, name) == 0) {
return cipher.func();
}
}
return NULL;
return nullptr;
}
+237 -73
View File
@@ -1,45 +1,51 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSSL_HEADER_CIPHER_EXTRA_INTERNAL_H
#define OPENSSL_HEADER_CIPHER_EXTRA_INTERNAL_H
#ifndef OPENSSL_HEADER_CRYPTO_CIPHER_INTERNAL_H
#define OPENSSL_HEADER_CRYPTO_CIPHER_INTERNAL_H
#include <assert.h>
#include <stdlib.h>
#include <CNIOBoringSSL_aead.h>
#include <CNIOBoringSSL_base.h>
#include <CNIOBoringSSL_sha.h>
#include <CNIOBoringSSL_span.h>
#include "../internal.h"
#if defined(__cplusplus)
extern "C" {
#endif
BSSL_NAMESPACE_BEGIN
// EVP_tls_cbc_get_padding determines the padding from the decrypted, TLS, CBC
// record in |in|. This decrypted record should not include any "decrypted"
// record in `in`. This decrypted record should not include any "decrypted"
// explicit IV. If the record is publicly invalid, it returns zero. Otherwise,
// it returns one and sets |*out_padding_ok| to all ones (0xfff..f) if the
// padding is valid and zero otherwise. It then sets |*out_len| to the length
// with the padding removed or |in_len| if invalid.
// it returns one and sets `*out_padding_ok` to all ones (0xfff..f) if the
// padding is valid and zero otherwise. It then sets `*out_len` to the length
// with the padding removed or `in_len` if invalid.
//
// If the function returns one, it runs in time independent of the contents of
// |in|. It is also guaranteed that |*out_len| >= |mac_size|, satisfying
// |EVP_tls_cbc_copy_mac|'s precondition.
// `in`. It is also guaranteed that, independent of `*out_padding_ok`, `mac_len`
// <= `*out_len` <= `in_len`, satisfying `EVP_tls_cbc_copy_mac`'s precondition.
int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len,
const uint8_t *in, size_t in_len,
size_t block_size, size_t mac_size);
// EVP_tls_cbc_copy_mac copies |md_size| bytes from the end of the first
// |in_len| bytes of |in| to |out| in constant time (independent of the concrete
// value of |in_len|, which may vary within a 256-byte window). |in| must point
// to a buffer of |orig_len| bytes.
// EVP_tls_cbc_copy_mac copies `md_size` bytes from the end of the first
// `in_len` bytes of `in` to `out` in constant time (independent of the concrete
// value of `in_len`, which may vary within a 256-byte window). `in` must point
// to a buffer of `orig_len` bytes.
//
// On entry:
// orig_len >= in_len >= md_size
@@ -47,14 +53,14 @@ int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len,
void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in,
size_t in_len, size_t orig_len);
// EVP_tls_cbc_record_digest_supported returns 1 iff |md| is a hash function
// EVP_tls_cbc_record_digest_supported returns 1 iff `md` is a hash function
// which EVP_tls_cbc_digest_record supports.
int EVP_tls_cbc_record_digest_supported(const EVP_MD *md);
// EVP_sha1_final_with_secret_suffix computes the result of hashing |len| bytes
// from |in| to |ctx| and writes the resulting hash to |out|. |len| is treated
// as secret and must be at most |max_len|, which is treated as public. |in|
// must point to a buffer of at least |max_len| bytes. It returns one on success
// EVP_sha1_final_with_secret_suffix computes the result of hashing `len` bytes
// from `in` to `ctx` and writes the resulting hash to `out`. `len` is treated
// as secret and must be at most `max_len`, which is treated as public. `in`
// must point to a buffer of at least `max_len` bytes. It returns one on success
// and zero if inputs are too long.
//
// This function is exported for unit tests.
@@ -63,7 +69,7 @@ OPENSSL_EXPORT int EVP_sha1_final_with_secret_suffix(
size_t max_len);
// EVP_sha256_final_with_secret_suffix acts like
// |EVP_sha1_final_with_secret_suffix|, but for SHA-256.
// `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(
@@ -77,23 +83,29 @@ OPENSSL_EXPORT int EVP_sha256_final_with_secret_suffix(
// EVP_tls_cbc_record_digest_supported must return true for this hash.
// md_out: the digest output. At most EVP_MAX_MD_SIZE bytes will be written.
// md_out_size: the number of output bytes is written here.
// header: the 13-byte, TLS record header.
// data: the record data itself
// data_size: the secret, reported length of the data once the padding and MAC
// have been removed.
// data_plus_mac_plus_padding_size: the public length of the whole
// record, including padding.
// len_header: the two length bytes of the TLS record header.
// aadvecs: the 11-byte TLS record header as it was provided by the caller.
// iovecs_without_trailer: the section of the plaintext that does not include
// the trailer whose length is secret (typically the entire plaintext with
// an upper bound of padding and MAC size removed)
// trailer: a buffer, of public length, containing the remainder of the
// plaintext as a prefix.
// data_in_trailer_size: the secret, reported length of the data portion in
// `trailer` once the padding and MAC have been removed.
//
// On entry: by virtue of having been through one of the remove_padding
// functions, above, we know that data_plus_mac_size is large enough to contain
// a padding byte and MAC. (If the padding was invalid, it might contain the
// padding too. )
int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out,
size_t *md_out_size, const uint8_t header[13],
const uint8_t *data, size_t data_size,
size_t data_plus_mac_plus_padding_size,
const uint8_t *mac_secret,
unsigned mac_secret_length);
int EVP_tls_cbc_digest_record(
const EVP_MD *md, uint8_t *md_out, size_t *md_out_size,
const uint8_t len_header[2], bssl::Span<const CRYPTO_IVEC> aadvecs,
bssl::Span<const CRYPTO_IOVEC> iovecs_without_trailer,
bssl::Span<const uint8_t> trailer, size_t data_in_trailer_size,
const uint8_t *mac_secret, unsigned mac_secret_length);
// ChaCha20-Poly1305 Assembly.
#define POLY1305_TAG_LEN 16
@@ -124,7 +136,7 @@ union chacha20_poly1305_seal_data {
} out;
};
#if (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \
#if (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \
!defined(OPENSSL_NO_ASM)
static_assert(sizeof(union chacha20_poly1305_open_data) == 48,
@@ -132,7 +144,7 @@ static_assert(sizeof(union chacha20_poly1305_open_data) == 48,
static_assert(sizeof(union chacha20_poly1305_seal_data) == 48 + 8 + 8,
"wrong chacha20_poly1305_seal_data size");
inline int chacha20_poly1305_asm_capable(void) {
inline int chacha20_poly1305_asm_capable() {
#if defined(OPENSSL_X86_64)
return CRYPTO_is_SSE4_1_capable();
#elif defined(OPENSSL_AARCH64)
@@ -141,15 +153,15 @@ inline int chacha20_poly1305_asm_capable(void) {
}
// chacha20_poly1305_open is defined in chacha20_poly1305_*.pl. It decrypts
// |plaintext_len| bytes from |ciphertext| and writes them to |out_plaintext|.
// Additional input parameters are passed in |aead_data->in|. On exit, it will
// write calculated tag value to |aead_data->out.tag|, which the caller must
// `plaintext_len` bytes from `ciphertext` and writes them to `out_plaintext`.
// Additional input parameters are passed in `aead_data->in`. On exit, it will
// write calculated tag value to `aead_data->out.tag`, which the caller must
// check.
#if defined(OPENSSL_X86_64)
extern void chacha20_poly1305_open_nohw(
extern "C" void chacha20_poly1305_open_sse41(
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(
extern "C" 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);
inline void chacha20_poly1305_open(uint8_t *out_plaintext,
@@ -161,28 +173,28 @@ inline void chacha20_poly1305_open(uint8_t *out_plaintext,
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);
chacha20_poly1305_open_sse41(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);
extern "C" 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|.
// `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(
extern "C" void chacha20_poly1305_seal_sse41(
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(
extern "C" 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);
inline void chacha20_poly1305_seal(uint8_t *out_ciphertext,
@@ -194,21 +206,21 @@ inline void chacha20_poly1305_seal(uint8_t *out_ciphertext,
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);
chacha20_poly1305_seal_sse41(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);
extern "C" 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
inline int chacha20_poly1305_asm_capable(void) { return 0; }
inline int chacha20_poly1305_asm_capable() { return 0; }
inline void chacha20_poly1305_open(uint8_t *out_plaintext,
const uint8_t *ciphertext,
@@ -228,8 +240,160 @@ inline void chacha20_poly1305_seal(uint8_t *out_ciphertext,
#endif
#if defined(__cplusplus)
} // extern C
#endif
// AES-GCM-SIV Assembly.
#endif // OPENSSL_HEADER_CIPHER_EXTRA_INTERNAL_H
// TODO(davidben): AES-GCM-SIV assembly is not correct for Windows. It must save
// and restore xmm6 through xmm15.
#if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) && \
!defined(OPENSSL_WINDOWS)
#define AES_GCM_SIV_ASM
struct aead_aes_gcm_siv_asm_ctx {
alignas(16) uint8_t key[16 * 15];
int is_128_bit;
};
inline int aes_gcm_siv_asm_capable() {
return CRYPTO_is_AVX_capable() && CRYPTO_is_AESNI_capable() &&
CRYPTO_is_PCLMUL_capable();
}
extern "C" {
// aes128gcmsiv_aes_ks writes an AES-128 key schedule for `key` to
// `out_expanded_key`. `out_expanded_key` must be 16-byte aligned.
extern void aes128gcmsiv_aes_ks(const uint8_t key[16],
uint8_t out_expanded_key[16 * 15]);
// aes256gcmsiv_aes_ks writes an AES-256 key schedule for `key` to
// `out_expanded_key`. `out_expanded_key` must be 16-byte aligned.
extern void aes256gcmsiv_aes_ks(const uint8_t key[32],
uint8_t out_expanded_key[16 * 15]);
// aesgcmsiv_polyval_horner updates the POLYVAL value in `in_out_poly` to
// include a number (`in_blocks`) of 16-byte blocks of data from `in`, given
// the POLYVAL key in `key`. `in_out_poly` and `key` must be 16-byte aligned.
extern void aesgcmsiv_polyval_horner(const uint8_t in_out_poly[16],
const uint8_t key[16], const uint8_t *in,
size_t in_blocks);
// aesgcmsiv_htable_init writes powers 1..8 of `auth_key` to `out_htable`.
// `out_htable` and `auth_key` must be 16-byte aligned.
extern void aesgcmsiv_htable_init(uint8_t out_htable[16 * 8],
const uint8_t auth_key[16]);
// aesgcmsiv_htable6_init writes powers 1..6 of `auth_key` to `out_htable`.
// `out_htable` and `auth_key` must be 16-byte aligned.
extern void aesgcmsiv_htable6_init(uint8_t out_htable[16 * 6],
const uint8_t auth_key[16]);
// aesgcmsiv_htable_polyval updates the POLYVAL value in `in_out_poly` to
// include `in_len` bytes of data from `in`. (Where `in_len` must be a multiple
// of 16.) It uses the precomputed powers of the key given in `htable`.
// `in_out_poly` and `htable` must be 16-byte aligned.
extern void aesgcmsiv_htable_polyval(const uint8_t htable[16 * 8],
const uint8_t *in, size_t in_len,
uint8_t in_out_poly[16]);
// aes128gcmsiv_dec decrypts `in_len` & ~15 bytes from `out` and writes them to
// `in`. `in` and `out` may be equal, but must not otherwise alias.
//
// `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, the whole of `in_out_calculated_tag_and_scratch` may be
// used for other purposes. `in_out_calculated_tag_and_scratch` and `htable`
// must be 16-byte aligned. 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],
const struct aead_aes_gcm_siv_asm_ctx *key,
size_t in_len);
// aes256gcmsiv_dec acts like `aes128gcmsiv_dec`, but for AES-256.
// `in_out_calculated_tag_and_scratch` and `htable` must be 16-byte aligned.
extern void aes256gcmsiv_dec(const uint8_t *in, uint8_t *out,
uint8_t in_out_calculated_tag_and_scratch[16 * 8],
const uint8_t htable[16 * 6],
const struct aead_aes_gcm_siv_asm_ctx *key,
size_t in_len);
// aes128gcmsiv_kdf performs the AES-GCM-SIV KDF given the expanded key from
// `key_schedule` and the nonce in `nonce`. Note that, while only 12 bytes of
// the nonce are used, 16 bytes are read and so the value must be
// right-padded. `nonce`, `out_key_material`, and `key_schedule` must be
// 16-byte aligned.
extern void aes128gcmsiv_kdf(const uint8_t nonce[16],
uint64_t out_key_material[8],
const uint8_t *key_schedule);
// aes256gcmsiv_kdf acts like `aes128gcmsiv_kdf`, but for AES-256. `nonce`,
// `out_key_material`, and `key_schedule` must be 16-byte aligned.
extern void aes256gcmsiv_kdf(const uint8_t nonce[16],
uint64_t out_key_material[12],
const uint8_t *key_schedule);
// aes128gcmsiv_aes_ks_enc_x1 performs a key expansion of the AES-128 key in
// `key`, writes the expanded key to `out_expanded_key` and encrypts a single
// block from `in` to `out`. `in`, `out`, `out_expanded_key`, and `key` must be
// 16-byte aligned.
extern void aes128gcmsiv_aes_ks_enc_x1(const uint8_t in[16], uint8_t out[16],
uint8_t out_expanded_key[16 * 15],
const uint64_t key[2]);
// aes256gcmsiv_aes_ks_enc_x1 acts like `aes128gcmsiv_aes_ks_enc_x1`, but for
// AES-256. `in`, `out`, `out_expanded_key`, and `key` must be 16-byte aligned.
extern void aes256gcmsiv_aes_ks_enc_x1(const uint8_t in[16], uint8_t out[16],
uint8_t out_expanded_key[16 * 15],
const uint64_t key[4]);
// aes128gcmsiv_ecb_enc_block encrypts a single block from `in` to `out` using
// the expanded key in `expanded_key`. `in` and `out` must be 16-byte aligned.
extern void aes128gcmsiv_ecb_enc_block(
const uint8_t in[16], uint8_t out[16],
const struct aead_aes_gcm_siv_asm_ctx *expanded_key);
// aes256gcmsiv_ecb_enc_block acts like `aes128gcmsiv_ecb_enc_block`, but for
// AES-256. `in` and `out` must be 16-byte aligned.
extern void aes256gcmsiv_ecb_enc_block(
const uint8_t in[16], uint8_t out[16],
const struct aead_aes_gcm_siv_asm_ctx *expanded_key);
// aes128gcmsiv_enc_msg_x4 encrypts `in_len` bytes from `in` to `out` using the
// expanded key from `key`. (The value of `in_len` must be a multiple of 16.)
// The `in` and `out` buffers may be equal but must not otherwise overlap. The
// initial counter is constructed from the given `tag` as required by
// AES-GCM-SIV. `tag` must be 16-byte aligned.
extern void aes128gcmsiv_enc_msg_x4(const uint8_t *in, uint8_t *out,
const uint8_t *tag,
const struct aead_aes_gcm_siv_asm_ctx *key,
size_t in_len);
// aes256gcmsiv_enc_msg_x4 acts like `aes128gcmsiv_enc_msg_x4`, but for
// AES-256. `tag` must be 16-byte aligned.
extern void aes256gcmsiv_enc_msg_x4(const uint8_t *in, uint8_t *out,
const uint8_t *tag,
const struct aead_aes_gcm_siv_asm_ctx *key,
size_t in_len);
// aes128gcmsiv_enc_msg_x8 acts like `aes128gcmsiv_enc_msg_x4`, but is
// optimised for longer messages.
extern void aes128gcmsiv_enc_msg_x8(const uint8_t *in, uint8_t *out,
const uint8_t *tag,
const struct aead_aes_gcm_siv_asm_ctx *key,
size_t in_len);
// aes256gcmsiv_enc_msg_x8 acts like `aes256gcmsiv_enc_msg_x4`, but is
// optimised for longer messages.
extern void aes256gcmsiv_enc_msg_x8(const uint8_t *in, uint8_t *out,
const uint8_t *tag,
const struct aead_aes_gcm_siv_asm_ctx *key,
size_t in_len);
}
#endif // OPENSSL_X86_64 && !OPENSSL_NO_ASM && !OPENSSL_WINDOWS
BSSL_NAMESPACE_END
#endif // OPENSSL_HEADER_CRYPTO_CIPHER_INTERNAL_H
+124 -119
View File
@@ -1,11 +1,16 @@
/*
* Copyright 2012-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 2012-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <assert.h>
#include <string.h>
@@ -13,15 +18,19 @@
#include <CNIOBoringSSL_digest.h>
#include <CNIOBoringSSL_nid.h>
#include <CNIOBoringSSL_sha.h>
#include <CNIOBoringSSL_span.h>
#include "../fipsmodule/cipher/internal.h"
#include "../internal.h"
#include "internal.h"
#include "../fipsmodule/cipher/internal.h"
int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len,
const uint8_t *in, size_t in_len,
size_t block_size, size_t mac_size) {
using namespace bssl;
int bssl::EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok,
size_t *out_len, const uint8_t *in,
size_t in_len, size_t block_size,
size_t mac_size) {
const size_t overhead = 1 /* padding length byte */ + mac_size;
// These lengths are all public so we can test them in non-constant time.
@@ -37,7 +46,7 @@ int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len,
// length byte. Thus, with the length byte included, there are i+1
// bytes of padding.
//
// We can't check just |padding_length+1| bytes because that leaks
// We can't check just `padding_length+1` bytes because that leaks
// decrypted information. Therefore we always have to check the maximum
// amount of padding possible. (Again, the length of the record is
// public information so we can use it.)
@@ -48,18 +57,21 @@ int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len,
for (size_t i = 0; i < to_check; i++) {
uint8_t mask = constant_time_ge_8(padding_length, i);
uint8_t b = in[in_len - 1 - i];
// The final |padding_length+1| bytes should all have the value
// |padding_length|. Therefore the XOR should be zero.
// The value barrier on `(in_len - 1 - i)` isn't needed to enforce
// constant-time. It is just there to prevent a false positive in
// constant-time checks by valgrind.
uint8_t b = in[value_barrier_w(in_len - 1 - i)];
// The final `padding_length+1` bytes should all have the value
// `padding_length`. Therefore the XOR should be zero.
good &= ~(mask & (padding_length ^ b));
}
// If any of the final |padding_length+1| bytes had the wrong value,
// one or more of the lower eight bits of |good| will be cleared.
// If any of the final `padding_length+1` bytes had the wrong value,
// one or more of the lower eight bits of `good` will be cleared.
good = constant_time_eq_w(0xff, good & 0xff);
// Always treat |padding_length| as zero on error. If, assuming block size of
// 16, a padding of [<15 arbitrary bytes> 15] treated |padding_length| as 16
// Always treat `padding_length` as zero on error. If, assuming block size of
// 16, a padding of [<15 arbitrary bytes> 15] treated `padding_length` as 16
// and returned -1, distinguishing good MAC and bad padding from bad MAC and
// bad padding would give POODLE's padding oracle.
padding_length = good & (padding_length + 1);
@@ -68,13 +80,13 @@ int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len,
return 1;
}
void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in,
size_t in_len, size_t orig_len) {
void bssl::EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in,
size_t in_len, size_t orig_len) {
uint8_t rotated_mac1[EVP_MAX_MD_SIZE], rotated_mac2[EVP_MAX_MD_SIZE];
uint8_t *rotated_mac = rotated_mac1;
uint8_t *rotated_mac_tmp = rotated_mac2;
// mac_end is the index of |in| just after the end of the MAC.
// mac_end is the index of `in` just after the end of the MAC.
size_t mac_end = in_len;
size_t mac_start = mac_end - md_size;
@@ -102,15 +114,15 @@ void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in,
mac_started |= is_mac_start;
uint8_t mac_ended = constant_time_ge_8(i, mac_end);
rotated_mac[j] |= in[i] & mac_started & ~mac_ended;
// Save the offset that |mac_start| is mapped to.
// Save the offset that `mac_start` is mapped to.
rotate_offset |= j & is_mac_start;
}
// Now rotate the MAC. We rotate in log(md_size) steps, one for each bit
// position.
for (size_t offset = 1; offset < md_size; offset <<= 1, rotate_offset >>= 1) {
// Rotate by |offset| iff the corresponding bit is set in
// |rotate_offset|, placing the result in |rotated_mac_tmp|.
// Rotate by `offset` iff the corresponding bit is set in
// `rotate_offset`, placing the result in `rotated_mac_tmp`.
const uint8_t skip_rotate = (rotate_offset & 1) - 1;
for (size_t i = 0, j = offset; i < md_size; i++, j++) {
if (j >= md_size) {
@@ -120,7 +132,7 @@ void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in,
constant_time_select_8(skip_rotate, rotated_mac[i], rotated_mac[j]);
}
// Swap pointers so |rotated_mac| contains the (possibly) rotated value.
// Swap pointers so `rotated_mac` contains the (possibly) rotated value.
// Note the number of iterations and thus the identity of these pointers is
// public information.
uint8_t *tmp = rotated_mac;
@@ -131,12 +143,12 @@ void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in,
OPENSSL_memcpy(out, rotated_mac, md_size);
}
int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx,
uint8_t out[SHA_DIGEST_LENGTH],
const uint8_t *in, size_t len,
size_t max_len) {
// Bound the input length so |total_bits| below fits in four bytes. This is
// redundant with TLS record size limits. This also ensures |input_idx| below
int bssl::EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx,
uint8_t out[SHA_DIGEST_LENGTH],
const uint8_t *in, size_t len,
size_t max_len) {
// Bound the input length so `total_bits` below fits in four bytes. This is
// redundant with TLS record size limits. This also ensures `input_idx` below
// does not overflow.
size_t max_len_bits = max_len << 3;
if (ctx->Nh != 0 ||
@@ -146,7 +158,7 @@ int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx,
return 0;
}
// We need to hash the following into |ctx|:
// We need to hash the following into `ctx`:
//
// - ctx->data[:ctx->num]
// - in[:len]
@@ -157,24 +169,21 @@ int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx,
size_t last_block = num_blocks - 1;
size_t max_blocks = (ctx->num + max_len + 1 + 8 + SHA_CBLOCK - 1) >> 6;
// The bounds above imply |total_bits| fits in four bytes.
// 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;
CRYPTO_store_u32_be(length_bytes, total_bits);
// We now construct and process each expected block in constant-time.
uint8_t block[SHA_CBLOCK] = {0};
uint32_t result[5] = {0};
// input_idx is the index into |in| corresponding to the current block.
// However, we allow this index to overflow beyond |max_len|, to simplify the
// 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.
// 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);
@@ -188,12 +197,12 @@ int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx,
OPENSSL_memcpy(block + block_start, in + input_idx, to_copy);
}
// Zero any bytes beyond |len| and add the 0x80 byte.
// Zero any bytes beyond `len` and add the 0x80 byte.
for (size_t j = block_start; j < SHA_CBLOCK; j++) {
// input[idx] corresponds to block[j].
size_t idx = input_idx + j - block_start;
// The barriers on |len| are not strictly necessary. However, without
// them, GCC compiles this code by incorporating |len| into the loop
// 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));
@@ -204,8 +213,10 @@ int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx,
input_idx += SHA_CBLOCK - block_start;
// Fill in the length if this is the last block.
crypto_word_t is_last_block = constant_time_eq_w(i, last_block);
// Fill in the length if this is the last block. Use a value barrier to
// prevent Clang from compiling the conditional select as a jump.
crypto_word_t is_last_block =
value_barrier_w(constant_time_eq_w(i, last_block));
for (size_t j = 0; j < 4; j++) {
block[SHA_CBLOCK - 4 + j] |= is_last_block & length_bytes[j];
}
@@ -224,12 +235,12 @@ int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx,
return 1;
}
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
int bssl::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 ||
@@ -239,7 +250,7 @@ int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx,
return 0;
}
// We need to hash the following into |ctx|:
// We need to hash the following into `ctx`:
//
// - ctx->data[:ctx->num]
// - in[:len]
@@ -250,24 +261,21 @@ int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx,
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.
// 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;
CRYPTO_store_u32_be(length_bytes, 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
// 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.
// 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);
@@ -281,12 +289,12 @@ int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx,
OPENSSL_memcpy(block + block_start, in + input_idx, to_copy);
}
// Zero any bytes beyond |len| and add the 0x80 byte.
// 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
// 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));
@@ -297,8 +305,10 @@ int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx,
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);
// Fill in the length if this is the last block. Use a value barrier to
// prevent Clang from compiling the conditional select as a jump.
crypto_word_t is_last_block =
value_barrier_w(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];
}
@@ -317,7 +327,7 @@ int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx,
return 1;
}
int EVP_tls_cbc_record_digest_supported(const EVP_MD *md) {
int bssl::EVP_tls_cbc_record_digest_supported(const EVP_MD *md) {
switch (EVP_MD_type(md)) {
case NID_sha1:
case NID_sha256:
@@ -327,12 +337,12 @@ int EVP_tls_cbc_record_digest_supported(const EVP_MD *md) {
}
}
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) {
static int tls_cbc_digest_record_sha1(
uint8_t *md_out, size_t *md_out_size, const uint8_t len_header[2],
Span<const CRYPTO_IVEC> aadvecs,
Span<const CRYPTO_IOVEC> iovecs_without_trailer,
Span<const uint8_t> trailer, size_t data_in_trailer_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.
@@ -351,24 +361,22 @@ static int tls_cbc_digest_record_sha1(uint8_t *md_out, size_t *md_out_size,
SHA_CTX ctx;
SHA1_Init(&ctx);
SHA1_Update(&ctx, hmac_pad, SHA_CBLOCK);
SHA1_Update(&ctx, header, 13);
// There are at most 256 bytes of padding, so we can compute the public
// minimum length for |data_size|.
size_t min_data_size = 0;
if (data_plus_mac_plus_padding_size > SHA_DIGEST_LENGTH + 256) {
min_data_size = data_plus_mac_plus_padding_size - SHA_DIGEST_LENGTH - 256;
for (const CRYPTO_IVEC &aadvec : aadvecs) {
SHA1_Update(&ctx, aadvec.in, aadvec.len);
}
SHA1_Update(&ctx, len_header, 2);
// Hash the public minimum length directly. This reduces the number of blocks
// that must be computed in constant-time.
SHA1_Update(&ctx, data, min_data_size);
for (const CRYPTO_IOVEC &iovec : iovecs_without_trailer) {
SHA1_Update(&ctx, iovec.out, iovec.len);
}
// Hash the remaining data without leaking |data_size|.
// Hash the remaining data without leaking `data_in_trailer_size`.
uint8_t mac_out[SHA_DIGEST_LENGTH];
if (!EVP_sha1_final_with_secret_suffix(
&ctx, mac_out, data + min_data_size, data_size - min_data_size,
data_plus_mac_plus_padding_size - min_data_size)) {
if (!EVP_sha1_final_with_secret_suffix(&ctx, mac_out, trailer.data(),
data_in_trailer_size,
trailer.size())) {
return 0;
}
@@ -385,12 +393,12 @@ static int tls_cbc_digest_record_sha1(uint8_t *md_out, size_t *md_out_size,
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) {
static int tls_cbc_digest_record_sha256(
uint8_t *md_out, size_t *md_out_size, const uint8_t len_header[2],
Span<const CRYPTO_IVEC> aadvecs,
Span<const CRYPTO_IOVEC> iovecs_without_trailer,
Span<const uint8_t> trailer, size_t data_in_trailer_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.
@@ -409,25 +417,22 @@ static int tls_cbc_digest_record_sha256(uint8_t *md_out, size_t *md_out_size,
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;
for (const CRYPTO_IVEC &aadvec : aadvecs) {
SHA256_Update(&ctx, aadvec.in, aadvec.len);
}
SHA256_Update(&ctx, len_header, 2);
// 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);
for (const CRYPTO_IOVEC &iovec : iovecs_without_trailer) {
SHA256_Update(&ctx, iovec.out, iovec.len);
}
// Hash the remaining data without leaking |data_size|.
// Hash the remaining data without leaking `data_in_trailer_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)) {
if (!EVP_sha256_final_with_secret_suffix(&ctx, mac_out, trailer.data(),
data_in_trailer_size,
trailer.size())) {
return 0;
}
@@ -444,22 +449,22 @@ static int tls_cbc_digest_record_sha256(uint8_t *md_out, size_t *md_out_size,
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) {
int bssl::EVP_tls_cbc_digest_record(
const EVP_MD *md, uint8_t *md_out, size_t *md_out_size,
const uint8_t len_header[2], Span<const CRYPTO_IVEC> aadvecs,
Span<const CRYPTO_IOVEC> iovecs_without_trailer,
Span<const uint8_t> trailer, size_t data_in_trailer_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);
return tls_cbc_digest_record_sha1( //
md_out, md_out_size, len_header, aadvecs, iovecs_without_trailer,
trailer, data_in_trailer_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);
return tls_cbc_digest_record_sha256( //
md_out, md_out_size, len_header, aadvecs, iovecs_without_trailer,
trailer, data_in_trailer_size, mac_secret, mac_secret_length);
default:
// EVP_tls_cbc_record_digest_supported should have been called first to
+178
View File
@@ -0,0 +1,178 @@
// Copyright 2025 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_cms.h>
#include <CNIOBoringSSL_bio.h>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_evp.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_x509.h>
#include "../bytestring/internal.h"
#include "../internal.h"
#include "../mem_internal.h"
#include "../pkcs7/internal.h"
using namespace bssl;
// TODO(davidben): Should we move the core PKCS#7 / CMS implementation into
// crypto/cms instead of crypto/pkcs7? CMS is getting new features while PKCS#7
// is not.
OPENSSL_DECLARE_ERROR_REASON(CMS, CERTIFICATE_HAS_NO_KEYID)
DECLARE_OPAQUE_STRUCT(CMS_SignerInfo_st, CMSSignerInfo)
DECLARE_OPAQUE_STRUCT(CMS_ContentInfo_st, CMSContentInfo)
BSSL_NAMESPACE_BEGIN
class CMSSignerInfo : public CMS_SignerInfo_st {
public:
UniquePtr<X509> signcert;
UniquePtr<EVP_PKEY> pkey;
const EVP_MD *md = nullptr;
bool use_key_id = false;
};
class CMSContentInfo : public CMS_ContentInfo_st {
public:
static constexpr bool kAllowUniquePtr = true;
bool has_signer_info = false;
CMSSignerInfo signer_info;
Array<uint8_t> der;
};
BSSL_NAMESPACE_END
CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
BIO *data, uint32_t flags) {
// We only support external signatures and do not support embedding
// certificates in SignedData.
if ((flags & CMS_DETACHED) == 0 || sk_X509_num(certs) != 0) {
OPENSSL_PUT_ERROR(CMS, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return nullptr;
}
UniquePtr<CMSContentInfo> cms = MakeUnique<CMSContentInfo>();
if (cms == nullptr) {
return nullptr;
}
if (pkey != nullptr &&
!CMS_add1_signer(cms.get(), signcert, pkey, /*md=*/nullptr, flags)) {
return nullptr;
}
// We don't actually use streaming mode, but Linux passes `CMS_STREAM` to
// `CMS_sign` and OpenSSL interprets it as an alias for `CMS_PARTIAL` in this
// context.
if ((flags & (CMS_PARTIAL | CMS_STREAM)) == 0 &&
!CMS_final(cms.get(), data, nullptr, flags)) {
return nullptr;
}
return cms.release();
}
void CMS_ContentInfo_free(CMS_ContentInfo *cms) { Delete(FromOpaque(cms)); }
CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, X509 *signcert,
EVP_PKEY *pkey, const EVP_MD *md,
uint32_t flags) {
auto *impl = FromOpaque(cms);
if ( // Already finalized.
!impl->der.empty() ||
// We only support one signer.
impl->has_signer_info ||
// We do not support embedding certificates in SignedData.
(flags & CMS_NOCERTS) == 0 ||
// We do not support attributes in SignedData.
(flags & CMS_NOATTR) == 0) {
OPENSSL_PUT_ERROR(CMS, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return nullptr;
}
if (signcert == nullptr || pkey == nullptr) {
OPENSSL_PUT_ERROR(CMS, ERR_R_PASSED_NULL_PARAMETER);
return nullptr;
}
if (!X509_check_private_key(signcert, pkey)) {
OPENSSL_PUT_ERROR(CMS, CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
return nullptr;
}
// Default to SHA-256.
if (md == nullptr) {
md = EVP_sha256();
}
// Save information for later.
impl->has_signer_info = true;
impl->signer_info.signcert = UpRef(signcert);
impl->signer_info.pkey = UpRef(pkey);
impl->signer_info.md = md;
impl->signer_info.use_key_id = (flags & CMS_USE_KEYID) != 0;
return &impl->signer_info;
}
int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, uint32_t flags) {
auto *impl = FromOpaque(cms);
if ( // Already finalized.
!impl->der.empty() ||
// Require a SignerInfo. We do not support signature-less SignedDatas.
!impl->has_signer_info ||
// We only support the straightforward passthrough mode, without S/MIME
// translations.
(flags & CMS_BINARY) == 0 ||
// We do not support `dcont`. It is unclear what it does.
dcont != nullptr) {
OPENSSL_PUT_ERROR(CMS, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
ScopedCBB cbb;
if (!CBB_init(cbb.get(), 2048) ||
!pkcs7_add_external_signature(cbb.get(), impl->signer_info.signcert.get(),
impl->signer_info.pkey.get(),
impl->signer_info.md, data,
impl->signer_info.use_key_id) ||
!CBBFinishArray(cbb.get(), &impl->der)) {
return 0;
}
return 1;
}
int i2d_CMS_bio(BIO *out, CMS_ContentInfo *cms) {
auto *impl = FromOpaque(cms);
if (impl->der.empty()) {
// Not yet finalized.
OPENSSL_PUT_ERROR(CMS, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
return BIO_write_all(out, impl->der.data(), impl->der.size());
}
int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags) {
// We do not support streaming mode.
if ((flags & CMS_STREAM) != 0 || in != nullptr) {
OPENSSL_PUT_ERROR(CMS, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
return i2d_CMS_bio(out, cms);
}
+82 -71
View File
@@ -1,11 +1,16 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_conf.h>
@@ -16,19 +21,25 @@
#include <CNIOBoringSSL_bio.h>
#include <CNIOBoringSSL_buf.h>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_lhash.h>
#include <CNIOBoringSSL_mem.h>
#include "../internal.h"
#include "../mem_internal.h"
#include "internal.h"
using namespace bssl;
BSSL_NAMESPACE_BEGIN
struct conf_section_st {
char *name;
// values contains non-owning pointers to the values in the section.
STACK_OF(CONF_VALUE) *values;
};
BSSL_NAMESPACE_END
static const char kDefaultSectionName[] = "default";
static uint32_t conf_section_hash(const CONF_SECTION *s) {
@@ -55,46 +66,44 @@ static int conf_value_cmp(const CONF_VALUE *a, const CONF_VALUE *b) {
}
CONF *NCONF_new(void *method) {
if (method != NULL) {
return NULL;
if (method != nullptr) {
return nullptr;
}
CONF *conf = reinterpret_cast<CONF *>(OPENSSL_malloc(sizeof(CONF)));
if (conf == NULL) {
return NULL;
CONF *conf = New<CONF>();
if (conf == nullptr) {
return nullptr;
}
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) {
if (conf->sections == nullptr || conf->values == nullptr) {
NCONF_free(conf);
return NULL;
return nullptr;
}
return conf;
}
CONF_VALUE *CONF_VALUE_new(void) {
return reinterpret_cast<CONF_VALUE *>(OPENSSL_zalloc(sizeof(CONF_VALUE)));
}
CONF_VALUE *bssl::CONF_VALUE_new() { return New<CONF_VALUE>(); }
static void value_free(CONF_VALUE *value) {
if (value == NULL) {
if (value == nullptr) {
return;
}
OPENSSL_free(value->section);
OPENSSL_free(value->name);
OPENSSL_free(value->value);
OPENSSL_free(value);
Delete(value);
}
static void section_free(CONF_SECTION *section) {
if (section == NULL) {
if (section == nullptr) {
return;
}
OPENSSL_free(section->name);
sk_CONF_VALUE_free(section->values);
OPENSSL_free(section);
Delete(section);
}
static void value_free_arg(CONF_VALUE *value, void *arg) { value_free(value); }
@@ -104,26 +113,25 @@ static void section_free_arg(CONF_SECTION *section, void *arg) {
}
void NCONF_free(CONF *conf) {
if (conf == NULL) {
if (conf == nullptr) {
return;
}
lh_CONF_SECTION_doall_arg(conf->sections, section_free_arg, NULL);
lh_CONF_SECTION_doall_arg(conf->sections, section_free_arg, nullptr);
lh_CONF_SECTION_free(conf->sections);
lh_CONF_VALUE_doall_arg(conf->values, value_free_arg, NULL);
lh_CONF_VALUE_doall_arg(conf->values, value_free_arg, nullptr);
lh_CONF_VALUE_free(conf->values);
OPENSSL_free(conf);
Delete(conf);
}
static CONF_SECTION *NCONF_new_section(const CONF *conf, const char *section) {
CONF_SECTION *s =
reinterpret_cast<CONF_SECTION *>(OPENSSL_malloc(sizeof(CONF_SECTION)));
CONF_SECTION *s = New<CONF_SECTION>();
if (!s) {
return NULL;
return nullptr;
}
s->name = OPENSSL_strdup(section);
s->values = sk_CONF_VALUE_new_null();
if (s->name == NULL || s->values == NULL) {
if (s->name == nullptr || s->values == nullptr) {
goto err;
}
@@ -136,7 +144,7 @@ static CONF_SECTION *NCONF_new_section(const CONF *conf, const char *section) {
err:
section_free(s);
return NULL;
return nullptr;
}
static int is_comment(char c) { return c == '#'; }
@@ -146,7 +154,7 @@ 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
// This differs from `OPENSSL_isspace` in that CONF does not accept '\v' and
// '\f' as whitespace.
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
@@ -165,7 +173,7 @@ static int str_copy(CONF *conf, char *section, char **pto, char *from) {
BUF_MEM *buf;
buf = BUF_MEM_new();
if (buf == NULL) {
if (buf == nullptr) {
return 0;
}
@@ -240,8 +248,8 @@ static CONF_SECTION *get_section(const CONF *conf, const char *section) {
const STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf,
const char *section) {
const CONF_SECTION *section_obj = get_section(conf, section);
if (section_obj == NULL) {
return NULL;
if (section_obj == nullptr) {
return nullptr;
}
return section_obj->values;
}
@@ -250,7 +258,7 @@ const char *NCONF_get_string(const CONF *conf, const char *section,
const char *name) {
CONF_VALUE templ, *value;
if (section == NULL) {
if (section == nullptr) {
section = kDefaultSectionName;
}
@@ -258,8 +266,8 @@ const char *NCONF_get_string(const CONF *conf, const char *section,
templ.section = (char *)section;
templ.name = (char *)name;
value = lh_CONF_VALUE_retrieve(conf->values, &templ);
if (value == NULL) {
return NULL;
if (value == nullptr) {
return nullptr;
}
return value->value;
}
@@ -267,7 +275,7 @@ const char *NCONF_get_string(const CONF *conf, const char *section,
static int add_string(const CONF *conf, CONF_SECTION *section,
CONF_VALUE *value) {
value->section = OPENSSL_strdup(section->name);
if (value->section == NULL) {
if (value->section == nullptr) {
return 0;
}
@@ -277,12 +285,12 @@ static int add_string(const CONF *conf, CONF_SECTION *section,
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
// 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) {
if (old_value != nullptr) {
(void)sk_CONF_VALUE_delete_ptr(section->values, old_value);
value_free(old_value);
}
@@ -366,27 +374,27 @@ static void clear_comments(char *p) {
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;
BUF_MEM *buff = nullptr;
char *s, *p, *end;
int again;
long eline = 0;
CONF_VALUE *v = NULL;
CONF_SECTION *sv = NULL;
char *section = NULL, *buf;
CONF_VALUE *v = nullptr;
CONF_SECTION *sv = nullptr;
char *section = nullptr, *buf;
char *start, *psection, *pname;
if ((buff = BUF_MEM_new()) == NULL) {
if ((buff = BUF_MEM_new()) == nullptr) {
OPENSSL_PUT_ERROR(CONF, ERR_R_BUF_LIB);
goto err;
}
section = OPENSSL_strdup(kDefaultSectionName);
if (section == NULL) {
if (section == nullptr) {
goto err;
}
sv = NCONF_new_section(conf, section);
if (sv == NULL) {
if (sv == nullptr) {
OPENSSL_PUT_ERROR(CONF, CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
goto err;
}
@@ -428,7 +436,7 @@ int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) {
// i is the number of bytes
bufnum += i;
v = NULL;
v = nullptr;
// check for line continuation
if (bufnum >= 1) {
// If we have bytes and the last char '\\' and
@@ -468,20 +476,20 @@ int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) {
goto err;
}
*end = '\0';
if (!str_copy(conf, NULL, &section, start)) {
if (!str_copy(conf, nullptr, &section, start)) {
goto err;
}
if ((sv = get_section(conf, section)) == NULL) {
if ((sv = get_section(conf, section)) == nullptr) {
sv = NCONF_new_section(conf, section);
}
if (sv == NULL) {
if (sv == nullptr) {
OPENSSL_PUT_ERROR(CONF, CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
goto err;
}
continue;
} else {
pname = s;
psection = NULL;
psection = nullptr;
end = eat_name(s);
if ((end[0] == ':') && (end[1] == ':')) {
*end = '\0';
@@ -511,11 +519,11 @@ int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) {
if (!(v = CONF_VALUE_new())) {
goto err;
}
if (psection == NULL) {
if (psection == nullptr) {
psection = section;
}
v->name = OPENSSL_strdup(pname);
if (v->name == NULL) {
if (v->name == nullptr) {
goto err;
}
if (!str_copy(conf, psection, &(v->value), start)) {
@@ -524,10 +532,10 @@ int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) {
CONF_SECTION *tv;
if (strcmp(psection, section) != 0) {
if ((tv = get_section(conf, psection)) == NULL) {
if ((tv = get_section(conf, psection)) == nullptr) {
tv = NCONF_new_section(conf, psection);
}
if (tv == NULL) {
if (tv == nullptr) {
OPENSSL_PUT_ERROR(CONF, CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
goto err;
}
@@ -537,17 +545,17 @@ int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) {
if (add_string(conf, tv, v) == 0) {
goto err;
}
v = NULL;
v = nullptr;
}
}
BUF_MEM_free(buff);
OPENSSL_free(section);
Delete(section);
return 1;
err:
BUF_MEM_free(buff);
OPENSSL_free(section);
if (out_error_line != NULL) {
Delete(section);
if (out_error_line != nullptr) {
*out_error_line = eline;
}
ERR_add_error_dataf("line %ld", eline);
@@ -559,7 +567,7 @@ int NCONF_load(CONF *conf, const char *filename, long *out_error_line) {
BIO *in = BIO_new_file(filename, "rb");
int ret;
if (in == NULL) {
if (in == nullptr) {
OPENSSL_PUT_ERROR(CONF, ERR_R_SYS_LIB);
return 0;
}
@@ -570,13 +578,14 @@ int NCONF_load(CONF *conf, const char *filename, long *out_error_line) {
return ret;
}
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) {
int bssl::CONF_parse_list(const char *list, char sep, int remove_whitespace,
int (*list_cb)(const char *elem, size_t len,
void *usr),
void *arg) {
int ret;
const char *lstart, *tmpend, *p;
if (list == NULL) {
if (list == nullptr) {
OPENSSL_PUT_ERROR(CONF, CONF_R_LIST_CANNOT_BE_NULL);
return 0;
}
@@ -590,7 +599,7 @@ int CONF_parse_list(const char *list, char sep, int remove_whitespace,
}
p = strchr(lstart, sep);
if (p == lstart || !*lstart) {
ret = list_cb(NULL, 0, arg);
ret = list_cb(nullptr, 0, arg);
} else {
if (p) {
tmpend = p - 1;
@@ -607,7 +616,7 @@ int CONF_parse_list(const char *list, char sep, int remove_whitespace,
if (ret <= 0) {
return ret;
}
if (p == NULL) {
if (p == nullptr) {
return 1;
}
lstart = p + 1;
@@ -619,8 +628,10 @@ int CONF_modules_load_file(const char *filename, const char *appname,
return 1;
}
void CONF_modules_free(void) {}
void CONF_modules_unload(int all) {}
void CONF_modules_free() {}
void OPENSSL_config(const char *config_name) {}
void OPENSSL_no_config(void) {}
void OPENSSL_no_config() {}
+24 -25
View File
@@ -1,16 +1,16 @@
/* Copyright 2015 The BoringSSL Authors
*
* 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. */
// Copyright 2015 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSSL_HEADER_CRYPTO_CONF_INTERNAL_H
#define OPENSSL_HEADER_CRYPTO_CONF_INTERNAL_H
@@ -19,37 +19,36 @@
#include "../lhash/internal.h"
#if defined(__cplusplus)
extern "C" {
#endif
BSSL_NAMESPACE_BEGIN
typedef struct conf_section_st CONF_SECTION;
DEFINE_LHASH_OF(CONF_SECTION)
DEFINE_LHASH_OF(CONF_VALUE)
BSSL_NAMESPACE_END
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);
BSSL_NAMESPACE_BEGIN
// CONF_parse_list takes a list separated by 'sep' and calls |list_cb| giving
// CONF_VALUE_new returns a freshly allocated and zeroed `CONF_VALUE`.
CONF_VALUE *CONF_VALUE_new();
// CONF_parse_list takes a list separated by 'sep' and calls `list_cb` giving
// the start and length of each member, optionally stripping leading and
// trailing whitespace. This can be used to parse comma separated lists for
// example. If |list_cb| returns <= 0, then the iteration is halted and that
// value is returned immediately. Otherwise it returns one. Note that |list_cb|
// example. If `list_cb` returns <= 0, then the iteration is halted and that
// value is returned immediately. Otherwise it returns one. Note that `list_cb`
// may be called on an empty member.
OPENSSL_EXPORT int CONF_parse_list(
const char *list, char sep, int remove_whitespace,
int (*list_cb)(const char *elem, size_t len, void *usr), void *arg);
#if defined(__cplusplus)
} // extern C
#endif
BSSL_NAMESPACE_END
#endif // OPENSSL_HEADER_CRYPTO_CONF_INTERNAL_H
@@ -1,16 +1,16 @@
/* Copyright 2021 The BoringSSL Authors
*
* 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. */
// Copyright 2021 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal.h"
@@ -20,13 +20,13 @@
#include <sys/sysctl.h>
#include <sys/types.h>
#include <CNIOBoringSSL_arm_arch.h>
using namespace bssl;
static int has_hw_feature(const char *name) {
int value;
size_t len = sizeof(value);
if (sysctlbyname(name, &value, &len, NULL, 0) != 0) {
if (sysctlbyname(name, &value, &len, nullptr, 0) != 0) {
return 0;
}
if (len != sizeof(int)) {
@@ -45,7 +45,7 @@ static int has_hw_feature(const char *name) {
return value != 0;
}
void OPENSSL_cpuid_setup(void) {
void bssl::OPENSSL_cpuid_setup() {
// Apple ARM64 platforms have NEON and cryptography extensions available
// statically, so we do not need to query them. In particular, there sometimes
// are no sysctls corresponding to such features. See below.
@@ -63,13 +63,14 @@ 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;
}
if (has_hw_feature("hw.optional.arm.FEAT_SHA3") ||
has_hw_feature("hw.optional.armv8_2_sha3")) {
OPENSSL_armcap_P |= ARMV8_SHA3;
}
}
#endif // OPENSSL_AARCH64 && OPENSSL_APPLE && !OPENSSL_STATIC_ARMCAP
@@ -1,16 +1,16 @@
/* Copyright 2018 The BoringSSL Authors
*
* 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. */
// Copyright 2018 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal.h"
@@ -21,10 +21,10 @@
#include <zircon/syscalls.h>
#include <zircon/types.h>
#include <CNIOBoringSSL_arm_arch.h>
using namespace bssl;
void OPENSSL_cpuid_setup(void) {
void bssl::OPENSSL_cpuid_setup() {
uint32_t hwcap;
zx_status_t rc = zx_system_get_features(ZX_FEATURE_KIND_CPU, &hwcap);
if (rc != ZX_OK || (hwcap & ZX_ARM64_FEATURE_ISA_ASIMD) == 0) {
@@ -50,6 +50,9 @@ void OPENSSL_cpuid_setup(void) {
if (hwcap & ZX_ARM64_FEATURE_ISA_SHA512) {
OPENSSL_armcap_P |= ARMV8_SHA512;
}
if (hwcap & ZX_ARM64_FEATURE_ISA_SHA3) {
OPENSSL_armcap_P |= ARMV8_SHA3;
}
}
#endif // OPENSSL_AARCH64 && OPENSSL_FUCHSIA && !OPENSSL_STATIC_ARMCAP
@@ -1,16 +1,16 @@
/* Copyright 2016 The BoringSSL Authors
*
* 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. */
// Copyright 2016 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal.h"
@@ -19,10 +19,10 @@
#include <sys/auxv.h>
#include <CNIOBoringSSL_arm_arch.h>
using namespace bssl;
void OPENSSL_cpuid_setup(void) {
void bssl::OPENSSL_cpuid_setup() {
unsigned long hwcap = getauxval(AT_HWCAP);
// See /usr/include/asm/hwcap.h on an aarch64 installation for the source of
@@ -32,6 +32,7 @@ void OPENSSL_cpuid_setup(void) {
static const unsigned long kPMULL = 1 << 4;
static const unsigned long kSHA1 = 1 << 5;
static const unsigned long kSHA256 = 1 << 6;
static const unsigned long kSHA3 = 1 << 17;
static const unsigned long kSHA512 = 1 << 21;
if ((hwcap & kNEON) == 0) {
@@ -57,6 +58,9 @@ void OPENSSL_cpuid_setup(void) {
if (hwcap & kSHA512) {
OPENSSL_armcap_P |= ARMV8_SHA512;
}
if (hwcap & kSHA3) {
OPENSSL_armcap_P |= ARMV8_SHA3;
}
}
#endif // OPENSSL_AARCH64 && OPENSSL_LINUX && !OPENSSL_STATIC_ARMCAP
@@ -1,16 +1,16 @@
/* Copyright (c) 2022, Robert Nagy <robert.nagy@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
// Copyright (c) 2022, Robert Nagy <robert.nagy@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_cpu.h>
@@ -21,41 +21,25 @@
#include <machine/cpu.h>
#include <sys/sysctl.h>
#include <CNIOBoringSSL_arm_arch.h>
#include "armv8_feature_parsing.h"
#include "internal.h"
void OPENSSL_cpuid_setup(void) {
using namespace bssl;
void bssl::OPENSSL_cpuid_setup() {
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) {
if (sysctl(isar0_mib, 2, &cpu_id, &len, nullptr, 0) < 0) {
return;
}
OPENSSL_armcap_P |= ARMV7_NEON;
if (ID_AA64ISAR0_AES(cpu_id) >= ID_AA64ISAR0_AES_BASE) {
OPENSSL_armcap_P |= ARMV8_AES;
}
if (ID_AA64ISAR0_AES(cpu_id) >= ID_AA64ISAR0_AES_PMULL) {
OPENSSL_armcap_P |= ARMV8_PMULL;
}
if (ID_AA64ISAR0_SHA1(cpu_id) >= ID_AA64ISAR0_SHA1_BASE) {
OPENSSL_armcap_P |= ARMV8_SHA1;
}
if (ID_AA64ISAR0_SHA2(cpu_id) >= ID_AA64ISAR0_SHA2_BASE) {
OPENSSL_armcap_P |= ARMV8_SHA256;
}
if (ID_AA64ISAR0_SHA2(cpu_id) >= ID_AA64ISAR0_SHA2_512) {
OPENSSL_armcap_P |= ARMV8_SHA512;
}
// Use the common parsing function to check other features.
OPENSSL_armcap_P |= armcap::ParseISAR0Flags(cpu_id);
}
#endif // OPENSSL_AARCH64 && OPENSSL_OPENBSD && !OPENSSL_STATIC_ARMCAP
@@ -1,16 +1,18 @@
/* Copyright 2023 The BoringSSL Authors
*
* 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. */
// Copyright 2023 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_cpu.h>
#include "internal.h"
@@ -21,16 +23,12 @@
(defined(ANDROID_BAREMETAL) || defined(OPENSSL_FREEBSD)) && \
!defined(OPENSSL_NO_ASM)
#include <CNIOBoringSSL_arm_arch.h>
#include "./armv8_feature_parsing.h"
BSSL_NAMESPACE_BEGIN
#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; \
@@ -38,12 +36,10 @@
_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);
// We use the common GetIDField helper now, but need a signed variant
// for the NEON check using ID_AA64PFR0_EL1.
static int GetSignedIDField(uint64_t reg, unsigned field) {
unsigned value = armcap::GetIDField(reg, field);
if (value & (1 << (NBITS_ID_FIELD - 1))) {
return (int)(value | (UINT64_MAX << NBITS_ID_FIELD));
} else {
@@ -51,44 +47,20 @@ static int get_signed_id_field(uint64_t reg, unsigned field) {
}
}
static uint32_t read_armcap(void) {
uint32_t armcap = ARMV7_NEON;
void OPENSSL_cpuid_setup() {
uint64_t id_aa64pfr0_el1 = READ_SYSREG("id_aa64pfr0_el1");
if (get_signed_id_field(id_aa64pfr0_el1, ID_AA64PFR0_EL1_ADVSIMD) < 0) {
if (GetSignedIDField(id_aa64pfr0_el1, ID_AA64PFR0_EL1_ADVSIMD) < 0) {
// If AdvSIMD ("NEON") is missing, don't report other features either.
// This matches OpenSSL.
return 0;
return;
}
// Use the common parsing function to check all cryptographic features.
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;
OPENSSL_armcap_P |= ARMV7_NEON | armcap::ParseISAR0Flags(id_aa64isar0_el1);
}
void OPENSSL_cpuid_setup(void) { OPENSSL_armcap_P |= read_armcap(); }
BSSL_NAMESPACE_END
#endif // OPENSSL_AARCH64 && !OPENSSL_STATIC_ARMCAP &&
// (ANDROID_BAREMETAL || OPENSSL_FREEBSD)
+29 -18
View File
@@ -1,17 +1,17 @@
/* Copyright 2018 The BoringSSL Authors
* Copyright (c) 2020, Arm Ltd.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
// Copyright 2018 The BoringSSL Authors
// Copyright (c) 2020, Arm Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal.h"
@@ -20,10 +20,17 @@
#include <windows.h>
#include <CNIOBoringSSL_arm_arch.h>
#if !defined(PF_ARM_SHA3_INSTRUCTIONS_AVAILABLE)
#define PF_ARM_SHA3_INSTRUCTIONS_AVAILABLE 64
#endif
#if !defined(PF_ARM_SHA512_INSTRUCTIONS_AVAILABLE)
#define PF_ARM_SHA512_INSTRUCTIONS_AVAILABLE 65
#endif
void OPENSSL_cpuid_setup(void) {
using namespace bssl;
void bssl::OPENSSL_cpuid_setup() {
// We do not need to check for the presence of NEON, as Armv8-A always has it
OPENSSL_armcap_P |= ARMV7_NEON;
@@ -34,8 +41,12 @@ void OPENSSL_cpuid_setup(void) {
OPENSSL_armcap_P |= ARMV8_SHA1;
OPENSSL_armcap_P |= ARMV8_SHA256;
}
// As of writing, Windows does not have a |PF_*| value for ARMv8.2 SHA-512
// extensions. When it does, add it here.
if (IsProcessorFeaturePresent(PF_ARM_SHA512_INSTRUCTIONS_AVAILABLE)) {
OPENSSL_armcap_P |= ARMV8_SHA512;
}
if (IsProcessorFeaturePresent(PF_ARM_SHA3_INSTRUCTIONS_AVAILABLE)) {
OPENSSL_armcap_P |= ARMV8_SHA3;
}
}
#endif // OPENSSL_AARCH64 && OPENSSL_WINDOWS && !OPENSSL_STATIC_ARMCAP
+17 -16
View File
@@ -1,16 +1,16 @@
/* Copyright 2022 The BoringSSL Authors
*
* 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. */
// Copyright 2022 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal.h"
@@ -19,14 +19,15 @@
#include <sys/auxv.h>
#include <sys/types.h>
#include <CNIOBoringSSL_arm_arch.h>
#include <CNIOBoringSSL_mem.h>
void OPENSSL_cpuid_setup(void) {
using namespace bssl;
void bssl::OPENSSL_cpuid_setup() {
unsigned long hwcap = 0, hwcap2 = 0;
// |elf_aux_info| may fail, in which case |hwcap| and |hwcap2| will be
// `elf_aux_info` may fail, in which case `hwcap` and `hwcap2` will be
// left at zero. The rest of this function will then gracefully report
// the features are absent.
elf_aux_info(AT_HWCAP, &hwcap, sizeof(hwcap));
+67 -45
View File
@@ -1,16 +1,16 @@
/* Copyright 2016 The BoringSSL Authors
*
* 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. */
// Copyright 2016 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal.h"
@@ -22,11 +22,14 @@
#include <sys/types.h>
#include <unistd.h>
#include <CNIOBoringSSL_arm_arch.h>
#include <string_view>
#include <CNIOBoringSSL_mem.h>
#include "cpu_arm_linux.h"
using namespace bssl;
static int open_eintr(const char *path, int flags) {
int ret;
do {
@@ -43,8 +46,8 @@ static ssize_t read_eintr(int fd, void *out, size_t len) {
return ret;
}
// 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
// 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.
static int read_file(char **out_ptr, size_t *out_len, const char *path) {
int fd = open_eintr(path, O_RDONLY);
@@ -56,7 +59,7 @@ static int read_file(char **out_ptr, size_t *out_len, const char *path) {
int ret = 0;
size_t cap = kReadSize, len = 0;
char *buf = reinterpret_cast<char *>(OPENSSL_malloc(cap));
if (buf == NULL) {
if (buf == nullptr) {
goto err;
}
@@ -67,7 +70,7 @@ static int read_file(char **out_ptr, size_t *out_len, const char *path) {
goto err;
}
char *new_buf = reinterpret_cast<char *>(OPENSSL_realloc(buf, new_cap));
if (new_buf == NULL) {
if (new_buf == nullptr) {
goto err;
}
buf = new_buf;
@@ -87,7 +90,7 @@ static int read_file(char **out_ptr, size_t *out_len, const char *path) {
*out_ptr = buf;
*out_len = len;
ret = 1;
buf = NULL;
buf = nullptr;
err:
OPENSSL_free(buf);
@@ -97,53 +100,72 @@ err:
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.
char *cpuinfo_data = NULL;
size_t cpuinfo_len = 0;
read_file(&cpuinfo_data, &cpuinfo_len, "/proc/cpuinfo");
STRING_PIECE cpuinfo;
cpuinfo.data = cpuinfo_data;
cpuinfo.len = cpuinfo_len;
void bssl::OPENSSL_cpuid_setup() {
// Matching OpenSSL, only report other features if NEON is present.
unsigned long hwcap = getauxval(AT_HWCAP);
if (hwcap & HWCAP_NEON) {
if (hwcap & CRYPTO_HWCAP_NEON) {
#if defined(HWCAP_ARM_NEON)
static_assert(HWCAP_ARM_NEON == CRYPTO_HWCAP_NEON,
"CRYPTO_HWCAP values must match Linux");
#endif
OPENSSL_armcap_P |= ARMV7_NEON;
// Some ARMv8 Android devices don't expose AT_HWCAP2. Fall back to
// /proc/cpuinfo. See https://crbug.com/boringssl/46. As of February 2021,
// this is now rare (see Chrome's Net.NeedsHWCAP2Workaround metric), but AES
// and PMULL extensions are very useful, so we still carry the workaround
// for now.
// /proc/cpuinfo. See https://crbug.com/40644934. The fix was added to
// Android CTS in N, so, after Net.NeedsHWCAP2Workaround confirms this, we
// should be able to disable this when __ANDROID_MIN_SDK_VERSION__ is high
// enough. (It may not be worth carrying the workaround at all at that
// point. Then again, AES and PMULL extensions are crucial for performance
// when available.)
unsigned long hwcap2 = getauxval(AT_HWCAP2);
if (hwcap2 == 0) {
hwcap2 = crypto_get_arm_hwcap2_from_cpuinfo(&cpuinfo);
g_needs_hwcap2_workaround = hwcap2 != 0;
char *cpuinfo_data = nullptr;
size_t cpuinfo_len = 0;
if (read_file(&cpuinfo_data, &cpuinfo_len, "/proc/cpuinfo")) {
hwcap2 = armcap::GetHWCAP2FromCpuinfo(
std::string_view(cpuinfo_data, cpuinfo_len));
g_needs_hwcap2_workaround = hwcap2 != 0;
OPENSSL_free(cpuinfo_data);
}
}
if (hwcap2 & HWCAP2_AES) {
// HWCAP2_* values, without the "CRYPTO_" prefix, are exposed through
// <sys/auxv.h> in some versions of glibc(>= 2.41). Assert that we don't
// diverge from those values.
if (hwcap2 & CRYPTO_HWCAP2_AES) {
#if defined(HWCAP2_AES)
static_assert(HWCAP2_AES == CRYPTO_HWCAP2_AES,
"CRYPTO_HWCAP2 values must match Linux");
#endif
OPENSSL_armcap_P |= ARMV8_AES;
}
if (hwcap2 & HWCAP2_PMULL) {
if (hwcap2 & CRYPTO_HWCAP2_PMULL) {
#if defined(HWCAP2_PMULL)
static_assert(HWCAP2_PMULL == CRYPTO_HWCAP2_PMULL,
"CRYPTO_HWCAP2 values must match Linux");
#endif
OPENSSL_armcap_P |= ARMV8_PMULL;
}
if (hwcap2 & HWCAP2_SHA1) {
if (hwcap2 & CRYPTO_HWCAP2_SHA1) {
#if defined(HWCAP2_SHA1)
static_assert(HWCAP2_SHA1 == CRYPTO_HWCAP2_SHA1,
"CRYPTO_HWCAP2 values must match Linux");
#endif
OPENSSL_armcap_P |= ARMV8_SHA1;
}
if (hwcap2 & HWCAP2_SHA2) {
if (hwcap2 & CRYPTO_HWCAP2_SHA2) {
#if defined(HWCAP2_SHA2)
static_assert(HWCAP2_SHA2 == CRYPTO_HWCAP2_SHA2,
"CRYPTO_HWCAP2 values must match Linux");
#endif
OPENSSL_armcap_P |= ARMV8_SHA256;
}
}
OPENSSL_free(cpuinfo_data);
}
int CRYPTO_has_broken_NEON(void) { return 0; }
int CRYPTO_has_broken_NEON() { return 0; }
int CRYPTO_needs_hwcap2_workaround(void) {
int CRYPTO_needs_hwcap2_workaround() {
OPENSSL_init_cpuid();
return g_needs_hwcap2_workaround;
}
+92 -114
View File
@@ -1,163 +1,141 @@
/* Copyright 2018 The BoringSSL Authors
*
* 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. */
// Copyright 2018 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSSL_HEADER_CRYPTO_CPU_ARM_LINUX_H
#define OPENSSL_HEADER_CRYPTO_CPU_ARM_LINUX_H
#include <CNIOBoringSSL_base.h>
#include <string.h>
#include <assert.h>
#include <string_view>
#include "internal.h"
#if defined(__cplusplus)
extern "C" {
#endif
BSSL_NAMESPACE_BEGIN
namespace armcap {
// The cpuinfo parser lives in a header file so it may be accessible from
// cross-platform fuzzers without adding code to those platforms normally.
#define HWCAP_NEON (1 << 12)
#define CRYPTO_HWCAP_NEON (1 << 12)
// See /usr/include/asm/hwcap.h on an ARM installation for the source of
// these values.
#define HWCAP2_AES (1 << 0)
#define HWCAP2_PMULL (1 << 1)
#define HWCAP2_SHA1 (1 << 2)
#define HWCAP2_SHA2 (1 << 3)
// We add the prefix "CRYPTO_" to the definitions so as not to collide with
// some versions of glibc (>= 2.41) that expose them through <sys/auxv.h>.
#define CRYPTO_HWCAP2_AES (1 << 0)
#define CRYPTO_HWCAP2_PMULL (1 << 1)
#define CRYPTO_HWCAP2_SHA1 (1 << 2)
#define CRYPTO_HWCAP2_SHA2 (1 << 3)
typedef struct {
const char *data;
size_t len;
} STRING_PIECE;
static int STRING_PIECE_equals(const STRING_PIECE *a, const char *b) {
size_t b_len = strlen(b);
return a->len == b_len && OPENSSL_memcmp(a->data, b, b_len) == 0;
// SplitStringView finds the first occurrence of `sep` in `in` and, if found,
// sets `*out_left` and `*out_right` to `in` split before and after `sep`, and
// returns true. If not found, it returns false.
inline bool SplitStringView(std::string_view *out_left,
std::string_view *out_right, std::string_view in,
char sep) {
auto pos = in.find(sep);
if (pos == std::string_view::npos) {
return false;
}
*out_left = in.substr(0, pos);
*out_right = in.substr(pos + 1);
return true;
}
// STRING_PIECE_split finds the first occurence of |sep| in |in| and, if found,
// sets |*out_left| and |*out_right| to |in| split before and after it. It
// returns one if |sep| was found and zero otherwise.
static int STRING_PIECE_split(STRING_PIECE *out_left, STRING_PIECE *out_right,
const STRING_PIECE *in, char sep) {
const char *p = (const char *)OPENSSL_memchr(in->data, sep, in->len);
if (p == NULL) {
return 0;
// GetDelimited reads a `sep`-delimited entry from `s`, writing it to `out` and
// updating `s` to point beyond it. It returns true on success and false if `s`
// is empty. If `s` has no copies of `sep` and is non-empty, it reads the entire
// string to `out`.
inline bool GetDelimited(std::string_view *s, std::string_view *out, char sep) {
if (s->empty()) {
return false;
}
// |out_left| or |out_right| may alias |in|, so make a copy.
STRING_PIECE in_copy = *in;
out_left->data = in_copy.data;
out_left->len = p - in_copy.data;
out_right->data = in_copy.data + out_left->len + 1;
out_right->len = in_copy.len - out_left->len - 1;
return 1;
}
// STRING_PIECE_get_delimited reads a |sep|-delimited entry from |s|, writing it
// to |out| and updating |s| to point beyond it. It returns one on success and
// zero if |s| is empty. If |s| is has no copies of |sep| and is non-empty, it
// reads the entire string to |out|.
static int STRING_PIECE_get_delimited(STRING_PIECE *s, STRING_PIECE *out, char sep) {
if (s->len == 0) {
return 0;
}
if (!STRING_PIECE_split(out, s, s, sep)) {
// |s| had no instances of |sep|. Return the entire string.
if (!SplitStringView(out, s, *s, sep)) {
// `s` had no instances of `sep`. Return the entire string.
*out = *s;
s->data += s->len;
s->len = 0;
*s = std::string_view();
}
return 1;
return true;
}
// STRING_PIECE_trim removes leading and trailing whitespace from |s|.
static void STRING_PIECE_trim(STRING_PIECE *s) {
while (s->len != 0 && (s->data[0] == ' ' || s->data[0] == '\t')) {
s->data++;
s->len--;
}
while (s->len != 0 &&
(s->data[s->len - 1] == ' ' || s->data[s->len - 1] == '\t')) {
s->len--;
// TrimStringView removes leading and trailing whitespace from `s`.
inline std::string_view TrimStringView(std::string_view s) {
size_t pos = s.find_first_not_of(" \t");
if (pos == std::string_view::npos) {
return {};
}
s = s.substr(pos);
pos = s.find_last_not_of(" \t");
assert(pos != std::string_view::npos);
return s.substr(0, pos + 1);
}
// extract_cpuinfo_field extracts a /proc/cpuinfo field named |field| from
// |in|. If found, it sets |*out| to the value and returns one. Otherwise, it
// returns zero.
static int extract_cpuinfo_field(STRING_PIECE *out, const STRING_PIECE *in,
const char *field) {
// Process |in| one line at a time.
STRING_PIECE remaining = *in, line;
while (STRING_PIECE_get_delimited(&remaining, &line, '\n')) {
STRING_PIECE key, value;
if (!STRING_PIECE_split(&key, &value, &line, ':')) {
// ExtractCpuinfoField extracts a /proc/cpuinfo field named `field` from `in`.
// If found, it returns the value. Otherwise, it returns the empty string.
inline std::string_view ExtractCpuinfoField(std::string_view in,
std::string_view field) {
// Process `in` one line at a time.
std::string_view line;
while (GetDelimited(&in, &line, '\n')) {
std::string_view key, value;
if (!SplitStringView(&key, &value, line, ':')) {
continue;
}
STRING_PIECE_trim(&key);
if (STRING_PIECE_equals(&key, field)) {
STRING_PIECE_trim(&value);
*out = value;
return 1;
if (TrimStringView(key) == field) {
return TrimStringView(value);
}
}
return 0;
return {};
}
// 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) {
STRING_PIECE remaining = *list, feature;
while (STRING_PIECE_get_delimited(&remaining, &feature, ' ')) {
if (STRING_PIECE_equals(&feature, item)) {
return 1;
// HasListItem treats `list` as a space-separated list of items and returns
// whether `item` is contained in `list`.
inline bool HasListItem(std::string_view list, std::string_view item) {
std::string_view feature;
while (GetDelimited(&list, &feature, ' ')) {
if (feature == item) {
return true;
}
}
return 0;
return false;
}
// crypto_get_arm_hwcap2_from_cpuinfo returns an equivalent ARM |AT_HWCAP2|
// value from |cpuinfo|.
static unsigned long crypto_get_arm_hwcap2_from_cpuinfo(
const STRING_PIECE *cpuinfo) {
STRING_PIECE features;
if (!extract_cpuinfo_field(&features, cpuinfo, "Features")) {
return 0;
}
// GetHWCAP2FromCpuinfo returns an equivalent ARM `AT_HWCAP2` value from
// `cpuinfo`.
inline unsigned long GetHWCAP2FromCpuinfo(std::string_view cpuinfo) {
std::string_view features = ExtractCpuinfoField(cpuinfo, "Features");
unsigned long ret = 0;
if (has_list_item(&features, "aes")) {
ret |= HWCAP2_AES;
if (HasListItem(features, "aes")) {
ret |= CRYPTO_HWCAP2_AES;
}
if (has_list_item(&features, "pmull")) {
ret |= HWCAP2_PMULL;
if (HasListItem(features, "pmull")) {
ret |= CRYPTO_HWCAP2_PMULL;
}
if (has_list_item(&features, "sha1")) {
ret |= HWCAP2_SHA1;
if (HasListItem(features, "sha1")) {
ret |= CRYPTO_HWCAP2_SHA1;
}
if (has_list_item(&features, "sha2")) {
ret |= HWCAP2_SHA2;
if (HasListItem(features, "sha2")) {
ret |= CRYPTO_HWCAP2_SHA2;
}
return ret;
}
#if defined(__cplusplus)
} // extern C
#endif
} // namespace armcap
BSSL_NAMESPACE_END
#endif // OPENSSL_HEADER_CRYPTO_CPU_ARM_LINUX_H
+64 -71
View File
@@ -1,35 +1,41 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_base.h>
#if !defined(OPENSSL_NO_ASM) && \
(defined(OPENSSL_X86) || defined(OPENSSL_X86_64))
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#if defined(_MSC_VER)
OPENSSL_MSVC_PRAGMA(warning(push, 3))
#include <immintrin.h>
#include <intrin.h>
OPENSSL_MSVC_PRAGMA(warning(pop))
#endif
#include "internal.h"
// OPENSSL_cpuid runs the cpuid instruction. |leaf| is passed in as EAX and ECX
// is set to zero. It writes EAX, EBX, ECX, and EDX to |*out_eax| through
// |*out_edx|.
using namespace bssl;
// OPENSSL_cpuid runs the cpuid instruction. `leaf` is passed in as EAX and ECX
// is set to zero. It writes EAX, EBX, ECX, and EDX to `*out_eax` through
// `*out_edx`.
static void OPENSSL_cpuid(uint32_t *out_eax, uint32_t *out_ebx,
uint32_t *out_ecx, uint32_t *out_edx, uint32_t leaf) {
#if defined(_MSC_VER)
@@ -59,7 +65,7 @@ static void OPENSSL_cpuid(uint32_t *out_eax, uint32_t *out_ebx,
}
// OPENSSL_xgetbv returns the value of an Intel Extended Control Register (XCR).
// Currently only XCR0 is defined by Intel so |xcr| should always be zero.
// Currently only XCR0 is defined by Intel so `xcr` should always be zero.
static uint64_t OPENSSL_xgetbv(uint32_t xcr) {
#if defined(_MSC_VER)
return (uint64_t)_xgetbv(xcr);
@@ -86,23 +92,26 @@ static bool os_supports_avx512(uint64_t xcr0) {
#endif
}
// handle_cpu_env applies the value from |in| to the CPUID values in |out[0]|
// and |out[1]|. See the comment in |OPENSSL_cpuid_setup| about this.
static void handle_cpu_env(uint32_t *out, const char *in) {
// handle_cpu_env applies the value from `in` to the CPUID values in `out[0]`
// and `out[1]`. See the comment in `OPENSSL_cpuid_setup` about this. The
// `is_last` argument specifies whether the value is at the end of the string.
// Otherwise it may be followed by a colon.
static void handle_cpu_env(uint32_t out[2], const char *in, bool is_last) {
const int invert_op = in[0] == '~';
const int or_op = in[0] == '|';
const int skip_first_byte = invert_op || or_op;
const int hex = in[skip_first_byte] == '0' && in[skip_first_byte + 1] == 'x';
const int base = hex ? 16 : 10;
int sscanf_result;
uint64_t v;
if (hex) {
sscanf_result = sscanf(in + invert_op + 2, "%" PRIx64, &v);
} else {
sscanf_result = sscanf(in + invert_op, "%" PRIu64, &v);
}
const char *start = in + skip_first_byte;
char *end;
errno = 0;
// We need to parse 64-bit values with `strtoull`.
static_assert(sizeof(unsigned long long) == sizeof(uint64_t));
unsigned long long v = strtoull(start, &end, base);
if (!sscanf_result) {
if (end == start || (*end != '\0' && (is_last || *end != ':')) ||
(v == ULLONG_MAX && errno == ERANGE)) {
return;
}
@@ -118,18 +127,39 @@ static void handle_cpu_env(uint32_t *out, const char *in) {
}
}
void OPENSSL_cpuid_setup(void) {
void bssl::OPENSSL_adjust_ia32cap(uint32_t cap[4], const char *env) {
// OPENSSL_ia32cap can contain zero, one or two values, separated with a ':'.
// Each value is a 64-bit, unsigned value which may start with "0x" to
// indicate a hex value. Prior to the 64-bit value, a '~' or '|' may be given.
//
// If the '~' prefix is present:
// the value is inverted and ANDed with the probed CPUID result
// If the '|' prefix is present:
// the value is ORed with the probed CPUID result
// Otherwise:
// the value is taken as the result of the CPUID
//
// The first value determines OPENSSL_ia32cap_P[0] and [1]. The second [2]
// and [3].
handle_cpu_env(cap, env, /*is_last=*/false);
env = strchr(env, ':');
if (env != nullptr) {
handle_cpu_env(cap + 2, env + 1, /*is_last=*/true);
}
}
void bssl::OPENSSL_cpuid_setup() {
// Determine the vendor and maximum input value.
uint32_t eax, ebx, ecx, edx;
OPENSSL_cpuid(&eax, &ebx, &ecx, &edx, 0);
uint32_t num_ids = eax;
int is_intel = ebx == 0x756e6547 /* Genu */ && //
edx == 0x49656e69 /* ineI */ && //
int is_intel = ebx == 0x756e6547 /* Genu */ && //
edx == 0x49656e69 /* ineI */ && //
ecx == 0x6c65746e /* ntel */;
int is_amd = ebx == 0x68747541 /* Auth */ && //
edx == 0x69746e65 /* enti */ && //
int is_amd = ebx == 0x68747541 /* Auth */ && //
edx == 0x69746e65 /* enti */ && //
ecx == 0x444d4163 /* cAMD */;
uint32_t extended_features[2] = {0};
@@ -166,14 +196,6 @@ void OPENSSL_cpuid_setup(void) {
}
}
// Force the hyper-threading bit so that the more conservative path is always
// chosen.
edx |= 1u << 28;
// Reserved bit #20 was historically repurposed to control the in-memory
// representation of RC4 state. Always set it to zero.
edx &= ~(1u << 20);
// Reserved bit #30 is repurposed to signal an Intel CPU.
if (is_intel) {
edx |= (1u << 30);
@@ -181,10 +203,6 @@ void OPENSSL_cpuid_setup(void) {
edx &= ~(1u << 30);
}
// The SDBG bit is repurposed to denote AMD XOP support. Don't ever use AMD
// XOP code paths.
ecx &= ~(1u << 11);
uint64_t xcr0 = 0;
if (ecx & (1u << 27)) {
// XCR0 may only be queried if the OSXSAVE bit is set.
@@ -214,10 +232,6 @@ void OPENSSL_cpuid_setup(void) {
// 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
@@ -264,30 +278,9 @@ void OPENSSL_cpuid_setup(void) {
OPENSSL_ia32cap_P[2] = extended_features[0];
OPENSSL_ia32cap_P[3] = extended_features[1];
const char *env1, *env2;
env1 = getenv("OPENSSL_ia32cap");
if (env1 == NULL) {
return;
}
// OPENSSL_ia32cap can contain zero, one or two values, separated with a ':'.
// Each value is a 64-bit, unsigned value which may start with "0x" to
// indicate a hex value. Prior to the 64-bit value, a '~' or '|' may be given.
//
// If the '~' prefix is present:
// the value is inverted and ANDed with the probed CPUID result
// If the '|' prefix is present:
// the value is ORed with the probed CPUID result
// Otherwise:
// the value is taken as the result of the CPUID
//
// The first value determines OPENSSL_ia32cap_P[0] and [1]. The second [2]
// and [3].
handle_cpu_env(&OPENSSL_ia32cap_P[0], env1);
env2 = strchr(env1, ':');
if (env2 != NULL) {
handle_cpu_env(&OPENSSL_ia32cap_P[2], env2 + 1);
const char *env = getenv("OPENSSL_ia32cap");
if (env != nullptr) {
OPENSSL_adjust_ia32cap(OPENSSL_ia32cap_P, env);
}
}
+39 -70
View File
@@ -1,16 +1,16 @@
/* Copyright 2014 The BoringSSL Authors
*
* 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. */
// Copyright 2014 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <CNIOBoringSSL_crypto.h>
@@ -22,6 +22,8 @@
#include "internal.h"
using namespace bssl;
static_assert(sizeof(ossl_ssize_t) == sizeof(size_t),
"ossl_ssize_t should be the same size as size_t");
@@ -54,77 +56,42 @@ static_assert(sizeof(ossl_ssize_t) == sizeof(size_t),
// archive, linking on OS X will fail to resolve common symbols. By
// initialising it to zero, it becomes a "data symbol", which isn't so
// affected.
HIDDEN uint8_t BORINGSSL_function_hit[9] = {0};
HIDDEN uint8_t bssl::BORINGSSL_function_hit[8] = {0};
#endif
#if defined(OPENSSL_X86) || defined(OPENSSL_X86_64)
// This value must be explicitly initialized to zero. See similar comment above.
HIDDEN uint32_t OPENSSL_ia32cap_P[4] = {0};
HIDDEN uint32_t bssl::OPENSSL_ia32cap_P[4] = {0};
uint32_t OPENSSL_get_ia32cap(int idx) {
uint32_t bssl::OPENSSL_get_ia32cap(int idx) {
OPENSSL_init_cpuid();
return OPENSSL_ia32cap_P[idx];
}
#elif defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)
#elif (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) && \
!defined(OPENSSL_STATIC_ARMCAP)
HIDDEN uint32_t bssl::OPENSSL_armcap_P = 0;
#include <CNIOBoringSSL_arm_arch.h>
#if defined(OPENSSL_STATIC_ARMCAP)
// See ARM ACLE for the definitions of these macros. Note |__ARM_FEATURE_AES|
// covers both AES and PMULL and |__ARM_FEATURE_SHA2| covers SHA-1 and SHA-256.
// https://developer.arm.com/architectures/system-architectures/software-standards/acle
// https://github.com/ARM-software/acle/issues/152
//
// TODO(davidben): Do we still need |OPENSSL_STATIC_ARMCAP_*| or are the
// standard flags and -march sufficient?
HIDDEN uint32_t OPENSSL_armcap_P =
#if defined(OPENSSL_STATIC_ARMCAP_NEON) || defined(__ARM_NEON)
ARMV7_NEON |
#endif
#if defined(OPENSSL_STATIC_ARMCAP_AES) || defined(__ARM_FEATURE_AES)
ARMV8_AES |
#endif
#if defined(OPENSSL_STATIC_ARMCAP_PMULL) || defined(__ARM_FEATURE_AES)
ARMV8_PMULL |
#endif
#if defined(OPENSSL_STATIC_ARMCAP_SHA1) || defined(__ARM_FEATURE_SHA2)
ARMV8_SHA1 |
#endif
#if defined(OPENSSL_STATIC_ARMCAP_SHA256) || defined(__ARM_FEATURE_SHA2)
ARMV8_SHA256 |
#endif
#if defined(__ARM_FEATURE_SHA512)
ARMV8_SHA512 |
#endif
0;
#else
HIDDEN uint32_t OPENSSL_armcap_P = 0;
uint32_t *OPENSSL_get_armcap_pointer_for_test(void) {
uint32_t *bssl::OPENSSL_get_armcap_pointer_for_test() {
OPENSSL_init_cpuid();
return &OPENSSL_armcap_P;
}
#endif
uint32_t OPENSSL_get_armcap(void) {
uint32_t bssl::OPENSSL_get_armcap() {
OPENSSL_init_cpuid();
return OPENSSL_armcap_P;
}
#endif
#if defined(NEED_CPUID)
static CRYPTO_once_t once = CRYPTO_ONCE_INIT;
void OPENSSL_init_cpuid(void) { CRYPTO_once(&once, OPENSSL_cpuid_setup); }
static bssl::CRYPTO_once_t once = CRYPTO_ONCE_INIT;
void bssl::OPENSSL_init_cpuid() { CRYPTO_once(&once, OPENSSL_cpuid_setup); }
#endif
void CRYPTO_library_init(void) {}
void CRYPTO_library_init() {}
int CRYPTO_is_confidential_build(void) {
int CRYPTO_is_confidential_build() {
#if defined(BORINGSSL_CONFIDENTIAL)
return 1;
#else
@@ -132,7 +99,7 @@ int CRYPTO_is_confidential_build(void) {
#endif
}
void CRYPTO_pre_sandbox_init(void) {
void CRYPTO_pre_sandbox_init() {
// Read from /proc/cpuinfo if needed.
OPENSSL_init_cpuid();
// Open /dev/urandom if needed.
@@ -160,24 +127,26 @@ const char *OpenSSL_version(int which) {
}
}
unsigned long SSLeay(void) { return OPENSSL_VERSION_NUMBER; }
unsigned long SSLeay() { return OPENSSL_VERSION_NUMBER; }
unsigned long OpenSSL_version_num(void) { return OPENSSL_VERSION_NUMBER; }
unsigned long OpenSSL_version_num() { return OPENSSL_VERSION_NUMBER; }
int CRYPTO_malloc_init(void) { return 1; }
int CRYPTO_malloc_init() { return 1; }
int OPENSSL_malloc_init(void) { return 1; }
int OPENSSL_malloc_init() { return 1; }
void ENGINE_load_builtin_engines(void) {}
void ENGINE_load_builtin_engines() {}
int ENGINE_register_all_complete(void) { return 1; }
int ENGINE_register_all_complete() { return 1; }
void OPENSSL_load_builtin_modules(void) {}
void ENGINE_cleanup() {}
void OPENSSL_load_builtin_modules() {}
int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings) {
return 1;
}
void OPENSSL_cleanup(void) {}
void OPENSSL_cleanup() {}
FILE *CRYPTO_get_stderr(void) { return stderr; }
FILE *bssl::CRYPTO_get_stderr() { return stderr; }
@@ -1,22 +1,22 @@
#define BORINGSSL_PREFIX CNIOBoringSSL
#if defined(__arm__) && defined(__linux__)
/* Copyright 2015 The BoringSSL Authors
*
* 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. */
// Copyright 2015 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* This file is taken from crypto_scalarmult/curve25519/neon2/scalarmult.s in
* SUPERCOP 20141124 (http://bench.cr.yp.to/supercop.html). That code is public
* domain licensed but the standard ISC license is included above to keep
* domain licensed but the standard Apache 2.0 license is included above to keep
* licensing simple. */
#include <CNIOBoringSSL_asm_base.h>
@@ -1,16 +1,16 @@
/* Copyright 2020 The BoringSSL Authors
*
* 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. */
// Copyright 2020 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Some of this code is taken from the ref10 version of Ed25519 in SUPERCOP
// 20141124 (http://bench.cr.yp.to/supercop.html). That code is released as
@@ -22,9 +22,10 @@
#include <assert.h>
#include <string.h>
#include <CNIOBoringSSL_digest.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_rand.h>
#include <CNIOBoringSSL_sha.h>
#include <CNIOBoringSSL_sha2.h>
#include "../internal.h"
#include "internal.h"
@@ -41,6 +42,8 @@
#endif
using namespace bssl;
// Low-level intrinsic operations
static uint64_t load_3(const uint8_t *in) {
@@ -68,7 +71,7 @@ static uint64_t load_4(const uint8_t *in) {
typedef uint64_t fe_limb_t;
#define FE_NUM_LIMBS 5
// assert_fe asserts that |f| satisfies bounds:
// assert_fe asserts that `f` satisfies bounds:
//
// [[0x0 ~> 0x8cccccccccccc],
// [0x0 ~> 0x8cccccccccccc],
@@ -85,7 +88,7 @@ typedef uint64_t fe_limb_t;
} \
} while (0)
// assert_fe_loose asserts that |f| satisfies bounds:
// assert_fe_loose asserts that `f` satisfies bounds:
//
// [[0x0 ~> 0x1a666666666664],
// [0x0 ~> 0x1a666666666664],
@@ -107,7 +110,7 @@ typedef uint64_t fe_limb_t;
typedef uint32_t fe_limb_t;
#define FE_NUM_LIMBS 10
// assert_fe asserts that |f| satisfies bounds:
// assert_fe asserts that `f` satisfies bounds:
//
// [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333],
// [0x0 ~> 0x4666666], [0x0 ~> 0x2333333],
@@ -125,7 +128,7 @@ typedef uint32_t fe_limb_t;
} \
} while (0)
// assert_fe_loose asserts that |f| satisfies bounds:
// assert_fe_loose asserts that `f` satisfies bounds:
//
// [[0x0 ~> 0xd333332], [0x0 ~> 0x6999999],
// [0x0 ~> 0xd333332], [0x0 ~> 0x6999999],
@@ -149,12 +152,14 @@ 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.
// `fiat_25519_from_bytes` requires the top-most bit be clear.
declassify_assert((s[31] & 0x80) == 0);
fiat_25519_from_bytes(h->v, s);
assert_fe(h->v);
}
// fe_frombytes takes in a little-endian 255-bit number and decodes it into an
// `fe`.
static void fe_frombytes(fe *h, const uint8_t s[32]) {
uint8_t s_copy[32];
OPENSSL_memcpy(s_copy, s, 32);
@@ -284,7 +289,7 @@ static void fe_neg(fe_loose *h, const fe *f) {
//
// Preconditions: b in {0,1}.
static void fe_cmov(fe_loose *f, const fe_loose *g, fe_limb_t b) {
// Silence an unused function warning. |fiat_25519_selectznz| isn't quite the
// Silence an unused function warning. `fiat_25519_selectznz` isn't quite the
// calling convention the rest of this code wants, so implement it by hand.
//
// TODO(davidben): Switch to fiat's calling convention, or ask fiat to emit a
@@ -298,6 +303,19 @@ static void fe_cmov(fe_loose *f, const fe_loose *g, fe_limb_t b) {
}
}
// Replace (f,g) with (g,g) if b == 1;
// replace (f,g) with (f,g) if b == 0.
//
// Preconditions: b in {0,1}.
static void fe_cmov(fe *f, const fe *g, fe_limb_t b) {
b = 0 - b;
for (unsigned i = 0; i < FE_NUM_LIMBS; i++) {
fe_limb_t x = f->v[i] ^ g->v[i];
x &= b;
f->v[i] ^= x;
}
}
// h = f
static void fe_copy(fe *h, const fe *f) { OPENSSL_memmove(h, f, sizeof(fe)); }
@@ -372,16 +390,22 @@ static void fe_invert(fe *out, const fe *z) {
// return 0 if f == 0
// return 1 if f != 0
static int fe_isnonzero(const fe_loose *f) {
fe tight;
fe_carry(&tight, f);
static int fe_isnonzero(const fe *f) {
uint8_t s[32];
fe_tobytes(s, &tight);
fe_tobytes(s, f);
static const uint8_t zero[32] = {0};
return CRYPTO_memcmp(s, zero, sizeof(zero)) != 0;
}
// return 0 if f == 0
// return 1 if f != 0
static int fe_isnonzero(const fe_loose *f) {
fe tight;
fe_carry(&tight, f);
return fe_isnonzero(&tight);
}
// return 1 if f is in {1,3,5,...,q-2}
// return 0 if f is in {0,2,4,...,q-1}
static int fe_isnegative(const fe *f) {
@@ -391,7 +415,7 @@ static int fe_isnegative(const fe *f) {
}
static void fe_sq2_tt(fe *h, const fe *f) {
// h = f^2
// h = f²
fe_sq_tt(h, f);
// h = h + h
@@ -460,7 +484,7 @@ static void fe_pow22523(fe *out, const fe *z) {
// Group operations.
void x25519_ge_tobytes(uint8_t s[32], const ge_p2 *h) {
void bssl::x25519_ge_tobytes(uint8_t s[32], const ge_p2 *h) {
fe recip;
fe x;
fe y;
@@ -484,7 +508,7 @@ static void ge_p3_tobytes(uint8_t s[32], const ge_p3 *h) {
s[31] ^= fe_isnegative(&x) << 7;
}
int x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t s[32]) {
int bssl::x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t s[32]) {
fe u;
fe_loose v;
fe w;
@@ -495,9 +519,9 @@ int x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t s[32]) {
fe_1(&h->Z);
fe_sq_tt(&w, &h->Y);
fe_mul_ttt(&vxx, &w, &d);
fe_sub(&v, &w, &h->Z); // u = y^2-1
fe_sub(&v, &w, &h->Z); // u = y² - 1
fe_carry(&u, &v);
fe_add(&v, &vxx, &h->Z); // v = dy^2+1
fe_add(&v, &vxx, &h->Z); // v = dy² + 1
fe_mul_ttl(&w, &u, &v); // w = u*v
fe_pow22523(&h->X, &w); // x = w^((q-5)/8)
@@ -558,7 +582,7 @@ static void ge_p3_to_p2(ge_p2 *r, const ge_p3 *p) {
}
// r = p
void x25519_ge_p3_to_cached(ge_cached *r, const ge_p3 *p) {
void bssl::x25519_ge_p3_to_cached(ge_cached *r, const ge_p3 *p) {
fe_add(&r->YplusX, &p->Y, &p->X);
fe_sub(&r->YminusX, &p->Y, &p->X);
fe_copy_lt(&r->Z, &p->Z);
@@ -566,14 +590,14 @@ void x25519_ge_p3_to_cached(ge_cached *r, const ge_p3 *p) {
}
// r = p
void x25519_ge_p1p1_to_p2(ge_p2 *r, const ge_p1p1 *p) {
void bssl::x25519_ge_p1p1_to_p2(ge_p2 *r, const ge_p1p1 *p) {
fe_mul_tll(&r->X, &p->X, &p->T);
fe_mul_tll(&r->Y, &p->Y, &p->Z);
fe_mul_tll(&r->Z, &p->Z, &p->T);
}
// r = p
void x25519_ge_p1p1_to_p3(ge_p3 *r, const ge_p1p1 *p) {
void bssl::x25519_ge_p1p1_to_p3(ge_p3 *r, const ge_p1p1 *p) {
fe_mul_tll(&r->X, &p->X, &p->T);
fe_mul_tll(&r->Y, &p->Y, &p->Z);
fe_mul_tll(&r->Z, &p->Z, &p->T);
@@ -648,7 +672,7 @@ static void ge_msub(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) {
}
// r = p + q
void x25519_ge_add(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) {
void bssl::x25519_ge_add(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) {
fe trX, trY, trZ, trT;
fe_add(&r->X, &p->Y, &p->X);
@@ -666,7 +690,7 @@ void x25519_ge_add(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) {
}
// r = p - q
void x25519_ge_sub(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) {
void bssl::x25519_ge_sub(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) {
fe trX, trY, trZ, trT;
fe_add(&r->X, &p->Y, &p->X);
@@ -689,16 +713,16 @@ static void cmov(ge_precomp *t, const ge_precomp *u, uint8_t b) {
fe_cmov(&t->xy2d, &u->xy2d, b);
}
void x25519_ge_scalarmult_small_precomp(
void bssl::x25519_ge_scalarmult_small_precomp(
ge_p3 *h, const uint8_t a[32], const uint8_t precomp_table[15 * 2 * 32]) {
// precomp_table is first expanded into matching |ge_precomp|
// precomp_table is first expanded into matching `ge_precomp`
// elements.
ge_precomp multiples[15];
unsigned i;
for (i = 0; i < 15; i++) {
// The precomputed table is assumed to already clear the top bit, so
// |fe_frombytes_strict| may be used directly.
// `fe_frombytes_strict` may be used directly.
const uint8_t *bytes = &precomp_table[i * (2 * 32)];
fe x, y;
fe_frombytes_strict(&x, bytes);
@@ -711,7 +735,7 @@ void x25519_ge_scalarmult_small_precomp(
fe_mul_llt(&out->xy2d, &out->xy2d, &d2);
}
// See the comment above |k25519SmallPrecomp| about the structure of the
// See the comment above `k25519SmallPrecomp` about the structure of the
// precomputed elements. This loop does 64 additions and 64 doublings to
// calculate the result.
ge_p3_0(h);
@@ -745,7 +769,7 @@ void x25519_ge_scalarmult_small_precomp(
#if defined(OPENSSL_SMALL)
void x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) {
void bssl::x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) {
x25519_ge_scalarmult_small_precomp(h, a, k25519SmallPrecomp);
}
@@ -762,7 +786,7 @@ static void table_select(ge_precomp *t, const int pos, const signed char b) {
#if defined(__clang__) // materialize for vectorization, 6% speedup
__asm__("" : "+m"(t_bytes) : /*no inputs*/);
#endif
static_assert(sizeof(t_bytes) == sizeof(k25519Precomp[pos][0]), "");
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),
@@ -791,7 +815,7 @@ static void table_select(ge_precomp *t, const int pos, const signed char b) {
//
// Preconditions:
// a[31] <= 127
void x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) {
void bssl::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()) {
@@ -862,7 +886,8 @@ static void cmov_cached(ge_cached *t, ge_cached *u, uint8_t b) {
// r = scalar * A.
// where a = a[0]+256*a[1]+...+256^31 a[31].
void x25519_ge_scalarmult(ge_p2 *r, const uint8_t *scalar, const ge_p3 *A) {
void bssl::x25519_ge_scalarmult(ge_p2 *r, const uint8_t *scalar,
const ge_p3 *A) {
ge_p2 Ai_p2[8];
ge_cached Ai[16];
ge_p1p1 t;
@@ -1021,9 +1046,9 @@ static void ge_double_scalarmult_vartime(ge_p2 *r, const uint8_t *a,
}
}
// int64_lshift21 returns |a << 21| but is defined when shifting bits into the
// int64_lshift21 returns `a << 21` but is defined when shifting bits into the
// sign bit. This works around a language flaw in C.
static inline int64_t int64_lshift21(int64_t a) {
static int64_t int64_lshift21(int64_t a) {
return (int64_t)((uint64_t)a << 21);
}
@@ -1037,7 +1062,7 @@ static inline int64_t int64_lshift21(int64_t a) {
// s[0]+256*s[1]+...+256^31*s[31] = s mod l
// where l = 2^252 + 27742317777372353535851937790883648493.
// Overwrites s in place.
void x25519_sc_reduce(uint8_t s[64]) {
void bssl::x25519_sc_reduce(uint8_t s[64]) {
int64_t s0 = 2097151 & load_3(s);
int64_t s1 = 2097151 & (load_4(s + 2) >> 5);
int64_t s2 = 2097151 & (load_3(s + 5) >> 2);
@@ -1865,13 +1890,9 @@ void ED25519_keypair(uint8_t out_public_key[32], uint8_t out_private_key[64]) {
ED25519_keypair_from_seed(out_public_key, out_private_key, seed);
}
int ED25519_sign(uint8_t out_sig[64], const uint8_t *message,
size_t message_len, const uint8_t private_key[64]) {
// NOTE: The documentation on this function says that it returns zero on
// allocation failure. While that can't happen with the current
// implementation, we want to reserve the ability to allocate in this
// implementation in the future.
static int ed25519_sign(uint8_t out_sig[64], const uint8_t *hash_prefix,
size_t hash_prefix_len, const uint8_t *message,
size_t message_len, const uint8_t private_key[64]) {
uint8_t az[SHA512_DIGEST_LENGTH];
SHA512(private_key, 32, az);
@@ -1881,6 +1902,7 @@ int ED25519_sign(uint8_t out_sig[64], const uint8_t *message,
SHA512_CTX hash_ctx;
SHA512_Init(&hash_ctx);
SHA512_Update(&hash_ctx, hash_prefix, hash_prefix_len);
SHA512_Update(&hash_ctx, az + 32, 32);
SHA512_Update(&hash_ctx, message, message_len);
uint8_t nonce[SHA512_DIGEST_LENGTH];
@@ -1892,6 +1914,7 @@ int ED25519_sign(uint8_t out_sig[64], const uint8_t *message,
ge_p3_tobytes(out_sig, &R);
SHA512_Init(&hash_ctx);
SHA512_Update(&hash_ctx, hash_prefix, hash_prefix_len);
SHA512_Update(&hash_ctx, out_sig, 32);
SHA512_Update(&hash_ctx, private_key + 32, 32);
SHA512_Update(&hash_ctx, message, message_len);
@@ -1906,8 +1929,10 @@ int ED25519_sign(uint8_t out_sig[64], const uint8_t *message,
return 1;
}
int ED25519_verify(const uint8_t *message, size_t message_len,
const uint8_t signature[64], const uint8_t public_key[32]) {
static int ed25519_verify(const uint8_t *hash_prefix, size_t hash_prefix_len,
const uint8_t *message, size_t message_len,
const uint8_t signature[64],
const uint8_t public_key[32]) {
ge_p3 A;
if ((signature[63] & 224) != 0 ||
!x25519_ge_frombytes_vartime(&A, public_key)) {
@@ -1950,6 +1975,7 @@ int ED25519_verify(const uint8_t *message, size_t message_len,
SHA512_CTX hash_ctx;
SHA512_Init(&hash_ctx);
SHA512_Update(&hash_ctx, hash_prefix, hash_prefix_len);
SHA512_Update(&hash_ctx, signature, 32);
SHA512_Update(&hash_ctx, public_key, 32);
SHA512_Update(&hash_ctx, message, message_len);
@@ -1967,6 +1993,78 @@ int ED25519_verify(const uint8_t *message, size_t message_len,
return CRYPTO_memcmp(rcheck, rcopy, sizeof(rcheck)) == 0;
}
int ED25519_sign(uint8_t out_sig[64], const uint8_t *message,
size_t message_len, const uint8_t private_key[64]) {
// NOTE: The documentation on this function says that it returns zero on
// allocation failure. While that can't happen with the current
// implementation, we want to reserve the ability to allocate in this
// implementation in the future.
return ed25519_sign(out_sig, nullptr, 0, message, message_len, private_key);
}
int ED25519_verify(const uint8_t *message, size_t message_len,
const uint8_t signature[64], const uint8_t public_key[32]) {
return ed25519_verify(nullptr, 0, message, message_len, signature,
public_key);
}
// ED25519_MAX_CONTEXT is the longest context permitted by RFC 8032.
#define ED25519_MAX_CONTEXT 255
#define ED25519_MAX_HASH_PREFIX (32 + 1 + 1 + ED25519_MAX_CONTEXT)
// ed25519_build_hash_prefix implements the `dom2` function from
// https://datatracker.ietf.org/doc/html/rfc8032#section-2
static int ed25519_build_hash_prefix(
uint8_t out_hash_prefix[ED25519_MAX_HASH_PREFIX],
size_t *out_hash_prefix_len, const uint8_t *context, size_t context_len) {
if (context_len > ED25519_MAX_CONTEXT) {
return 0;
}
OPENSSL_memcpy(out_hash_prefix, "SigEd25519 no Ed25519 collisions", 32);
out_hash_prefix[32] = 1;
out_hash_prefix[33] = static_cast<uint8_t>(context_len);
OPENSSL_memcpy(&out_hash_prefix[34], context, context_len);
*out_hash_prefix_len = 32 + 1 + 1 + context_len;
return 1;
}
int ED25519_sign_prehashed(uint8_t out_sig[64], const uint8_t *context,
size_t context_len,
const uint8_t sha512_digest[SHA512_DIGEST_LENGTH],
const uint8_t private_key[64]) {
// NOTE: The documentation on this function says that it returns zero on
// allocation failure. While that can't happen with the current
// implementation, we want to reserve the ability to allocate in this
// implementation in the future.
uint8_t hash_prefix[ED25519_MAX_HASH_PREFIX];
size_t hash_prefix_len;
if (!ed25519_build_hash_prefix(hash_prefix, &hash_prefix_len, context,
context_len)) {
return 0;
}
return ed25519_sign(out_sig, hash_prefix, hash_prefix_len, sha512_digest,
SHA512_DIGEST_LENGTH, private_key);
}
int ED25519_verify_prehashed(const uint8_t *context, size_t context_len,
const uint8_t sha512_digest[SHA512_DIGEST_LENGTH],
const uint8_t signature[64],
const uint8_t public_key[32]) {
uint8_t hash_prefix[ED25519_MAX_HASH_PREFIX];
size_t hash_prefix_len;
if (!ed25519_build_hash_prefix(hash_prefix, &hash_prefix_len, context,
context_len)) {
return 0;
}
return ed25519_verify(hash_prefix, hash_prefix_len, sha512_digest,
SHA512_DIGEST_LENGTH, signature, public_key);
}
void ED25519_keypair_from_seed(uint8_t out_public_key[32],
uint8_t out_private_key[64],
const uint8_t seed[32]) {
@@ -2152,3 +2250,187 @@ void X25519_public_from_private(uint8_t out_public_value[32],
fe_tobytes(out_public_value, &zminusy_inv);
CONSTTIME_DECLASSIFY(out_public_value, 32);
}
static void fe_from_limb(fe *h, fe_limb_t val) {
fe_0(h);
h->v[0] = val;
assert_fe(h->v);
}
// map_to_curve_elligator2 implements the straight-line Elligator 2 mapping
// for Curve25519 from RFC 9380, Appendix G.2.1.
//
// It maps a field element u to a Montgomery point (xn / xd, y / 1) on the curve
// t^2 = s^3 + 486662*s^2 + s.
static void map_to_curve_elligator2(fe *out_xMn, fe *out_xMd, fe *out_yMn,
const fe *u) {
fe one, J_fe, c2_fe;
fe_1(&one);
fe_from_limb(&J_fe, 486662);
// c2 = 2^((p + 3) / 8) mod (2^255 - 19) in little-endian.
constexpr static uint8_t kC2[32] = {
0xb1, 0xa0, 0x0e, 0x4a, 0x27, 0x1b, 0xee, 0xc4, 0x78, 0xe4, 0x2f,
0xad, 0x06, 0x18, 0x43, 0x2f, 0xa7, 0xd7, 0xfb, 0x3d, 0x99, 0x00,
0x4d, 0x2b, 0x0b, 0xdf, 0xc1, 0x4f, 0x80, 0x24, 0x83, 0x2b};
fe_frombytes(&c2_fe, kC2);
// 1-2. tv1 = 2 * u^2
fe tv1;
fe_sq2_tt(&tv1, u);
// 3. xd = tv1 + 1
fe_loose xd_loose;
fe_add(&xd_loose, &tv1, &one);
// 4. x1n = -J
fe_loose x1n_loose;
fe_neg(&x1n_loose, &J_fe);
// 5. tv2 = xd^2
fe tv2;
fe_sq_tl(&tv2, &xd_loose);
// 6. gxd = xd^3
fe gxd;
fe_mul_ttl(&gxd, &tv2, &xd_loose);
fe gx1;
{
fe_loose l_tmp;
// 7. gx1 = J * tv1
fe_mul_ltt(&l_tmp, &J_fe, &tv1);
// 8. gx1 = gx1 * x1n
fe_mul_tll(&gx1, &l_tmp, &x1n_loose);
// 9. gx1 = gx1 + tv2
fe_add(&l_tmp, &gx1, &tv2);
// 10. gx1 = gx1 * x1n
fe_mul_tll(&gx1, &l_tmp, &x1n_loose);
}
fe tv3;
// 11. tv3 = gxd^2
fe_sq_tt(&tv3, &gxd);
// 12. tv2 = tv3^2
fe_sq_tt(&tv2, &tv3);
// 13. tv3 = tv3 * gxd
fe_mul_ttt(&tv3, &tv3, &gxd);
// 14. tv3 = tv3 * gx1
fe_mul_ttt(&tv3, &tv3, &gx1);
// 15. tv2 = tv2 * tv3
fe_mul_ttt(&tv2, &tv2, &tv3);
// 16. y11 = tv2^c4 = (gx1 * gxd^7)^((p - 5) / 8)
fe y11;
fe_pow22523(&y11, &tv2);
// 17. y11 = y11 * tv3
fe_mul_ttt(&y11, &y11, &tv3);
// 18. y12 = y11 * c3
fe y12;
fe_mul_ttt(&y12, &y11, &sqrtm1);
// 19. tv2 = y11 ^ 2
fe_sq_tt(&tv2, &y11);
// 20. tv2 = tv2 * gxd
fe_mul_ttt(&tv2, &tv2, &gxd);
// 21. e1 = tv2 == gx1
fe_limb_t e1;
{
fe_loose l_tmp;
fe_sub(&l_tmp, &tv2, &gx1);
e1 = 1 - fe_isnonzero(&l_tmp);
}
// 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt
fe y1;
fe_copy(&y1, &y12);
fe_cmov(&y1, &y11, e1);
// 23. x2n = x1n * tv1
fe x2n;
fe_mul_ttl(&x2n, &tv1, &x1n_loose);
// 24. y21 = y11 * u
fe y21;
fe_mul_ttt(&y21, &y11, u);
// 25. y21 = y21 * c2
fe_mul_ttt(&y21, &y21, &c2_fe);
// 26. y22 = y21 * c3
fe y22;
fe_mul_ttt(&y22, &y21, &sqrtm1);
// 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)
fe gx2;
fe_mul_ttt(&gx2, &gx1, &tv1);
// 28. tv2 = y21^2
fe_sq_tt(&tv2, &y21);
// 29. tv2 = tv2 * gxd
fe_mul_ttt(&tv2, &tv2, &gxd);
// 30. e2 = tv2 == gx2
fe_limb_t e2;
{
fe_loose l_tmp;
fe_sub(&l_tmp, &tv2, &gx2);
e2 = 1 - fe_isnonzero(&l_tmp);
}
// 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt
fe y2;
fe_copy(&y2, &y22);
fe_cmov(&y2, &y21, e2);
// 32. tv2 = y1^2
fe_sq_tt(&tv2, &y1);
// 33. tv2 = tv2 * gxd
fe_mul_ttt(&tv2, &tv2, &gxd);
// 34. e3 = tv2 == gx1
fe_limb_t e3;
{
fe_loose l_tmp;
fe_sub(&l_tmp, &tv2, &gx1);
e3 = 1 - fe_isnonzero(&l_tmp);
}
fe xn, y;
// 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2
// or xn = CMOV(x1n, x2n, 1 - e3)
fe_carry(&xn, &x1n_loose);
fe_cmov(&xn, &x2n, 1 - e3);
// 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2
fe_copy(&y, &y2);
fe_cmov(&y, &y1, e3);
// 37. e4 = sgn0(y) == 1 # Fix sign of y
fe_limb_t e4 = fe_isnegative(&y);
fe negy;
{
fe_loose l_tmp;
fe_neg(&l_tmp, &y);
fe_carry(&negy, &l_tmp);
}
// 38. y = CMOV(y, -y, e3 XOR e4)
fe_cmov(&y, &negy, e3 ^ e4);
// 39. return (xn, xd, y, /* 1 */)
fe_copy(out_xMn, &xn);
fe_carry(out_xMd, &xd_loose);
fe_copy(out_yMn, &y);
}
void bssl::map_to_curve_curve25519_elligator2(uint8_t out_qx[32],
uint8_t out_qy[32],
const uint8_t u[32]) {
fe u_fe;
fe_frombytes(&u_fe, u);
fe xMn, xMd, yMn;
map_to_curve_elligator2(&xMn, &xMd, &yMn, &u_fe);
fe xMd_inv, qx;
fe_invert(&xMd_inv, &xMd);
fe_mul_ttt(&qx, &xMn, &xMd_inv);
fe_tobytes(out_qx, &qx);
fe_tobytes(out_qy, &yMn);
}
@@ -1,16 +1,16 @@
/* Copyright 2023 The BoringSSL Authors
*
* 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. */
// Copyright 2023 The BoringSSL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal.h"
#if defined(BORINGSSL_FE25519_ADX)
Loaded 100 of 717 files, more files were not shown because too many files have changed in this diff. Show more