Coverage Report

Created: 2026-04-15 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/crypto/pkcs7/pkcs7_x509.cc
Line
Count
Source
1
// Copyright 2017 The BoringSSL Authors
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include <openssl/pkcs7.h>
16
17
#include <assert.h>
18
#include <limits.h>
19
20
#include <openssl/asn1.h>
21
#include <openssl/bytestring.h>
22
#include <openssl/cms.h>
23
#include <openssl/digest.h>
24
#include <openssl/err.h>
25
#include <openssl/evp.h>
26
#include <openssl/mem.h>
27
#include <openssl/obj.h>
28
#include <openssl/pem.h>
29
#include <openssl/pool.h>
30
#include <openssl/stack.h>
31
#include <openssl/x509.h>
32
33
#include "../asn1/internal.h"
34
#include "../internal.h"
35
#include "../mem_internal.h"
36
#include "../x509/internal.h"
37
#include "internal.h"
38
39
40
using namespace bssl;
41
42
0
int PKCS7_get_certificates(STACK_OF(X509) *out_certs, CBS *cbs) {
43
0
  int ret = 0;
44
0
  const size_t initial_certs_len = sk_X509_num(out_certs);
45
0
  STACK_OF(CRYPTO_BUFFER) *raw = sk_CRYPTO_BUFFER_new_null();
46
0
  if (raw == nullptr || !PKCS7_get_raw_certificates(raw, cbs, nullptr)) {
47
0
    goto err;
48
0
  }
49
50
0
  for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(raw); i++) {
51
0
    CRYPTO_BUFFER *buf = sk_CRYPTO_BUFFER_value(raw, i);
52
0
    X509 *x509 = X509_parse_from_buffer(buf);
53
0
    if (x509 == nullptr || !sk_X509_push(out_certs, x509)) {
54
0
      X509_free(x509);
55
0
      goto err;
56
0
    }
57
0
  }
58
59
0
  ret = 1;
60
61
0
err:
62
0
  sk_CRYPTO_BUFFER_pop_free(raw, CRYPTO_BUFFER_free);
63
0
  if (!ret) {
64
0
    while (sk_X509_num(out_certs) != initial_certs_len) {
65
0
      X509 *x509 = sk_X509_pop(out_certs);
66
0
      X509_free(x509);
67
0
    }
68
0
  }
69
70
0
  return ret;
71
0
}
72
73
0
int PKCS7_get_CRLs(STACK_OF(X509_CRL) *out_crls, CBS *cbs) {
74
0
  CBS signed_data, crls;
75
0
  uint8_t *der_bytes = nullptr;
76
0
  int ret = 0, has_crls;
77
0
  const size_t initial_crls_len = sk_X509_CRL_num(out_crls);
78
79
  // See https://tools.ietf.org/html/rfc2315#section-9.1
80
0
  if (!pkcs7_parse_header(&der_bytes, &signed_data, cbs) ||
81
      // Even if only CRLs are included, there may be an empty certificates
82
      // block. OpenSSL does this, for example.
83
0
      !CBS_get_optional_asn1(
84
0
          &signed_data, nullptr, nullptr,
85
0
          CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
86
0
      !CBS_get_optional_asn1(
87
0
          &signed_data, &crls, &has_crls,
88
0
          CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1)) {
89
0
    goto err;
90
0
  }
91
92
0
  if (!has_crls) {
93
0
    CBS_init(&crls, nullptr, 0);
94
0
  }
95
96
0
  while (CBS_len(&crls) > 0) {
97
0
    CBS crl_data;
98
0
    X509_CRL *crl;
99
0
    const uint8_t *inp;
100
101
0
    if (!CBS_get_asn1_element(&crls, &crl_data, CBS_ASN1_SEQUENCE)) {
102
0
      goto err;
103
0
    }
104
105
0
    if (CBS_len(&crl_data) > LONG_MAX) {
106
0
      goto err;
107
0
    }
108
0
    inp = CBS_data(&crl_data);
109
0
    crl = d2i_X509_CRL(nullptr, &inp, (long)CBS_len(&crl_data));
110
0
    if (!crl) {
111
0
      goto err;
112
0
    }
113
114
0
    assert(inp == CBS_data(&crl_data) + CBS_len(&crl_data));
115
116
0
    if (sk_X509_CRL_push(out_crls, crl) == 0) {
117
0
      X509_CRL_free(crl);
118
0
      goto err;
119
0
    }
120
0
  }
121
122
0
  ret = 1;
123
124
0
err:
125
0
  OPENSSL_free(der_bytes);
126
127
0
  if (!ret) {
128
0
    while (sk_X509_CRL_num(out_crls) != initial_crls_len) {
129
0
      X509_CRL_free(sk_X509_CRL_pop(out_crls));
130
0
    }
131
0
  }
132
133
0
  return ret;
134
0
}
135
136
0
int PKCS7_get_PEM_certificates(STACK_OF(X509) *out_certs, BIO *pem_bio) {
137
0
  uint8_t *data;
138
0
  long len;
139
0
  int ret;
140
141
  // Even though we pass PEM_STRING_PKCS7 as the expected PEM type here, PEM
142
  // internally will actually allow several other values too, including
143
  // "CERTIFICATE".
144
0
  if (!PEM_bytes_read_bio(&data, &len, nullptr /* PEM type output */,
145
0
                          PEM_STRING_PKCS7, pem_bio,
146
0
                          nullptr /* password callback */,
147
0
                          nullptr /* password callback argument */)) {
148
0
    return 0;
149
0
  }
150
151
0
  CBS cbs;
152
0
  CBS_init(&cbs, data, len);
153
0
  ret = PKCS7_get_certificates(out_certs, &cbs);
154
0
  OPENSSL_free(data);
155
0
  return ret;
156
0
}
157
158
0
int PKCS7_get_PEM_CRLs(STACK_OF(X509_CRL) *out_crls, BIO *pem_bio) {
159
0
  uint8_t *data;
160
0
  long len;
161
0
  int ret;
162
163
  // Even though we pass PEM_STRING_PKCS7 as the expected PEM type here, PEM
164
  // internally will actually allow several other values too, including
165
  // "CERTIFICATE".
166
0
  if (!PEM_bytes_read_bio(&data, &len, nullptr /* PEM type output */,
167
0
                          PEM_STRING_PKCS7, pem_bio,
168
0
                          nullptr /* password callback */,
169
0
                          nullptr /* password callback argument */)) {
170
0
    return 0;
171
0
  }
172
173
0
  CBS cbs;
174
0
  CBS_init(&cbs, data, len);
175
0
  ret = PKCS7_get_CRLs(out_crls, &cbs);
176
0
  OPENSSL_free(data);
177
0
  return ret;
178
0
}
179
180
0
static int pkcs7_bundle_certificates_cb(CBB *out, void *arg) {
181
0
  auto *certs = static_cast<const STACK_OF(X509) *>(arg);
182
0
  size_t i;
183
0
  CBB certificates;
184
185
  // See https://tools.ietf.org/html/rfc2315#section-9.1
186
0
  if (!CBB_add_asn1(out, &certificates,
187
0
                    CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
188
0
    return 0;
189
0
  }
190
191
0
  for (i = 0; i < sk_X509_num(certs); i++) {
192
0
    X509 *x509 = sk_X509_value(certs, i);
193
0
    uint8_t *buf;
194
0
    int len = i2d_X509(x509, nullptr);
195
196
0
    if (len < 0 || !CBB_add_space(&certificates, &buf, len) ||
197
0
        i2d_X509(x509, &buf) < 0) {
198
0
      return 0;
199
0
    }
200
0
  }
201
202
  // |certificates| is a implicitly-tagged SET OF.
203
0
  return CBB_flush_asn1_set_of(&certificates) && CBB_flush(out);
204
0
}
205
206
0
int PKCS7_bundle_certificates(CBB *out, const STACK_OF(X509) *certs) {
207
0
  return pkcs7_add_signed_data(
208
0
      out, /*signed_data_version=*/1,
209
0
      /*digest_algos_cb=*/nullptr, pkcs7_bundle_certificates_cb,
210
0
      /*signer_infos_cb=*/nullptr, const_cast<STACK_OF(X509) *>(certs));
211
0
}
212
213
0
static int pkcs7_bundle_crls_cb(CBB *out, void *arg) {
214
0
  auto *crls = static_cast<const STACK_OF(X509_CRL) *>(arg);
215
0
  size_t i;
216
0
  CBB crl_data;
217
218
  // See https://tools.ietf.org/html/rfc2315#section-9.1
219
0
  if (!CBB_add_asn1(out, &crl_data,
220
0
                    CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1)) {
221
0
    return 0;
222
0
  }
223
224
0
  for (i = 0; i < sk_X509_CRL_num(crls); i++) {
225
0
    X509_CRL *crl = sk_X509_CRL_value(crls, i);
226
0
    uint8_t *buf;
227
0
    int len = i2d_X509_CRL(crl, nullptr);
228
229
0
    if (len < 0 || !CBB_add_space(&crl_data, &buf, len) ||
230
0
        i2d_X509_CRL(crl, &buf) < 0) {
231
0
      return 0;
232
0
    }
233
0
  }
234
235
  // |crl_data| is a implicitly-tagged SET OF.
236
0
  return CBB_flush_asn1_set_of(&crl_data) && CBB_flush(out);
237
0
}
238
239
0
int PKCS7_bundle_CRLs(CBB *out, const STACK_OF(X509_CRL) *crls) {
240
0
  return pkcs7_add_signed_data(
241
0
      out, /*signed_data_version=*/1,
242
0
      /*digest_algos_cb=*/nullptr, pkcs7_bundle_crls_cb,
243
0
      /*signer_infos_cb=*/nullptr, const_cast<STACK_OF(X509_CRL) *>(crls));
244
0
}
245
246
0
static PKCS7 *pkcs7_new(CBS *cbs) {
247
0
  CBS copy = *cbs, copy2 = *cbs;
248
0
  PKCS7 *ret = New<PKCS7>();
249
0
  if (ret == nullptr) {
250
0
    return nullptr;
251
0
  }
252
0
  ret->type = OBJ_nid2obj(NID_pkcs7_signed);
253
0
  ret->d.sign = New<PKCS7_SIGNED>();
254
0
  if (ret->d.sign == nullptr) {
255
0
    goto err;
256
0
  }
257
0
  ret->d.sign->cert = sk_X509_new_null();
258
0
  ret->d.sign->crl = sk_X509_CRL_new_null();
259
0
  if (ret->d.sign->cert == nullptr || ret->d.sign->crl == nullptr ||
260
0
      !PKCS7_get_certificates(ret->d.sign->cert, &copy) ||
261
0
      !PKCS7_get_CRLs(ret->d.sign->crl, cbs)) {
262
0
    goto err;
263
0
  }
264
265
0
  if (sk_X509_num(ret->d.sign->cert) == 0) {
266
0
    sk_X509_free(ret->d.sign->cert);
267
0
    ret->d.sign->cert = nullptr;
268
0
  }
269
270
0
  if (sk_X509_CRL_num(ret->d.sign->crl) == 0) {
271
0
    sk_X509_CRL_free(ret->d.sign->crl);
272
0
    ret->d.sign->crl = nullptr;
273
0
  }
274
275
0
  ret->ber_len = CBS_len(&copy2) - CBS_len(cbs);
276
0
  ret->ber_bytes = reinterpret_cast<uint8_t *>(
277
0
      OPENSSL_memdup(CBS_data(&copy2), ret->ber_len));
278
0
  if (ret->ber_bytes == nullptr) {
279
0
    goto err;
280
0
  }
281
282
0
  return ret;
283
284
0
err:
285
0
  PKCS7_free(ret);
286
0
  return nullptr;
287
0
}
288
289
0
PKCS7 *d2i_PKCS7(PKCS7 **out, const uint8_t **inp, size_t len) {
290
0
  CBS cbs;
291
0
  CBS_init(&cbs, *inp, len);
292
0
  PKCS7 *ret = pkcs7_new(&cbs);
293
0
  if (ret == nullptr) {
294
0
    return nullptr;
295
0
  }
296
0
  *inp = CBS_data(&cbs);
297
0
  if (out != nullptr) {
298
0
    PKCS7_free(*out);
299
0
    *out = ret;
300
0
  }
301
0
  return ret;
302
0
}
303
304
0
PKCS7 *d2i_PKCS7_bio(BIO *bio, PKCS7 **out) {
305
  // Use a generous bound, to allow for PKCS#7 files containing large root sets.
306
0
  static const size_t kMaxSize = 4 * 1024 * 1024;
307
0
  uint8_t *data;
308
0
  size_t len;
309
0
  if (!BIO_read_asn1(bio, &data, &len, kMaxSize)) {
310
0
    return nullptr;
311
0
  }
312
313
0
  CBS cbs;
314
0
  CBS_init(&cbs, data, len);
315
0
  PKCS7 *ret = pkcs7_new(&cbs);
316
0
  OPENSSL_free(data);
317
0
  if (out != nullptr && ret != nullptr) {
318
0
    PKCS7_free(*out);
319
0
    *out = ret;
320
0
  }
321
0
  return ret;
322
0
}
323
324
0
int i2d_PKCS7(const PKCS7 *p7, uint8_t **out) {
325
0
  if (p7->ber_len > INT_MAX) {
326
0
    OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
327
0
    return -1;
328
0
  }
329
330
0
  if (out == nullptr) {
331
0
    return (int)p7->ber_len;
332
0
  }
333
334
0
  if (*out == nullptr) {
335
0
    *out =
336
0
        reinterpret_cast<uint8_t *>(OPENSSL_memdup(p7->ber_bytes, p7->ber_len));
337
0
    if (*out == nullptr) {
338
0
      return -1;
339
0
    }
340
0
  } else {
341
0
    OPENSSL_memcpy(*out, p7->ber_bytes, p7->ber_len);
342
0
    *out += p7->ber_len;
343
0
  }
344
0
  return (int)p7->ber_len;
345
0
}
346
347
0
int i2d_PKCS7_bio(BIO *bio, const PKCS7 *p7) {
348
0
  return BIO_write_all(bio, p7->ber_bytes, p7->ber_len);
349
0
}
350
351
0
void PKCS7_free(PKCS7 *p7) {
352
0
  if (p7 == nullptr) {
353
0
    return;
354
0
  }
355
356
0
  OPENSSL_free(p7->ber_bytes);
357
0
  ASN1_OBJECT_free(p7->type);
358
  // We only supported signed data.
359
0
  if (p7->d.sign != nullptr) {
360
0
    sk_X509_pop_free(p7->d.sign->cert, X509_free);
361
0
    sk_X509_CRL_pop_free(p7->d.sign->crl, X509_CRL_free);
362
0
    Delete(p7->d.sign);
363
0
  }
364
0
  Delete(p7);
365
0
}
366
367
// We only support signed data, so these getters are no-ops.
368
0
int PKCS7_type_is_data(const PKCS7 *p7) { return 0; }
369
0
int PKCS7_type_is_digest(const PKCS7 *p7) { return 0; }
370
0
int PKCS7_type_is_encrypted(const PKCS7 *p7) { return 0; }
371
0
int PKCS7_type_is_enveloped(const PKCS7 *p7) { return 0; }
372
0
int PKCS7_type_is_signed(const PKCS7 *p7) { return 1; }
373
0
int PKCS7_type_is_signedAndEnveloped(const PKCS7 *p7) { return 0; }
374
375
0
static bool digest_sign_update(EVP_MD_CTX *ctx, BIO *data) {
376
0
  for (;;) {
377
0
    uint8_t buf[4096];
378
0
    const int n = BIO_read(data, buf, sizeof(buf));
379
0
    if (n == 0) {
380
0
      return true;
381
0
    } else if (n < 0 || !EVP_DigestSignUpdate(ctx, buf, n)) {
382
0
      return false;
383
0
    }
384
0
  }
385
0
}
386
387
namespace {
388
struct signer_info_data {
389
  X509 *sign_cert = nullptr;
390
  ScopedEVP_MD_CTX sign_ctx;
391
  bool use_key_id = false;
392
};
393
}  // namespace
394
395
0
static int write_signer_digest_algos(CBB *digest_algos_set, void *arg) {
396
0
  auto *si_data = static_cast<struct signer_info_data *>(arg);
397
  // https://www.rfc-editor.org/rfc/rfc5754.html#section-2
398
  // "Implementations MUST generate SHA2 AlgorithmIdentifiers with absent
399
  //  parameters."
400
0
  return EVP_marshal_digest_algorithm_no_params(
401
0
      digest_algos_set, EVP_MD_CTX_get0_md(si_data->sign_ctx.get()));
402
0
}
403
404
// write_signer_info writes the SignerInfo structure from
405
// https://www.rfc-editor.org/rfc/rfc2315.html#section-9.2 and
406
// https://www.rfc-editor.org/rfc/rfc5652.html#section-5.3 to |out|. It returns
407
// one on success or zero on error.
408
0
static int write_signer_info(CBB *out, void *arg) {
409
0
  auto *si_data = static_cast<struct signer_info_data *>(arg);
410
411
0
  uint64_t version = si_data->use_key_id ? 3u : 1u;
412
0
  CBB seq, child, signing_algo, null, signature;
413
0
  if (!CBB_add_asn1(out, &seq, CBS_ASN1_SEQUENCE) ||
414
0
      !CBB_add_asn1_uint64(&seq, version)) {
415
0
    return 0;
416
0
  }
417
418
  // Output the SignerIdentifier.
419
0
  if (si_data->use_key_id) {
420
0
    const ASN1_OCTET_STRING *skid =
421
0
        X509_get0_subject_key_id(si_data->sign_cert);
422
0
    if (skid == nullptr) {
423
0
      OPENSSL_PUT_ERROR(CMS, CMS_R_CERTIFICATE_HAS_NO_KEYID);
424
0
      return 0;
425
0
    }
426
    // subjectKeyIdentifier is implicitly-tagged.
427
0
    if (!CBB_add_asn1_element(&seq, CBS_ASN1_CONTEXT_SPECIFIC | 0,
428
0
                              ASN1_STRING_get0_data(skid),
429
0
                              ASN1_STRING_length(skid))) {
430
0
      return 0;
431
0
    }
432
0
  } else {
433
0
    if (!CBB_add_asn1(&seq, &child, CBS_ASN1_SEQUENCE) ||
434
0
        !x509_marshal_name(&child, X509_get_subject_name(si_data->sign_cert)) ||
435
0
        !asn1_marshal_integer(&child,
436
0
                              X509_get0_serialNumber(si_data->sign_cert),
437
0
                              /*tag=*/0)) {
438
0
      return 0;
439
0
    }
440
0
  }
441
442
  // Output the digest and signature algorithm. This cannot use X.509 signature
443
  // algorithms because CMS incorrectly decomposes signature algorithms into a
444
  // combination of digesting and "encrypting" the digest, then uses the plain
445
  // rsaEncryption OID instead of the hash-specific RSA OIDs. For now, we only
446
  // support RSA.
447
0
  EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(si_data->sign_ctx->pctx);
448
0
  if (EVP_PKEY_id(pkey) != EVP_PKEY_RSA) {
449
0
    OPENSSL_PUT_ERROR(PKCS7, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
450
0
    return 0;
451
0
  }
452
0
  if (!EVP_marshal_digest_algorithm_no_params(
453
0
          &seq, EVP_MD_CTX_get0_md(si_data->sign_ctx.get())) ||
454
0
      !CBB_add_asn1(&seq, &signing_algo, CBS_ASN1_SEQUENCE) ||
455
0
      !OBJ_nid2cbb(&signing_algo, NID_rsaEncryption) ||
456
0
      !CBB_add_asn1(&signing_algo, &null, CBS_ASN1_NULL)) {
457
0
    return 0;
458
0
  }
459
460
  // Output the signature.
461
0
  uint8_t *ptr;
462
0
  size_t sig_len;
463
0
  if (!EVP_DigestSignFinal(si_data->sign_ctx.get(), nullptr, &sig_len) ||
464
0
      !CBB_add_asn1(&seq, &signature, CBS_ASN1_OCTETSTRING) ||
465
0
      !CBB_reserve(&signature, &ptr, sig_len) ||
466
0
      !EVP_DigestSignFinal(si_data->sign_ctx.get(), ptr, &sig_len) ||
467
0
      !CBB_did_write(&signature, sig_len) ||  //
468
0
      !CBB_flush(out)) {
469
0
    return 0;
470
0
  }
471
472
0
  return 1;
473
0
}
474
475
int bssl::pkcs7_add_external_signature(CBB *out, X509 *sign_cert, EVP_PKEY *key,
476
                                       const EVP_MD *md, BIO *data,
477
0
                                       bool use_key_id) {
478
0
  signer_info_data si_data;
479
0
  si_data.use_key_id = use_key_id;
480
0
  si_data.sign_cert = sign_cert;
481
482
  // Set up the signature.
483
0
  if (!EVP_DigestSignInit(si_data.sign_ctx.get(), nullptr, md, nullptr, key) ||
484
0
      !digest_sign_update(si_data.sign_ctx.get(), data)) {
485
0
    return 0;
486
0
  }
487
488
  // See RFC 5652, Section 5.1. When no certificates are present, the version
489
  // comes from the highest SignerInfo version, which will be 3 (CMS) for a key
490
  // ID, and 1 (CMS or PKCS#7) for issuer and serial.
491
0
  uint64_t signed_data_version = use_key_id ? 3u : 1u;
492
0
  return pkcs7_add_signed_data(
493
0
      out, signed_data_version, write_signer_digest_algos,
494
0
      /*cert_crl_cb=*/nullptr, write_signer_info, &si_data);
495
0
}
496
497
PKCS7 *PKCS7_sign(X509 *sign_cert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
498
0
                  BIO *data, int flags) {
499
0
  ScopedCBB cbb;
500
0
  if (!CBB_init(cbb.get(), 2048)) {
501
0
    return nullptr;
502
0
  }
503
504
0
  if (sign_cert == nullptr && pkey == nullptr && flags == PKCS7_DETACHED) {
505
    // Caller just wants to bundle certificates.
506
0
    if (!PKCS7_bundle_certificates(cbb.get(), certs)) {
507
0
      return nullptr;
508
0
    }
509
0
  } else if (sign_cert != nullptr && pkey != nullptr && certs == nullptr &&
510
0
             data != nullptr &&
511
0
             flags == (PKCS7_NOATTR | PKCS7_BINARY | PKCS7_NOCERTS |
512
0
                       PKCS7_DETACHED)) {
513
    // In OpenSSL, this API signs with some default hash. That default has been
514
    // SHA-256 since 2015.
515
0
    if (!pkcs7_add_external_signature(cbb.get(), sign_cert, pkey, EVP_sha256(),
516
0
                                      data, /*use_key_id=*/false)) {
517
0
      return nullptr;
518
0
    }
519
0
  } else {
520
0
    OPENSSL_PUT_ERROR(PKCS7, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
521
0
    return nullptr;
522
0
  }
523
524
0
  CBS cbs;
525
0
  CBS_init(&cbs, CBB_data(cbb.get()), CBB_len(cbb.get()));
526
0
  return pkcs7_new(&cbs);
527
0
}