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