chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

View File

@@ -0,0 +1,335 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR ISC
#include <gtest/gtest.h>
#include <openssl/crypto.h>
#include <openssl/mem.h>
#include <openssl/x509.h>
#include "../../test/test_util.h"
#include "../internal.h"
// NOTE: need to keep this in sync with sizeof(ctx->buf) cipher.c
#define ENC_BLOCK_SIZE 1024 * 4
struct CipherParams {
const char name[40];
const EVP_CIPHER *(*cipher)(void);
};
static const struct CipherParams Ciphers[] = {
{"AES_128_CBC", EVP_aes_128_cbc},
{"AES_128_CTR", EVP_aes_128_ctr},
{"AES_128_OFB", EVP_aes_128_ofb},
{"AES_256_CBC", EVP_aes_256_cbc},
{"AES_256_CTR", EVP_aes_256_ctr},
{"AES_256_OFB", EVP_aes_256_ofb},
{"ChaCha20Poly1305", EVP_chacha20_poly1305},
{"DES_EDE3_CBC", EVP_des_ede3_cbc},
};
class BIOCipherTest : public testing::TestWithParam<CipherParams> {};
INSTANTIATE_TEST_SUITE_P(PKCS7Test, BIOCipherTest, testing::ValuesIn(Ciphers),
[](const testing::TestParamInfo<CipherParams> &params)
-> std::string { return params.param.name; });
TEST_P(BIOCipherTest, Basic) {
uint8_t key[EVP_MAX_KEY_LENGTH];
uint8_t iv[EVP_MAX_IV_LENGTH];
uint8_t pt[ENC_BLOCK_SIZE * 2];
uint8_t pt_decrypted[sizeof(pt)];
uint8_t ct[sizeof(pt) + EVP_MAX_BLOCK_LENGTH]; // pt + pad
bssl::UniquePtr<BIO> bio_cipher;
bssl::UniquePtr<BIO> bio_mem;
std::vector<uint8_t> pt_vec, ct_vec, decrypted_pt_vec;
uint8_t buff[2 * sizeof(pt)];
const EVP_CIPHER *cipher = GetParam().cipher();
ASSERT_TRUE(cipher);
OPENSSL_cleanse(buff, sizeof(buff));
OPENSSL_cleanse(ct, sizeof(ct));
OPENSSL_cleanse(pt_decrypted, sizeof(pt_decrypted));
OPENSSL_memset(pt, 'A', sizeof(pt));
OPENSSL_memset(key, 'B', sizeof(key));
OPENSSL_memset(iv, 'C', sizeof(iv));
// Unsupported or unimplemented CTRL flags and cipher(s)
bio_cipher.reset(BIO_new(BIO_f_cipher()));
ASSERT_TRUE(bio_cipher);
EXPECT_FALSE(BIO_ctrl(bio_cipher.get(), BIO_CTRL_DUP, 0, NULL));
EXPECT_FALSE(BIO_ctrl(bio_cipher.get(), BIO_CTRL_GET_CALLBACK, 0, NULL));
EXPECT_FALSE(BIO_ctrl(bio_cipher.get(), BIO_CTRL_SET_CALLBACK, 0, NULL));
EXPECT_FALSE(BIO_ctrl(bio_cipher.get(), BIO_C_DO_STATE_MACHINE, 0, NULL));
EXPECT_FALSE(BIO_ctrl(bio_cipher.get(), BIO_C_GET_CIPHER_CTX, 0, NULL));
EXPECT_FALSE(BIO_ctrl(bio_cipher.get(), BIO_C_SSL_MODE, 0, NULL));
EXPECT_FALSE(BIO_set_cipher(bio_cipher.get(), EVP_rc4(), key, iv, /*enc*/ 1));
ASSERT_TRUE(BIO_set_cipher(bio_cipher.get(), cipher, key, iv, /*enc*/ 1));
// Round-trip using |BIO_write| for encryption with same BIOs, reset between
// encryption/decryption using |BIO_reset|. Fixed size IO.
bio_cipher.reset(BIO_new(BIO_f_cipher()));
ASSERT_TRUE(bio_cipher);
EXPECT_TRUE(BIO_set_cipher(bio_cipher.get(), cipher, key, iv, /*enc*/ 1));
bio_mem.reset(BIO_new(BIO_s_mem()));
ASSERT_TRUE(bio_mem);
ASSERT_TRUE(BIO_push(bio_cipher.get(), bio_mem.get()));
// Copy |pt| contents to |ct| so we can detect that |ct| gets overwritten
OPENSSL_memcpy(ct, pt, sizeof(pt));
OPENSSL_cleanse(pt_decrypted, sizeof(pt_decrypted));
EXPECT_TRUE(BIO_eof(bio_cipher.get()));
EXPECT_EQ(0UL, BIO_wpending(bio_cipher.get()));
EXPECT_TRUE(BIO_write(bio_cipher.get(), pt, sizeof(pt)));
EXPECT_FALSE(BIO_eof(bio_cipher.get()));
EXPECT_EQ(0UL, BIO_wpending(bio_cipher.get()));
EXPECT_TRUE(BIO_flush(bio_cipher.get()));
EXPECT_EQ(0UL, BIO_wpending(bio_cipher.get()));
EXPECT_TRUE(BIO_get_cipher_status(bio_cipher.get()));
int ct_size = BIO_read(bio_mem.get(), ct, sizeof(ct));
ASSERT_LE((size_t)ct_size, sizeof(ct));
// first block should now differ
EXPECT_NE(Bytes(pt, EVP_MAX_BLOCK_LENGTH), Bytes(ct, EVP_MAX_BLOCK_LENGTH));
// Reset both BIOs and decrypt
EXPECT_TRUE(BIO_reset(bio_cipher.get())); // also resets owned |bio_mem|
EXPECT_TRUE(BIO_write(bio_mem.get(), ct, ct_size));
bio_mem.release(); // |bio_cipher| took ownership
EXPECT_TRUE(BIO_set_cipher(bio_cipher.get(), cipher, key, iv, /*enc*/ 0));
EXPECT_TRUE(BIO_read(bio_cipher.get(), pt_decrypted, sizeof(pt_decrypted)));
EXPECT_TRUE(BIO_get_cipher_status(bio_cipher.get()));
EXPECT_EQ(Bytes(pt, sizeof(pt)), Bytes(pt_decrypted, sizeof(pt_decrypted)));
// Test a number of different IO sizes around byte, cipher block,
// internal buffer size, and other boundaries.
int io_sizes[] = {1,
3,
7,
8,
9,
64,
923,
sizeof(pt),
15,
16,
17,
31,
32,
33,
511,
512,
513,
1023,
1024,
1025,
ENC_BLOCK_SIZE - 1,
ENC_BLOCK_SIZE,
ENC_BLOCK_SIZE + 1};
// Round-trip encryption/decryption with successive IOs of different sizes.
bio_cipher.reset(BIO_new(BIO_f_cipher()));
ASSERT_TRUE(bio_cipher);
EXPECT_TRUE(BIO_set_cipher(bio_cipher.get(), cipher, key, iv, /*enc*/ 1));
bio_mem.reset(BIO_new(BIO_s_mem()));
ASSERT_TRUE(bio_mem);
ASSERT_TRUE(BIO_push(bio_cipher.get(), bio_mem.get()));
for (size_t wsize : io_sizes) {
pt_vec.insert(pt_vec.end(), pt, pt + wsize);
EXPECT_TRUE(BIO_write(bio_cipher.get(), pt, wsize));
}
EXPECT_TRUE(BIO_flush(bio_cipher.get()));
EXPECT_TRUE(BIO_get_cipher_status(bio_cipher.get()));
while (!BIO_eof(bio_mem.get())) {
size_t bytes_read = BIO_read(bio_mem.get(), buff, sizeof(buff));
ct_vec.insert(ct_vec.end(), buff, buff + bytes_read);
}
EXPECT_TRUE(BIO_reset(bio_cipher.get())); // also resets owned |bio_mem|
EXPECT_TRUE(
BIO_write(bio_mem.get(), ct_vec.data(), ct_vec.size())); // replace ct
bio_mem.release(); // |bio_cipher| took ownership
EXPECT_TRUE(BIO_set_cipher(bio_cipher.get(), cipher, key, iv, /*enc*/ 0));
for (size_t rsize : io_sizes) {
EXPECT_TRUE(BIO_read(bio_cipher.get(), buff, rsize));
decrypted_pt_vec.insert(decrypted_pt_vec.end(), buff, buff + rsize);
}
EXPECT_TRUE(BIO_get_cipher_status(bio_cipher.get()));
EXPECT_EQ(pt_vec.size(), decrypted_pt_vec.size());
EXPECT_EQ(Bytes(pt_vec.data(), pt_vec.size()),
Bytes(decrypted_pt_vec.data(), decrypted_pt_vec.size()));
// Induce IO failures in the underlying BIO between subsequent same-size
// operations. The flow of this test is to, for each IO size:
//
// 1. Write/encrypt a chunk of plaintext.
// 2. Disable writes in the underlying BIO and try to write the same plaintext
// chunk again. depending on how large the write size relative to cipher
// BIO's internal buffer size, the write may partially or fully succeed if
// it can be buffered.
// 3. Enable writes in the underlying BIO and complete 2.'s chunk by writing
// any remaining bytes in the chunk
// 4. Flush the cipher BIO to complete the encryption, reset the cipher BIO in
// decrypt mode with the underlying BIO containing the ciphertext.
// 5. Similar to 1., read/decrypt a chunk of ciphertext.
// 6. Similar to 2., disable reads in the underlying BIO. As with 2., this may
// partially or fully succeed depending on how large the read is relative
// to internal buffer sizes.
// 7. Enable reads in the underlying BIO and decrypt the rest of the
// ciphertext.
// 8. Compare original and decrypted plaintexts.
int rsize, wsize;
for (int io_size : io_sizes) {
pt_vec.clear();
decrypted_pt_vec.clear();
bio_cipher.reset(BIO_new(BIO_f_cipher()));
ASSERT_TRUE(bio_cipher);
EXPECT_TRUE(BIO_set_cipher(bio_cipher.get(), cipher, key, iv, /*enc*/ 1));
bio_mem.reset(BIO_new(BIO_s_mem()));
ASSERT_TRUE(bio_mem);
ASSERT_TRUE(BIO_push(bio_cipher.get(), bio_mem.get()));
// Initial write should fully succeed
wsize = BIO_write(bio_cipher.get(), pt, io_size);
if (wsize > 0) {
pt_vec.insert(pt_vec.end(), pt, pt + wsize);
}
EXPECT_EQ(io_size, wsize);
// All data should have been written through to underlying BIO
EXPECT_EQ(0UL, BIO_wpending(bio_cipher.get()));
// Set underlying BIO to r/o to induce buffering in |bio_cipher|
auto disable_writes = [](BIO *bio, int oper, const char *argp, size_t len,
int argi, long argl, int bio_ret,
size_t *processed) -> long {
return (oper & BIO_CB_RETURN) || !(oper & BIO_CB_WRITE);
};
BIO_set_callback_ex(bio_mem.get(), disable_writes);
BIO_set_retry_write(bio_mem.get());
int full_buffer = ENC_BLOCK_SIZE;
// EVP block ciphers need up to EVP_MAX_BLOCK_LENGTH-1 bytes reserved
if (EVP_CIPHER_block_size(cipher) > 1) {
full_buffer -= EVP_CIPHER_block_size(cipher) - 1;
}
// Write to |bio_cipher| should still succeed in writing up to
// ENC_BLOCK_SIZE bytes by buffering them
wsize = BIO_write(bio_cipher.get(), pt, io_size);
if (wsize > 0) {
pt_vec.insert(pt_vec.end(), pt, pt + wsize);
}
// First write succeeds due to write buffering up to |ENC_BLOCK_SIZE| bytes
if (io_size >= full_buffer) {
EXPECT_EQ(full_buffer, wsize);
} else {
EXPECT_GT(full_buffer, wsize);
}
// If buffer is full, writes will fail
if (BIO_wpending(bio_cipher.get()) >= (size_t)full_buffer) {
EXPECT_FALSE(BIO_write(bio_cipher.get(), pt, sizeof(pt)));
}
// Writes still disabled, so flush fails and we have data pending
EXPECT_FALSE(BIO_flush(bio_cipher.get()));
EXPECT_GT(BIO_wpending(bio_cipher.get()), 0UL);
// Re-enable writes
BIO_set_callback_ex(bio_mem.get(), nullptr);
BIO_clear_retry_flags(bio_mem.get());
if (wsize < io_size) {
const int remaining = io_size - wsize;
ASSERT_EQ(remaining, BIO_write(bio_cipher.get(), pt, remaining));
pt_vec.insert(pt_vec.end(), pt, pt + remaining);
}
// Flush should empty the buffered encrypted data
EXPECT_TRUE(BIO_flush(bio_cipher.get()));
EXPECT_EQ(0UL, BIO_wpending(bio_cipher.get()));
EXPECT_TRUE(BIO_get_cipher_status(bio_cipher.get()));
EXPECT_TRUE(BIO_set_cipher(bio_cipher.get(), cipher, key, iv, /*enc*/ 0));
// Reset BIOs, hydrate ciphertext for decryption
ct_vec.clear();
while ((rsize = BIO_read(bio_mem.get(), buff, io_size)) > 0) {
ct_vec.insert(ct_vec.end(), buff, buff + rsize);
}
EXPECT_TRUE(BIO_reset(bio_cipher.get())); // also resets owned |bio_mem|
ASSERT_EQ((int)ct_vec.size(), BIO_write(bio_mem.get(), ct_vec.data(),
ct_vec.size())); // replace ct
EXPECT_LE(pt_vec.size(), BIO_pending(bio_cipher.get()));
// First read should fully succeed
rsize = BIO_read(bio_cipher.get(), buff, io_size);
ASSERT_EQ(io_size, rsize);
decrypted_pt_vec.insert(decrypted_pt_vec.end(), buff, buff + rsize);
// Disable reads from underlying BIO
auto disable_reads = [](BIO *bio, int oper, const char *argp, size_t len,
int argi, long argl, int bio_ret,
size_t *processed) -> long {
return (oper & BIO_CB_RETURN) || !(oper & BIO_CB_READ);
};
BIO_set_callback_ex(bio_mem.get(), disable_reads);
// Set retry flags so |cipher_bio| doesn't give up when the read fails
BIO_set_retry_read(bio_mem.get());
rsize = BIO_read(bio_cipher.get(), buff, io_size);
decrypted_pt_vec.insert(decrypted_pt_vec.end(), buff, buff + rsize);
EXPECT_EQ(0UL, BIO_pending(bio_cipher.get()));
// Re-enable reads from underlying BIO
BIO_set_callback_ex(bio_mem.get(), nullptr);
BIO_clear_retry_flags(bio_mem.get());
while ((rsize = BIO_read(bio_cipher.get(), buff, io_size)) > 0) {
decrypted_pt_vec.insert(decrypted_pt_vec.end(), buff, buff + rsize);
}
EXPECT_TRUE(BIO_eof(bio_cipher.get()));
EXPECT_EQ(0UL, BIO_pending(bio_cipher.get()));
EXPECT_TRUE(BIO_get_cipher_status(bio_cipher.get()));
EXPECT_EQ(pt_vec.size(), decrypted_pt_vec.size());
EXPECT_EQ(Bytes(pt_vec.data(), pt_vec.size()),
Bytes(decrypted_pt_vec.data(), decrypted_pt_vec.size()));
bio_mem.release(); // |bio_cipher| took ownership
}
}
TEST_P(BIOCipherTest, Randomized) {
uint8_t key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], buff[8 * 1024];
bssl::UniquePtr<BIO> bio_cipher, bio_mem;
std::vector<uint8_t> pt, ct, decrypted;
const EVP_CIPHER *cipher = GetParam().cipher();
ASSERT_TRUE(cipher);
OPENSSL_memset(key, 'X', sizeof(key));
OPENSSL_memset(iv, 'Y', sizeof(iv));
for (int i = 0; i < (int)sizeof(buff); i++) {
int n = i % 16;
char c = n < 10 ? '0' + n : 'A' + (n - 10);
buff[i] = c;
}
// Round-trip using |BIO_write| for encryption with same BIOs, reset between
// encryption/decryption using |BIO_reset|. Fixed size IO.
bio_cipher.reset(BIO_new(BIO_f_cipher()));
BIO_set_cipher(bio_cipher.get(), cipher, key, iv, /*enc*/ 1);
bio_mem.reset(BIO_new(BIO_s_mem()));
BIO_push(bio_cipher.get(), bio_mem.get());
int total_bytes = 0;
srand(42);
for (int i = 0; i < 1000; i++) {
int n = (rand() % (sizeof(buff) - 1)) + 1; // NOLINT(clang-analyzer-security.insecureAPI.rand)
ASSERT_TRUE(BIO_write(bio_cipher.get(), buff, n));
pt.insert(pt.end(), buff, buff + n);
total_bytes += n;
}
EXPECT_TRUE(BIO_flush(bio_cipher.get()));
EXPECT_TRUE(BIO_get_cipher_status(bio_cipher.get()));
int rsize;
while ((rsize = BIO_read(bio_mem.get(), buff, sizeof(buff))) > 0) {
ct.insert(ct.end(), buff, buff + rsize);
}
// only consider first |pt.size()| bytes of |ct|, exclude pad block
EXPECT_NE(Bytes(pt.data(), pt.size()), Bytes(ct.data(), pt.size()));
// Reset both BIOs and decrypt
EXPECT_TRUE(BIO_reset(bio_cipher.get())); // also resets owned |bio_mem|
EXPECT_TRUE(BIO_write(bio_mem.get(), ct.data(), ct.size()));
bio_mem.release(); // |bio_cipher| took ownership
EXPECT_TRUE(BIO_set_cipher(bio_cipher.get(), cipher, key, iv, /*enc*/ 0));
EXPECT_FALSE(BIO_eof(bio_cipher.get()));
while ((rsize = BIO_read(bio_cipher.get(), buff, sizeof(buff))) > 0) {
decrypted.insert(decrypted.end(), buff, buff + rsize);
}
EXPECT_TRUE(BIO_eof(bio_cipher.get()));
EXPECT_TRUE(BIO_get_cipher_status(bio_cipher.get()));
EXPECT_EQ(Bytes(pt.data(), pt.size()),
Bytes(decrypted.data(), decrypted.size()));
EXPECT_EQ(total_bytes, (int)decrypted.size());
}

View File

@@ -0,0 +1,331 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR ISC
#include <openssl/buffer.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/mem.h>
#include <openssl/pkcs7.h>
#include <stdio.h>
#include "../../fipsmodule/cipher/internal.h"
#include "../internal.h"
typedef struct enc_struct {
uint8_t done; // indicates "EOF" for read, "flushed" for write
uint8_t ok; // cipher status, either 0 (error) or 1 (ok)
int buf_off; // start idx of buffered data
int buf_len; // length of buffered data
EVP_CIPHER_CTX *cipher;
uint8_t buf[1024 * 4]; // plaintext for read, ciphertext for writes
} BIO_ENC_CTX;
static int enc_new(BIO *b) {
BIO_ENC_CTX *ctx;
GUARD_PTR(b);
if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) {
return 0;
}
ctx->cipher = EVP_CIPHER_CTX_new();
if (ctx->cipher == NULL) {
OPENSSL_free(ctx);
return 0;
}
ctx->done = 0;
ctx->ok = 1;
ctx->buf_off = 0;
ctx->buf_len = 0;
BIO_set_data(b, ctx);
BIO_set_init(b, 1);
return 1;
}
static int enc_free(BIO *b) {
GUARD_PTR(b);
BIO_ENC_CTX *ctx = BIO_get_data(b);
if (ctx == NULL) {
return 0;
}
EVP_CIPHER_CTX_free(ctx->cipher);
OPENSSL_free(ctx);
BIO_set_data(b, NULL);
BIO_set_init(b, 0);
return 1;
}
static int enc_read(BIO *b, char *out, int outl) {
GUARD_PTR(b);
GUARD_PTR(out);
BIO_ENC_CTX *ctx = BIO_get_data(b);
if (ctx == NULL || ctx->cipher == NULL || !ctx->ok || outl <= 0) {
return 0;
}
BIO *next = BIO_next(b);
if (next == NULL) {
return 0;
}
int bytes_output = 0;
int remaining = outl;
uint8_t read_buf[sizeof(ctx->buf)];
const int cipher_block_size = EVP_CIPHER_CTX_block_size(ctx->cipher);
while ((!ctx->done || ctx->buf_len > 0) && remaining > 0) {
assert(bytes_output + remaining == outl);
if (ctx->buf_len > 0) {
uint8_t *out_pos = ((uint8_t *)out) + bytes_output;
int to_copy = remaining > ctx->buf_len ? ctx->buf_len : remaining;
OPENSSL_memcpy(out_pos, &ctx->buf[ctx->buf_off], to_copy);
// Update buffer info and counters with number of bytes processed from our
// buffer.
ctx->buf_len -= to_copy;
ctx->buf_off += to_copy;
bytes_output += to_copy;
remaining -= to_copy;
continue;
}
ctx->buf_len = 0;
ctx->buf_off = 0;
// |EVP_DecryptUpdate| may write up to cipher_block_size-1 more bytes than
// requested, so only read bytes we're sure we can decrypt in place.
int to_read = (int)sizeof(ctx->buf) - cipher_block_size + 1;
int bytes_read = BIO_read(next, read_buf, to_read);
if (bytes_read > 0) {
// Decrypt ciphertext in place, update |ctx->buf_len| with num bytes
// decrypted.
ctx->ok = EVP_DecryptUpdate(ctx->cipher, ctx->buf, &ctx->buf_len,
read_buf, bytes_read);
} else if (BIO_eof(next)) {
// EVP_DecryptFinal_ex may write up to one block to our buffer. If that
// happens, continue the loop to process the decrypted block as normal.
ctx->ok = EVP_DecryptFinal_ex(ctx->cipher, ctx->buf, &ctx->buf_len);
ctx->done = 1; // If we can't read any more bytes, set done.
} else {
// |BIO_read| returned <= 0, but no EOF. Copy retry and return.
if (bytes_read < 0 && !BIO_should_retry(next)) {
ctx->done = 1;
ctx->ok = 0;
}
BIO_copy_next_retry(b);
break;
}
if (!ctx->ok) {
ctx->done = 1; // Set EOF on cipher error.
}
}
return bytes_output;
}
static int enc_flush(BIO *b, BIO *next, BIO_ENC_CTX *ctx) {
GUARD_PTR(b);
GUARD_PTR(next);
GUARD_PTR(ctx);
while (ctx->ok > 0 && (ctx->buf_len > 0 || !ctx->done)) {
int bytes_written = BIO_write(next, &ctx->buf[ctx->buf_off], ctx->buf_len);
if (ctx->buf_len > 0 && bytes_written <= 0) {
if (bytes_written < 0 && !BIO_should_retry(next)) {
ctx->done = 1;
ctx->ok = 0;
}
BIO_copy_next_retry(b);
return 0;
}
ctx->buf_off += bytes_written;
ctx->buf_len -= bytes_written;
if (ctx->buf_len == 0 && !ctx->done) {
ctx->done = 1;
ctx->buf_off = 0;
ctx->ok = EVP_EncryptFinal_ex(ctx->cipher, ctx->buf, &ctx->buf_len);
}
}
return ctx->ok;
}
static int enc_write(BIO *b, const char *in, int inl) {
GUARD_PTR(b);
GUARD_PTR(in);
BIO_ENC_CTX *ctx = BIO_get_data(b);
if (ctx == NULL || ctx->cipher == NULL || ctx->done || !ctx->ok || inl <= 0) {
return 0;
}
BIO *next = BIO_next(b);
if (next == NULL) {
return 0;
}
int bytes_consumed = 0;
int remaining = inl;
const int max_crypt_size =
(int)sizeof(ctx->buf) - EVP_CIPHER_CTX_block_size(ctx->cipher) + 1;
while ((!ctx->done || ctx->buf_len > 0) && remaining > 0) {
assert(bytes_consumed + remaining == inl);
if (ctx->buf_len == 0) {
ctx->buf_off = 0;
int to_encrypt = remaining < max_crypt_size ? remaining : max_crypt_size;
uint8_t *in_pos = ((uint8_t *)in) + bytes_consumed;
ctx->ok = EVP_EncryptUpdate(ctx->cipher, ctx->buf, &ctx->buf_len, in_pos,
to_encrypt);
if (!ctx->ok) {
break;
};
bytes_consumed += to_encrypt;
remaining -= to_encrypt;
}
int bytes_written = BIO_write(next, &ctx->buf[ctx->buf_off], ctx->buf_len);
if (bytes_written <= 0) {
if (bytes_written < 0 && !BIO_should_retry(next)) {
ctx->done = 1;
ctx->ok = 0;
}
BIO_copy_next_retry(b);
break;
}
ctx->buf_off += bytes_written;
ctx->buf_len -= bytes_written;
}
return bytes_consumed;
}
static long enc_ctrl(BIO *b, int cmd, long num, void *ptr) {
GUARD_PTR(b);
long ret = 1;
BIO_ENC_CTX *ctx = BIO_get_data(b);
EVP_CIPHER_CTX **cipher_ctx;
BIO *next = BIO_next(b);
if (ctx == NULL) {
return 0;
}
switch (cmd) {
case BIO_CTRL_RESET:
ctx->done = 0;
ctx->ok = 1;
ctx->buf_off = 0;
ctx->buf_len = 0;
OPENSSL_cleanse(ctx->buf, sizeof(ctx->buf));
if (!EVP_CipherInit_ex(ctx->cipher, NULL, NULL, NULL, NULL,
EVP_CIPHER_CTX_encrypting(ctx->cipher))) {
return 0;
}
ret = BIO_ctrl(next, cmd, num, ptr);
break;
case BIO_CTRL_EOF:
if (ctx->done) {
ret = 1;
} else {
ret = BIO_ctrl(next, cmd, num, ptr);
}
break;
case BIO_CTRL_WPENDING:
case BIO_CTRL_PENDING:
// Return number of bytes left to process if we have anything buffered,
// else consult underlying BIO.
ret = ctx->buf_len;
if (ret <= 0) {
ret = BIO_ctrl(next, cmd, num, ptr);
}
break;
case BIO_CTRL_FLUSH:
ret = enc_flush(b, next, ctx);
if (ret <= 0) {
break;
}
// Flush the underlying BIO
ret = BIO_ctrl(next, cmd, num, ptr);
BIO_copy_next_retry(b);
break;
case BIO_C_GET_CIPHER_STATUS:
ret = (long)ctx->ok;
break;
case BIO_C_GET_CIPHER_CTX:
cipher_ctx = (EVP_CIPHER_CTX **)ptr;
if (!cipher_ctx) {
ret = 0;
break;
}
*cipher_ctx = ctx->cipher;
BIO_set_init(b, 1);
break;
// OpenSSL implements these, but because we don't need them and cipher BIO
// is internal, we can fail loudly if they're called. If this case is hit,
// it likely means you're making a change that will require implementing
// these.
case BIO_CTRL_DUP:
case BIO_CTRL_GET_CALLBACK:
case BIO_CTRL_SET_CALLBACK:
case BIO_C_DO_STATE_MACHINE:
OPENSSL_PUT_ERROR(PKCS7, ERR_R_BIO_LIB);
return 0;
default:
ret = BIO_ctrl(next, cmd, num, ptr);
break;
}
return ret;
}
int BIO_set_cipher(BIO *b, const EVP_CIPHER *c, const unsigned char *key,
const unsigned char *iv, int enc) {
GUARD_PTR(b);
GUARD_PTR(c);
BIO_ENC_CTX *ctx = BIO_get_data(b);
if (ctx == NULL) {
return 0;
}
// We only support a modern subset of available EVP_CIPHERs. Other ciphers
// (e.g. DES) and cipher modes (e.g. CBC, CCM) had issues with block alignment
// and padding during testing, so they're forbidden for now.
const EVP_CIPHER *kSupportedCiphers[] = {
EVP_aes_128_cbc(), EVP_aes_128_ctr(), EVP_aes_128_ofb(),
EVP_aes_256_cbc(), EVP_aes_256_ctr(), EVP_aes_256_ofb(),
EVP_chacha20_poly1305(), EVP_des_ede3_cbc(),
};
const size_t kSupportedCiphersCount =
sizeof(kSupportedCiphers) / sizeof(EVP_CIPHER *);
int supported = 0;
for (size_t i = 0; i < kSupportedCiphersCount; i++) {
if (c == kSupportedCiphers[i]) {
supported = 1;
break;
}
}
if (!supported) {
OPENSSL_PUT_ERROR(PKCS7, ERR_R_BIO_LIB);
return 0;
}
if (!EVP_CipherInit_ex(ctx->cipher, c, NULL, key, iv, enc)) {
return 0;
}
BIO_set_init(b, 1);
return 1;
}
static const BIO_METHOD methods_enc = {
BIO_TYPE_CIPHER, // type
"cipher", // name
enc_write, // bwrite
enc_read, // bread
NULL, // bputs
NULL, // bgets
enc_ctrl, // ctrl
enc_new, // create
enc_free, // destroy
NULL, // callback_ctrl
};
const BIO_METHOD *BIO_f_cipher(void) { return &methods_enc; }
int BIO_get_cipher_ctx(BIO *b, EVP_CIPHER_CTX **ctx) {
return BIO_ctrl(b, BIO_C_GET_CIPHER_CTX, 0, ctx);
}
int BIO_get_cipher_status(BIO *b) {
return BIO_ctrl(b, BIO_C_GET_CIPHER_STATUS, 0, NULL);
}

View File

@@ -0,0 +1,126 @@
// Copyright (c) 2017, Google Inc.
// SPDX-License-Identifier: ISC
#ifndef OPENSSL_HEADER_PKCS7_INTERNAL_H
#define OPENSSL_HEADER_PKCS7_INTERNAL_H
#include <openssl/base.h>
#if defined(__cplusplus)
extern "C" {
#endif
DECLARE_ASN1_FUNCTIONS(PKCS7_ISSUER_AND_SERIAL)
DECLARE_ASN1_FUNCTIONS(PKCS7_SIGNED)
DECLARE_ASN1_FUNCTIONS(PKCS7_ENC_CONTENT)
DECLARE_ASN1_FUNCTIONS(PKCS7_ENCRYPT)
DECLARE_ASN1_FUNCTIONS(PKCS7_ENVELOPE)
DECLARE_ASN1_FUNCTIONS(PKCS7_DIGEST)
DECLARE_ASN1_FUNCTIONS(PKCS7_SIGN_ENVELOPE)
DECLARE_ASN1_ITEM(PKCS7_ATTR_VERIFY)
DEFINE_STACK_OF(PKCS7)
// ASN.1 defined here https://datatracker.ietf.org/doc/html/rfc2315#section-10.1
//
// EncryptedContentInfo ::= SEQUENCE {
// contentType ContentType,
// contentEncryptionAlgorithm
// ContentEncryptionAlgorithmIdentifier,
// encryptedContent
// [0] IMPLICIT EncryptedContent OPTIONAL }
//
// EncryptedContent ::= OCTET STRING
struct pkcs7_enc_content_st {
ASN1_OBJECT *content_type;
X509_ALGOR *algorithm;
ASN1_OCTET_STRING *enc_data;
const EVP_CIPHER *cipher; // NOTE: |cipher| is not serialized
};
// ASN.1 defined here https://datatracker.ietf.org/doc/html/rfc2315#section-12
//
// DigestedData ::= SEQUENCE {
// version Version,
// digestAlgorithm DigestAlgorithmIdentifier,
// contentInfo ContentInfo,
// digest Digest }
//
// Digest ::= OCTET STRING
struct pkcs7_digest_st {
ASN1_INTEGER *version;
X509_ALGOR *digest_alg;
PKCS7 *contents;
ASN1_OCTET_STRING *digest;
const EVP_MD *md; // NOTE: |md| is not serialized
};
// ASN.1 defined here https://datatracker.ietf.org/doc/html/rfc2315#section-13
//
// EncryptedData ::= SEQUENCE {
// version Version,
// encryptedContentInfo EncryptedContentInfo }
struct pkcs7_encrypt_st {
ASN1_INTEGER *version;
PKCS7_ENC_CONTENT *enc_data;
};
// pkcs7_parse_header reads the non-certificate/non-CRL prefix of a PKCS#7
// SignedData blob from |cbs| and sets |*out| to point to the rest of the
// input. If the input is in BER format, then |*der_bytes| will be set to a
// pointer that needs to be freed by the caller once they have finished
// processing |*out| (which will be pointing into |*der_bytes|).
//
// It returns one on success or zero on error. On error, |*der_bytes| is
// NULL.
int pkcs7_parse_header(uint8_t **der_bytes, CBS *out, CBS *cbs);
// pkcs7_add_signed_data writes a PKCS#7, SignedData structure to |out|. While
// doing so it makes callbacks to let the caller fill in parts of the structure.
// All callbacks are ignored if NULL and return one on success or zero on error.
//
// digest_algos_cb: may write AlgorithmIdentifiers into the given CBB, which
// is a SET of digest algorithms.
// cert_crl_cb: may write the |certificates| or |crls| fields.
// (See https://datatracker.ietf.org/doc/html/rfc2315#section-9.1)
// signer_infos_cb: may write the contents of the |signerInfos| field.
// (See https://datatracker.ietf.org/doc/html/rfc2315#section-9.1)
//
// pkcs7_add_signed_data returns one on success or zero on error.
int pkcs7_add_signed_data(CBB *out,
int (*digest_algos_cb)(CBB *out, const void *arg),
int (*cert_crl_cb)(CBB *out, const void *arg),
int (*signer_infos_cb)(CBB *out, const void *arg),
const void *arg);
// BIO_f_cipher is used internally by the pkcs7 module. It is not recommended
// for external use.
OPENSSL_EXPORT const BIO_METHOD *BIO_f_cipher(void);
// BIO_get_cipher_ctx writes a reference of |b|'s EVP_CIPHER_CTX* to |*ctx|
int BIO_get_cipher_ctx(BIO *b, EVP_CIPHER_CTX **ctx);
// BIO_set_cipher is used internally for testing. It is not recommended for
// external use.
OPENSSL_EXPORT int BIO_set_cipher(BIO *b, const EVP_CIPHER *cipher,
const unsigned char *key,
const unsigned char *iv, int enc);
// BIO_get_cipher_status returns 1 if the cipher is in a healthy state or 0
// otherwise. Unhealthy state could indicate decryption failure or other
// abnormalities. Data read from an unhealthy cipher should not be considered
// authentic.
OPENSSL_EXPORT int BIO_get_cipher_status(BIO *b);
// pkcs7_final initializes a data BIO using |p7|, copies all of |data| into it,
// before final finalizing |p7|. It returns 1 on success and 0 on failure.
int pkcs7_final(PKCS7 *p7, BIO *data);
#if defined(__cplusplus)
} // extern C
#endif
#endif // OPENSSL_HEADER_PKCS7_INTERNAL_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,157 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR ISC
#include <openssl/pkcs7.h>
#include <openssl/asn1t.h>
#include <openssl/pem.h>
#include "../internal.h"
#include "internal.h"
ASN1_ADB_TEMPLATE(p7default) = ASN1_EXP_OPT(PKCS7, d.other, ASN1_ANY, 0);
ASN1_ADB(PKCS7) = {
ADB_ENTRY(NID_pkcs7_data,
ASN1_EXP_OPT(PKCS7, d.data, ASN1_OCTET_STRING, 0)),
ADB_ENTRY(NID_pkcs7_signed, ASN1_EXP_OPT(PKCS7, d.sign, PKCS7_SIGNED, 0)),
ADB_ENTRY(NID_pkcs7_enveloped,
ASN1_EXP_OPT(PKCS7, d.enveloped, PKCS7_ENVELOPE, 0)),
ADB_ENTRY(NID_pkcs7_signedAndEnveloped,
ASN1_EXP_OPT(PKCS7, d.signed_and_enveloped, PKCS7_SIGN_ENVELOPE,
0)),
ADB_ENTRY(NID_pkcs7_digest, ASN1_EXP_OPT(PKCS7, d.digest, PKCS7_DIGEST, 0)),
ADB_ENTRY(
NID_pkcs7_encrypted,
ASN1_EXP_OPT(PKCS7, d.encrypted, PKCS7_ENCRYPT,
0))} ASN1_ADB_END(PKCS7, 0, type, 0, &p7default_tt, &p7default_tt);
ASN1_SEQUENCE(PKCS7) = {ASN1_SIMPLE(PKCS7, type, ASN1_OBJECT),
ASN1_ADB_OBJECT(PKCS7)} ASN1_SEQUENCE_END(PKCS7)
IMPLEMENT_ASN1_FUNCTIONS(PKCS7)
IMPLEMENT_ASN1_DUP_FUNCTION(PKCS7)
ASN1_SEQUENCE(PKCS7_SIGNED) = {
ASN1_SIMPLE(PKCS7_SIGNED, version, ASN1_INTEGER),
ASN1_SET_OF(PKCS7_SIGNED, md_algs, X509_ALGOR),
ASN1_SIMPLE(PKCS7_SIGNED, contents, PKCS7),
ASN1_IMP_SEQUENCE_OF_OPT(PKCS7_SIGNED, cert, X509, 0),
ASN1_IMP_SET_OF_OPT(PKCS7_SIGNED, crl, X509_CRL, 1),
ASN1_SET_OF(PKCS7_SIGNED, signer_info,
PKCS7_SIGNER_INFO)} ASN1_SEQUENCE_END(PKCS7_SIGNED)
IMPLEMENT_ASN1_FUNCTIONS(PKCS7_SIGNED)
ASN1_SEQUENCE(PKCS7_ISSUER_AND_SERIAL) = {
ASN1_SIMPLE(PKCS7_ISSUER_AND_SERIAL, issuer, X509_NAME),
ASN1_SIMPLE(PKCS7_ISSUER_AND_SERIAL, serial,
ASN1_INTEGER)} ASN1_SEQUENCE_END(PKCS7_ISSUER_AND_SERIAL)
IMPLEMENT_ASN1_FUNCTIONS(PKCS7_ISSUER_AND_SERIAL)
// Minor tweak to operation: free up X509.
static int recip_info_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
void *exarg) {
if (operation == ASN1_OP_FREE_POST) {
PKCS7_RECIP_INFO *ri = (PKCS7_RECIP_INFO *)*pval;
X509_free(ri->cert);
}
return 1;
}
ASN1_SEQUENCE_cb(PKCS7_RECIP_INFO, recip_info_cb) =
{ASN1_SIMPLE(PKCS7_RECIP_INFO, version, ASN1_INTEGER),
ASN1_SIMPLE(PKCS7_RECIP_INFO, issuer_and_serial, PKCS7_ISSUER_AND_SERIAL),
ASN1_SIMPLE(PKCS7_RECIP_INFO, key_enc_algor, X509_ALGOR),
ASN1_SIMPLE(PKCS7_RECIP_INFO, enc_key,
ASN1_OCTET_STRING)} ASN1_SEQUENCE_END_cb(PKCS7_RECIP_INFO,
PKCS7_RECIP_INFO)
IMPLEMENT_ASN1_FUNCTIONS(PKCS7_RECIP_INFO)
// Minor tweak to operation: free up EVP_PKEY.
static int signer_info_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
void *exarg) {
PKCS7_SIGNER_INFO *si = (PKCS7_SIGNER_INFO *)*pval;
if (operation == ASN1_OP_FREE_POST) {
EVP_PKEY_free(si->pkey);
}
return 1;
}
ASN1_SEQUENCE_cb(PKCS7_SIGNER_INFO, signer_info_cb) = {
ASN1_SIMPLE(PKCS7_SIGNER_INFO, version, ASN1_INTEGER),
ASN1_SIMPLE(PKCS7_SIGNER_INFO, issuer_and_serial, PKCS7_ISSUER_AND_SERIAL),
ASN1_SIMPLE(PKCS7_SIGNER_INFO, digest_alg, X509_ALGOR),
// NB this should be a SET OF but we use a SEQUENCE OF so the original
// order is retained when the structure is reencoded. Since the attributes
// are implicitly tagged this will not affect the encoding.
ASN1_IMP_SEQUENCE_OF_OPT(PKCS7_SIGNER_INFO, auth_attr, X509_ATTRIBUTE, 0),
ASN1_SIMPLE(PKCS7_SIGNER_INFO, digest_enc_alg, X509_ALGOR),
ASN1_SIMPLE(PKCS7_SIGNER_INFO, enc_digest, ASN1_OCTET_STRING),
ASN1_IMP_SET_OF_OPT(
PKCS7_SIGNER_INFO, unauth_attr, X509_ATTRIBUTE,
1)} ASN1_SEQUENCE_END_cb(PKCS7_SIGNER_INFO, PKCS7_SIGNER_INFO)
IMPLEMENT_ASN1_FUNCTIONS(PKCS7_SIGNER_INFO)
ASN1_SEQUENCE(PKCS7_ENC_CONTENT) = {
ASN1_SIMPLE(PKCS7_ENC_CONTENT, content_type, ASN1_OBJECT),
ASN1_SIMPLE(PKCS7_ENC_CONTENT, algorithm, X509_ALGOR),
ASN1_IMP_OPT(PKCS7_ENC_CONTENT, enc_data, ASN1_OCTET_STRING,
0)} ASN1_SEQUENCE_END(PKCS7_ENC_CONTENT)
IMPLEMENT_ASN1_FUNCTIONS(PKCS7_ENC_CONTENT)
ASN1_SEQUENCE(PKCS7_SIGN_ENVELOPE) = {
ASN1_SIMPLE(PKCS7_SIGN_ENVELOPE, version, ASN1_INTEGER),
ASN1_SET_OF(PKCS7_SIGN_ENVELOPE, recipientinfo, PKCS7_RECIP_INFO),
ASN1_SET_OF(PKCS7_SIGN_ENVELOPE, md_algs, X509_ALGOR),
ASN1_SIMPLE(PKCS7_SIGN_ENVELOPE, enc_data, PKCS7_ENC_CONTENT),
ASN1_IMP_SET_OF_OPT(PKCS7_SIGN_ENVELOPE, cert, X509, 0),
ASN1_IMP_SET_OF_OPT(PKCS7_SIGN_ENVELOPE, crl, X509_CRL, 1),
ASN1_SET_OF(PKCS7_SIGN_ENVELOPE, signer_info,
PKCS7_SIGNER_INFO)} ASN1_SEQUENCE_END(PKCS7_SIGN_ENVELOPE)
IMPLEMENT_ASN1_FUNCTIONS(PKCS7_SIGN_ENVELOPE)
ASN1_SEQUENCE(PKCS7_ENCRYPT) = {
ASN1_SIMPLE(PKCS7_ENCRYPT, version, ASN1_INTEGER),
ASN1_SIMPLE(PKCS7_ENCRYPT, enc_data,
PKCS7_ENC_CONTENT)} ASN1_SEQUENCE_END(PKCS7_ENCRYPT)
IMPLEMENT_ASN1_FUNCTIONS(PKCS7_ENCRYPT)
ASN1_SEQUENCE(PKCS7_DIGEST) = {
ASN1_SIMPLE(PKCS7_DIGEST, version, ASN1_INTEGER),
ASN1_SIMPLE(PKCS7_DIGEST, digest_alg, X509_ALGOR),
ASN1_SIMPLE(PKCS7_DIGEST, contents, PKCS7),
ASN1_SIMPLE(PKCS7_DIGEST, digest,
ASN1_OCTET_STRING)} ASN1_SEQUENCE_END(PKCS7_DIGEST)
IMPLEMENT_ASN1_FUNCTIONS(PKCS7_DIGEST)
ASN1_SEQUENCE(PKCS7_ENVELOPE) = {
ASN1_SIMPLE(PKCS7_ENVELOPE, version, ASN1_INTEGER),
ASN1_SET_OF(PKCS7_ENVELOPE, recipientinfo, PKCS7_RECIP_INFO),
ASN1_SIMPLE(PKCS7_ENVELOPE, enc_data,
PKCS7_ENC_CONTENT)} ASN1_SEQUENCE_END(PKCS7_ENVELOPE)
IMPLEMENT_ASN1_FUNCTIONS(PKCS7_ENVELOPE)
ASN1_ITEM_TEMPLATE(PKCS7_ATTR_VERIFY) = ASN1_EX_TEMPLATE_TYPE(
ASN1_TFLG_SEQUENCE_OF | ASN1_TFLG_IMPTAG | ASN1_TFLG_UNIVERSAL, V_ASN1_SET,
PKCS7_ATTRIBUTES, X509_ATTRIBUTE)
ASN1_ITEM_TEMPLATE_END(PKCS7_ATTR_VERIFY)
int PKCS7_print_ctx(BIO *bio, PKCS7 *pkcs7, int indent, const ASN1_PCTX *pctx) {
GUARD_PTR(bio);
GUARD_PTR(pkcs7);
if (BIO_printf(bio, "PKCS7 printing is not supported") <= 0) {
return 0;
}
return 1;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,586 @@
// Copyright (c) 2017, Google Inc.
// SPDX-License-Identifier: ISC
#include <openssl/pkcs7.h>
#include <assert.h>
#include <limits.h>
#include <openssl/bytestring.h>
#include <openssl/err.h>
#include <openssl/mem.h>
#include <openssl/obj.h>
#include <openssl/pem.h>
#include <openssl/pool.h>
#include <openssl/stack.h>
#include <openssl/x509.h>
#include "../internal.h"
#include "internal.h"
OPENSSL_BEGIN_ALLOW_DEPRECATED
int PKCS7_get_certificates(STACK_OF(X509) *out_certs, CBS *cbs) {
int ret = 0;
const size_t initial_certs_len = sk_X509_num(out_certs);
STACK_OF(CRYPTO_BUFFER) *raw = sk_CRYPTO_BUFFER_new_null();
if (raw == NULL || !PKCS7_get_raw_certificates(raw, cbs, NULL)) {
goto err;
}
for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(raw); i++) {
CRYPTO_BUFFER *buf = sk_CRYPTO_BUFFER_value(raw, i);
X509 *x509 = X509_parse_from_buffer(buf);
if (x509 == NULL || !sk_X509_push(out_certs, x509)) {
X509_free(x509);
goto err;
}
}
ret = 1;
err:
sk_CRYPTO_BUFFER_pop_free(raw, CRYPTO_BUFFER_free);
if (!ret) {
while (sk_X509_num(out_certs) != initial_certs_len) {
X509 *x509 = sk_X509_pop(out_certs);
X509_free(x509);
}
}
return ret;
}
int PKCS7_get_CRLs(STACK_OF(X509_CRL) *out_crls, CBS *cbs) {
CBS signed_data, crls;
uint8_t *der_bytes = NULL;
int ret = 0, has_crls;
const size_t initial_crls_len = sk_X509_CRL_num(out_crls);
// See https://tools.ietf.org/html/rfc2315#section-9.1
if (!pkcs7_parse_header(&der_bytes, &signed_data, cbs) ||
// Even if only CRLs are included, there may be an empty certificates
// block. OpenSSL does this, for example.
!CBS_get_optional_asn1(
&signed_data, NULL, NULL,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
!CBS_get_optional_asn1(
&signed_data, &crls, &has_crls,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1)) {
goto err;
}
if (!has_crls) {
CBS_init(&crls, NULL, 0);
}
while (CBS_len(&crls) > 0) {
CBS crl_data;
X509_CRL *crl;
const uint8_t *inp;
if (!CBS_get_asn1_element(&crls, &crl_data, CBS_ASN1_SEQUENCE)) {
goto err;
}
if (CBS_len(&crl_data) > LONG_MAX) {
goto err;
}
inp = CBS_data(&crl_data);
crl = d2i_X509_CRL(NULL, &inp, (long)CBS_len(&crl_data));
if (!crl) {
goto err;
}
assert(inp == CBS_data(&crl_data) + CBS_len(&crl_data));
if (sk_X509_CRL_push(out_crls, crl) == 0) {
X509_CRL_free(crl);
goto err;
}
}
ret = 1;
err:
OPENSSL_free(der_bytes);
if (!ret) {
while (sk_X509_CRL_num(out_crls) != initial_crls_len) {
X509_CRL_free(sk_X509_CRL_pop(out_crls));
}
}
return ret;
}
int PKCS7_get_PEM_certificates(STACK_OF(X509) *out_certs, BIO *pem_bio) {
uint8_t *data;
long len;
int ret;
// Even though we pass PEM_STRING_PKCS7 as the expected PEM type here, PEM
// internally will actually allow several other values too, including
// "CERTIFICATE".
if (!PEM_bytes_read_bio(&data, &len, NULL /* PEM type output */,
PEM_STRING_PKCS7, pem_bio,
NULL /* password callback */,
NULL /* password callback argument */)) {
return 0;
}
CBS cbs;
CBS_init(&cbs, data, len);
ret = PKCS7_get_certificates(out_certs, &cbs);
OPENSSL_free(data);
return ret;
}
int PKCS7_get_PEM_CRLs(STACK_OF(X509_CRL) *out_crls, BIO *pem_bio) {
uint8_t *data;
long len;
int ret;
// Even though we pass PEM_STRING_PKCS7 as the expected PEM type here, PEM
// internally will actually allow several other values too, including
// "CERTIFICATE".
if (!PEM_bytes_read_bio(&data, &len, NULL /* PEM type output */,
PEM_STRING_PKCS7, pem_bio,
NULL /* password callback */,
NULL /* password callback argument */)) {
return 0;
}
CBS cbs;
CBS_init(&cbs, data, len);
ret = PKCS7_get_CRLs(out_crls, &cbs);
OPENSSL_free(data);
return ret;
}
static int pkcs7_bundle_certificates_cb(CBB *out, const void *arg) {
const STACK_OF(X509) *certs = arg;
size_t i;
CBB certificates;
// See https://tools.ietf.org/html/rfc2315#section-9.1
if (!CBB_add_asn1(out, &certificates,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
return 0;
}
for (i = 0; i < sk_X509_num(certs); i++) {
X509 *x509 = sk_X509_value(certs, i);
uint8_t *buf;
int len = i2d_X509(x509, NULL);
if (len < 0 || !CBB_add_space(&certificates, &buf, len) ||
i2d_X509(x509, &buf) < 0) {
return 0;
}
}
// |certificates| is a implicitly-tagged SET OF.
return CBB_flush_asn1_set_of(&certificates) && CBB_flush(out);
}
int PKCS7_bundle_certificates(CBB *out, const STACK_OF(X509) *certs) {
return pkcs7_add_signed_data(out, /*digest_algos_cb=*/NULL,
pkcs7_bundle_certificates_cb,
/*signer_infos_cb=*/NULL, certs);
}
static int pkcs7_bundle_crls_cb(CBB *out, const void *arg) {
const STACK_OF(X509_CRL) *crls = arg;
size_t i;
CBB crl_data;
// See https://tools.ietf.org/html/rfc2315#section-9.1
if (!CBB_add_asn1(out, &crl_data,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1)) {
return 0;
}
for (i = 0; i < sk_X509_CRL_num(crls); i++) {
X509_CRL *crl = sk_X509_CRL_value(crls, i);
uint8_t *buf;
int len = i2d_X509_CRL(crl, NULL);
if (len < 0 || !CBB_add_space(&crl_data, &buf, len) ||
i2d_X509_CRL(crl, &buf) < 0) {
return 0;
}
}
// |crl_data| is a implicitly-tagged SET OF.
return CBB_flush_asn1_set_of(&crl_data) && CBB_flush(out);
}
int PKCS7_bundle_CRLs(CBB *out, const STACK_OF(X509_CRL) *crls) {
return pkcs7_add_signed_data(out, /*digest_algos_cb=*/NULL,
pkcs7_bundle_crls_cb,
/*signer_infos_cb=*/NULL, crls);
}
PKCS7 *d2i_PKCS7_bio(BIO *bio, PKCS7 **out) {
GUARD_PTR(bio);
uint8_t *data = NULL;
size_t len;
// Read BIO contents into newly allocated buffer
if (!BIO_read_asn1(bio, &data, &len, INT_MAX)) {
return NULL;
}
const uint8_t *ptr = data;
// d2i_PKCS7 handles indefinite-length BER properly, so use it instead of
// ASN1_item_d2i_bio
PKCS7 *ret = d2i_PKCS7(out, &ptr, len);
OPENSSL_free(data);
return ret;
}
int i2d_PKCS7_bio(BIO *bio, const PKCS7 *p7) {
return ASN1_item_i2d_bio(ASN1_ITEM_rptr(PKCS7), bio, (void *)p7);
}
int PKCS7_type_is_data(const PKCS7 *p7) {
return OBJ_obj2nid(p7->type) == NID_pkcs7_data;
}
int PKCS7_type_is_digest(const PKCS7 *p7) {
return OBJ_obj2nid(p7->type) == NID_pkcs7_digest;
}
int PKCS7_type_is_encrypted(const PKCS7 *p7) {
return OBJ_obj2nid(p7->type) == NID_pkcs7_encrypted;
}
int PKCS7_type_is_enveloped(const PKCS7 *p7) {
return OBJ_obj2nid(p7->type) == NID_pkcs7_enveloped;
}
int PKCS7_type_is_signed(const PKCS7 *p7) {
return OBJ_obj2nid(p7->type) == NID_pkcs7_signed;
}
int PKCS7_type_is_signedAndEnveloped(const PKCS7 *p7) {
return OBJ_obj2nid(p7->type) == NID_pkcs7_signedAndEnveloped;
}
// write_sha256_ai writes an AlgorithmIdentifier for SHA-256 to
// |digest_algos_set|.
static int write_sha256_ai(CBB *digest_algos_set, const void *arg) {
CBB seq;
return CBB_add_asn1(digest_algos_set, &seq, CBS_ASN1_SEQUENCE) &&
OBJ_nid2cbb(&seq, NID_sha256) && //
// https://datatracker.ietf.org/doc/html/rfc5754#section-2
// "Implementations MUST generate SHA2 AlgorithmIdentifiers with absent
// parameters."
CBB_flush(digest_algos_set);
}
// sign_sha256 writes at most |max_out_sig| bytes of the signature of |data| by
// |pkey| to |out_sig| and sets |*out_sig_len| to the number of bytes written.
// It returns one on success or zero on error.
static int sign_sha256(uint8_t *out_sig, size_t *out_sig_len,
size_t max_out_sig, EVP_PKEY *pkey, BIO *data) {
static const size_t kBufSize = 4096;
uint8_t *buffer = OPENSSL_malloc(kBufSize);
if (!buffer) {
return 0;
}
EVP_MD_CTX ctx;
EVP_MD_CTX_init(&ctx);
int ret = 0;
if (!EVP_DigestSignInit(&ctx, NULL, EVP_sha256(), NULL, pkey)) {
goto out;
}
for (;;) {
const int n = BIO_read(data, buffer, kBufSize);
if (n == 0) {
break;
} else if (n < 0 || !EVP_DigestSignUpdate(&ctx, buffer, n)) {
goto out;
}
}
*out_sig_len = max_out_sig;
if (!EVP_DigestSignFinal(&ctx, out_sig, out_sig_len)) {
goto out;
}
ret = 1;
out:
EVP_MD_CTX_cleanup(&ctx);
OPENSSL_free(buffer);
return ret;
}
struct signer_info_data {
const X509 *sign_cert;
uint8_t *signature;
size_t signature_len;
};
// write_signer_info writes the SignerInfo structure from
// https://datatracker.ietf.org/doc/html/rfc2315#section-9.2 to |out|. It
// returns one on success or zero on error.
static int write_signer_info(CBB *out, const void *arg) {
const struct signer_info_data *const si_data = arg;
int ret = 0;
uint8_t *subject_bytes = NULL;
uint8_t *serial_bytes = NULL;
const int subject_len =
i2d_X509_NAME(X509_get_subject_name(si_data->sign_cert), &subject_bytes);
const int serial_len = i2d_ASN1_INTEGER(
(ASN1_INTEGER *)X509_get0_serialNumber(si_data->sign_cert),
&serial_bytes);
CBB seq, issuer_and_serial, signing_algo, null, signature;
if (subject_len < 0 || serial_len < 0 ||
!CBB_add_asn1(out, &seq, CBS_ASN1_SEQUENCE) ||
// version
!CBB_add_asn1_uint64(&seq, 1) ||
!CBB_add_asn1(&seq, &issuer_and_serial, CBS_ASN1_SEQUENCE) ||
!CBB_add_bytes(&issuer_and_serial, subject_bytes, subject_len) ||
!CBB_add_bytes(&issuer_and_serial, serial_bytes, serial_len) ||
!write_sha256_ai(&seq, NULL) ||
!CBB_add_asn1(&seq, &signing_algo, CBS_ASN1_SEQUENCE) ||
!OBJ_nid2cbb(&signing_algo, NID_rsaEncryption) ||
!CBB_add_asn1(&signing_algo, &null, CBS_ASN1_NULL) ||
!CBB_add_asn1(&seq, &signature, CBS_ASN1_OCTETSTRING) ||
!CBB_add_bytes(&signature, si_data->signature, si_data->signature_len) ||
!CBB_flush(out)) {
goto out;
}
ret = 1;
out:
OPENSSL_free(subject_bytes);
OPENSSL_free(serial_bytes);
return ret;
}
static int pkcs7_add_signature(PKCS7 *p7, X509 *x509, EVP_PKEY *pkey) {
// OpenSSL's docs say that this defaults to SHA1, but appears to actually
// default to SHA256 in 1.1.x and 3.x for RSA, DSA, and EC(DSA).
// https://linux.die.net/man/3/pkcs7_sign
// https://github.com/openssl/openssl/blob/79c98fc6ccab49f02528e06cc046ac61f841a753/crypto/rsa/rsa_ameth.c#L438
const EVP_MD *digest = EVP_sha256();
PKCS7_SIGNER_INFO *si = NULL;
switch (EVP_PKEY_id(pkey)) {
case EVP_PKEY_RSA:
case EVP_PKEY_DSA:
case EVP_PKEY_EC:
break;
default:
OPENSSL_PUT_ERROR(PKCS7, PKCS7_R_NO_DEFAULT_DIGEST);
goto err;
}
// We add the signer's info below, including the static |digest|. We delegate
// initialization of the |digest| into an |EVP_MD_CTX| to |BIO_f_md|.
if ((si = PKCS7_SIGNER_INFO_new()) == NULL ||
!PKCS7_SIGNER_INFO_set(si, x509, pkey, digest) ||
!PKCS7_add_signer(p7, si)) { // |p7| takes ownership of |si| here
OPENSSL_PUT_ERROR(PKCS7, PKCS7_R_PKCS7_DATASIGN);
goto err;
}
return 1;
err:
PKCS7_SIGNER_INFO_free(si);
return 0;
}
static int pkcs7_sign_add_signer(PKCS7 *p7, X509 *signcert, EVP_PKEY *pkey) {
if (!X509_check_private_key(signcert, pkey)) {
OPENSSL_PUT_ERROR(PKCS7, PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
return 0;
}
if (!pkcs7_add_signature(p7, signcert, pkey)) {
OPENSSL_PUT_ERROR(PKCS7, PKCS7_R_PKCS7_ADD_SIGNATURE_ERROR);
return 0;
}
if (!PKCS7_add_certificate(p7, signcert)) {
return 0;
}
return 1;
}
static PKCS7 *pkcs7_do_general_sign(X509 *sign_cert, EVP_PKEY *pkey,
struct stack_st_X509 *certs, BIO *data,
int flags) {
PKCS7 *ret = NULL;
if ((ret = PKCS7_new()) == NULL || !PKCS7_set_type(ret, NID_pkcs7_signed) ||
!PKCS7_content_new(ret, NID_pkcs7_data)) {
OPENSSL_PUT_ERROR(PKCS7, ERR_R_PKCS7_LIB);
goto err;
}
if (!pkcs7_sign_add_signer(ret, sign_cert, pkey)) {
OPENSSL_PUT_ERROR(PKCS7, PKCS7_R_PKCS7_ADD_SIGNER_ERROR);
goto err;
}
for (size_t i = 0; i < sk_X509_num(certs); i++) {
if (!PKCS7_add_certificate(ret, sk_X509_value(certs, i))) {
OPENSSL_PUT_ERROR(PKCS7, PKCS7_R_PKCS7_ADD_SIGNER_ERROR);
goto err;
}
}
if ((flags & PKCS7_DETACHED) && PKCS7_type_is_data(ret->d.sign->contents)) {
ASN1_OCTET_STRING_free(ret->d.sign->contents->d.data);
ret->d.sign->contents->d.data = NULL;
}
if (!pkcs7_final(ret, data)) {
goto err;
}
return ret;
err:
PKCS7_free(ret);
return NULL;
}
PKCS7 *PKCS7_sign(X509 *sign_cert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
BIO *data, int flags) {
CBB cbb;
if (!CBB_init(&cbb, 2048)) {
return NULL;
}
uint8_t *der = NULL;
size_t len;
PKCS7 *ret = NULL;
if (sign_cert == NULL && pkey == NULL && flags == PKCS7_DETACHED) {
// Caller just wants to bundle certificates.
if (!PKCS7_bundle_certificates(&cbb, certs)) {
goto out;
}
} else if (sign_cert != NULL && pkey != NULL && certs == NULL &&
data != NULL &&
flags == (PKCS7_NOATTR | PKCS7_BINARY | PKCS7_NOCERTS |
PKCS7_DETACHED) &&
EVP_PKEY_id(pkey) == NID_rsaEncryption) {
// sign-file.c from the Linux kernel.
const size_t signature_max_len = EVP_PKEY_size(pkey);
struct signer_info_data si_data = {
.sign_cert = sign_cert,
.signature = OPENSSL_malloc(signature_max_len),
};
if (!si_data.signature ||
!sign_sha256(si_data.signature, &si_data.signature_len,
signature_max_len, pkey, data) ||
!pkcs7_add_signed_data(&cbb, write_sha256_ai, /*cert_crl_cb=*/NULL,
write_signer_info, &si_data)) {
OPENSSL_free(si_data.signature);
goto out;
}
OPENSSL_free(si_data.signature);
} else if (sign_cert != NULL && pkey != NULL && data != NULL &&
!(flags & PKCS7_NOCERTS)) {
ret = pkcs7_do_general_sign(sign_cert, pkey, certs, data, flags);
goto out;
} else {
OPENSSL_PUT_ERROR(PKCS7, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
goto out;
}
if (!CBB_finish(&cbb, &der, &len)) {
goto out;
}
const uint8_t *const_der = der;
ret = d2i_PKCS7(NULL, &const_der, len);
out:
CBB_cleanup(&cbb);
OPENSSL_free(der);
return ret;
}
int PKCS7_add_certificate(PKCS7 *p7, X509 *x509) {
STACK_OF(X509) **sk;
if (p7 == NULL || x509 == NULL) {
OPENSSL_PUT_ERROR(PKCS7, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
switch (OBJ_obj2nid(p7->type)) {
case NID_pkcs7_signed:
sk = &(p7->d.sign->cert);
break;
case NID_pkcs7_signedAndEnveloped:
sk = &(p7->d.signed_and_enveloped->cert);
break;
default:
OPENSSL_PUT_ERROR(PKCS7, PKCS7_R_WRONG_CONTENT_TYPE);
return 0;
}
if (*sk == NULL) {
*sk = sk_X509_new_null();
}
if (*sk == NULL) {
OPENSSL_PUT_ERROR(PKCS7, ERR_R_CRYPTO_LIB);
return 0;
}
if (!sk_X509_push(*sk, x509)) {
return 0;
}
X509_up_ref(x509);
return 1;
}
int PKCS7_add_crl(PKCS7 *p7, X509_CRL *crl) {
STACK_OF(X509_CRL) **sk;
if (p7 == NULL || crl == NULL) {
OPENSSL_PUT_ERROR(PKCS7, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
switch (OBJ_obj2nid(p7->type)) {
case NID_pkcs7_signed:
sk = &(p7->d.sign->crl);
break;
case NID_pkcs7_signedAndEnveloped:
sk = &(p7->d.signed_and_enveloped->crl);
break;
default:
OPENSSL_PUT_ERROR(PKCS7, PKCS7_R_WRONG_CONTENT_TYPE);
return 0;
}
if (*sk == NULL) {
*sk = sk_X509_CRL_new_null();
}
if (*sk == NULL) {
OPENSSL_PUT_ERROR(PKCS7, ERR_R_CRYPTO_LIB);
return 0;
}
if (!sk_X509_CRL_push(*sk, crl)) {
return 0;
}
X509_CRL_up_ref(crl);
return 1;
}
OPENSSL_END_ALLOW_DEPRECATED