]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/cmp/cmp_vfy.c
Remove misleading diagnostics on pinned sender cert in OSSL_CMP_validate_msg()
[thirdparty/openssl.git] / crypto / cmp / cmp_vfy.c
1 /*
2 * Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright Nokia 2007-2020
4 * Copyright Siemens AG 2015-2020
5 *
6 * Licensed under the Apache License 2.0 (the "License"). You may not use
7 * this file except in compliance with the License. You can obtain a copy
8 * in the file LICENSE in the source distribution or at
9 * https://www.openssl.org/source/license.html
10 */
11
12 /* CMP functions for PKIMessage checking */
13
14 #include "cmp_local.h"
15 #include <openssl/cmp_util.h>
16
17 /* explicit #includes not strictly needed since implied by the above: */
18 #include <openssl/asn1t.h>
19 #include <openssl/cmp.h>
20 #include <openssl/crmf.h>
21 #include <openssl/err.h>
22 #include <openssl/x509.h>
23 #include "crypto/x509.h"
24
25 DEFINE_STACK_OF(X509)
26
27 /*
28 * Verify a message protected by signature according to section 5.1.3.3
29 * (sha1+RSA/DSA or any other algorithm supported by OpenSSL).
30 *
31 * Returns 1 on successful validation and 0 otherwise.
32 */
33 static int verify_signature(const OSSL_CMP_CTX *cmp_ctx,
34 const OSSL_CMP_MSG *msg, X509 *cert)
35 {
36 EVP_MD_CTX *ctx = NULL;
37 OSSL_CMP_PROTECTEDPART prot_part;
38 int digest_nid, pk_nid;
39 const EVP_MD *digest = NULL;
40 EVP_PKEY *pubkey = NULL;
41 int len;
42 size_t prot_part_der_len = 0;
43 unsigned char *prot_part_der = NULL;
44 BIO *bio = BIO_new(BIO_s_mem()); /* may be NULL */
45 int res = 0;
46
47 if (!ossl_assert(cmp_ctx != NULL && msg != NULL && cert != NULL))
48 return 0;
49
50 /* verify that keyUsage, if present, contains digitalSignature */
51 if (!cmp_ctx->ignore_keyusage
52 && (X509_get_key_usage(cert) & X509v3_KU_DIGITAL_SIGNATURE) == 0) {
53 CMPerr(0, CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE);
54 goto sig_err;
55 }
56
57 pubkey = X509_get_pubkey(cert);
58 if (pubkey == NULL) {
59 CMPerr(0, CMP_R_FAILED_EXTRACTING_PUBKEY);
60 goto sig_err;
61 }
62
63 /* create the DER representation of protected part */
64 prot_part.header = msg->header;
65 prot_part.body = msg->body;
66
67 len = i2d_OSSL_CMP_PROTECTEDPART(&prot_part, &prot_part_der);
68 if (len < 0 || prot_part_der == NULL)
69 goto end;
70 prot_part_der_len = (size_t) len;
71
72 /* verify signature of protected part */
73 if (!OBJ_find_sigid_algs(OBJ_obj2nid(msg->header->protectionAlg->algorithm),
74 &digest_nid, &pk_nid)
75 || digest_nid == NID_undef || pk_nid == NID_undef
76 || (digest = EVP_get_digestbynid(digest_nid)) == NULL) {
77 CMPerr(0, CMP_R_ALGORITHM_NOT_SUPPORTED);
78 goto sig_err;
79 }
80
81 /* check msg->header->protectionAlg is consistent with public key type */
82 if (EVP_PKEY_type(pk_nid) != EVP_PKEY_base_id(pubkey)) {
83 CMPerr(0, CMP_R_WRONG_ALGORITHM_OID);
84 goto sig_err;
85 }
86 if ((ctx = EVP_MD_CTX_new()) == NULL)
87 goto end;
88 if (EVP_DigestVerifyInit(ctx, NULL, digest, NULL, pubkey)
89 && EVP_DigestVerify(ctx, msg->protection->data,
90 msg->protection->length,
91 prot_part_der, prot_part_der_len) == 1) {
92 res = 1;
93 goto end;
94 }
95
96 sig_err:
97 res = x509_print_ex_brief(bio, cert, X509_FLAG_NO_EXTENSIONS);
98 CMPerr(0, CMP_R_ERROR_VALIDATING_SIGNATURE);
99 if (res)
100 ERR_add_error_mem_bio("\n", bio);
101 res = 0;
102
103 end:
104 EVP_MD_CTX_free(ctx);
105 OPENSSL_free(prot_part_der);
106 EVP_PKEY_free(pubkey);
107 BIO_free(bio);
108
109 return res;
110 }
111
112 /* Verify a message protected with PBMAC */
113 static int verify_PBMAC(const OSSL_CMP_MSG *msg,
114 const ASN1_OCTET_STRING *secret)
115 {
116 ASN1_BIT_STRING *protection = NULL;
117 int valid = 0;
118
119 /* generate expected protection for the message */
120 if ((protection = ossl_cmp_calc_protection(msg, secret, NULL)) == NULL)
121 return 0; /* failed to generate protection string! */
122
123 valid = msg->protection != NULL && msg->protection->length >= 0
124 && msg->protection->type == protection->type
125 && msg->protection->length == protection->length
126 && CRYPTO_memcmp(msg->protection->data, protection->data,
127 protection->length) == 0;
128 ASN1_BIT_STRING_free(protection);
129 if (!valid)
130 CMPerr(0, CMP_R_WRONG_PBM_VALUE);
131
132 return valid;
133 }
134
135 /*
136 * Attempt to validate certificate and path using any given store with trusted
137 * certs (possibly including CRLs and a cert verification callback function)
138 * and non-trusted intermediate certs from the given ctx.
139 *
140 * Returns 1 on successful validation and 0 otherwise.
141 */
142 int OSSL_CMP_validate_cert_path(OSSL_CMP_CTX *ctx, X509_STORE *trusted_store,
143 X509 *cert)
144 {
145 int valid = 0;
146 X509_STORE_CTX *csc = NULL;
147 int err;
148
149 if (ctx == NULL || cert == NULL) {
150 CMPerr(0, CMP_R_NULL_ARGUMENT);
151 return 0;
152 }
153
154 if (trusted_store == NULL) {
155 CMPerr(0, CMP_R_MISSING_TRUST_STORE);
156 return 0;
157 }
158
159 if ((csc = X509_STORE_CTX_new()) == NULL
160 || !X509_STORE_CTX_init(csc, trusted_store,
161 cert, ctx->untrusted_certs))
162 goto err;
163
164 valid = X509_verify_cert(csc) > 0;
165
166 /* make sure suitable error is queued even if callback did not do */
167 err = ERR_peek_last_error();
168 if (!valid && ERR_GET_REASON(err) != CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
169 CMPerr(0, CMP_R_POTENTIALLY_INVALID_CERTIFICATE);
170
171 err:
172 /* directly output any fresh errors, needed for check_msg_find_cert() */
173 OSSL_CMP_CTX_print_errors(ctx);
174 X509_STORE_CTX_free(csc);
175 return valid;
176 }
177
178 /* Return 0 if expect_name != NULL and there is no matching actual_name */
179 static int check_name(OSSL_CMP_CTX *ctx,
180 const char *actual_desc, const X509_NAME *actual_name,
181 const char *expect_desc, const X509_NAME *expect_name)
182 {
183 char *str;
184
185 if (expect_name == NULL)
186 return 1; /* no expectation, thus trivially fulfilled */
187
188 /* make sure that a matching name is there */
189 if (actual_name == NULL) {
190 ossl_cmp_log1(WARN, ctx, "missing %s", actual_desc);
191 return 0;
192 }
193 if (X509_NAME_cmp(actual_name, expect_name) == 0)
194 return 1;
195
196 if ((str = X509_NAME_oneline(actual_name, NULL, 0)) != NULL)
197 ossl_cmp_log2(INFO, ctx, " actual name in %s = %s", actual_desc, str);
198 OPENSSL_free(str);
199 if ((str = X509_NAME_oneline(expect_name, NULL, 0)) != NULL)
200 ossl_cmp_log2(INFO, ctx, " does not match %s = %s", expect_desc, str);
201 OPENSSL_free(str);
202 return 0;
203 }
204
205 /* Return 0 if skid != NULL and there is no matching subject key ID in cert */
206 static int check_kid(OSSL_CMP_CTX *ctx,
207 X509 *cert, const ASN1_OCTET_STRING *skid)
208 {
209 char *actual, *expect;
210 const ASN1_OCTET_STRING *ckid = X509_get0_subject_key_id(cert);
211
212 if (skid == NULL)
213 return 1; /* no expectation, thus trivially fulfilled */
214
215 /* make sure that the expected subject key identifier is there */
216 if (ckid == NULL) {
217 ossl_cmp_warn(ctx, "missing Subject Key Identifier in certificate");
218 return 0;
219 }
220 if (ASN1_OCTET_STRING_cmp(ckid, skid) == 0)
221 return 1;
222
223 if ((actual = OPENSSL_buf2hexstr(ckid->data, ckid->length)) != NULL)
224 ossl_cmp_log1(INFO, ctx, " cert Subject Key Identifier = %s", actual);
225 if ((expect = OPENSSL_buf2hexstr(skid->data, skid->length)) != NULL)
226 ossl_cmp_log1(INFO, ctx, " does not match senderKID = %s", expect);
227 OPENSSL_free(expect);
228 OPENSSL_free(actual);
229 return 0;
230 }
231
232 static int already_checked(X509 *cert, const STACK_OF(X509) *already_checked)
233 {
234 int i;
235
236 for (i = sk_X509_num(already_checked /* may be NULL */); i > 0; i--)
237 if (X509_cmp(sk_X509_value(already_checked, i - 1), cert) == 0)
238 return 1;
239 return 0;
240 }
241
242 /*
243 * Check if the given cert is acceptable as sender cert of the given message.
244 * The subject DN must match, the subject key ID as well if present in the msg,
245 * and the cert must be current (checked if ctx->trusted is not NULL).
246 * Note that cert revocation etc. is checked by OSSL_CMP_validate_cert_path().
247 *
248 * Returns 0 on error or not acceptable, else 1.
249 */
250 static int cert_acceptable(OSSL_CMP_CTX *ctx,
251 const char *desc1, const char *desc2, X509 *cert,
252 const STACK_OF(X509) *already_checked1,
253 const STACK_OF(X509) *already_checked2,
254 const OSSL_CMP_MSG *msg)
255 {
256 X509_STORE *ts = ctx->trusted;
257 int self_issued = X509_check_issued(cert, cert) == X509_V_OK;
258 char *str;
259 X509_VERIFY_PARAM *vpm = ts != NULL ? X509_STORE_get0_param(ts) : NULL;
260 int time_cmp;
261
262 ossl_cmp_log3(INFO, ctx, " considering %s%s %s with..",
263 self_issued ? "self-issued ": "", desc1, desc2);
264 if ((str = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0)) != NULL)
265 ossl_cmp_log1(INFO, ctx, " subject = %s", str);
266 OPENSSL_free(str);
267 if (!self_issued) {
268 str = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
269 if (str != NULL)
270 ossl_cmp_log1(INFO, ctx, " issuer = %s", str);
271 OPENSSL_free(str);
272 }
273
274 if (already_checked(cert, already_checked1)
275 || already_checked(cert, already_checked2)) {
276 ossl_cmp_info(ctx, " cert has already been checked");
277 return 0;
278 }
279
280 time_cmp = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
281 X509_get0_notAfter(cert));
282 if (time_cmp != 0) {
283 ossl_cmp_warn(ctx, time_cmp > 0 ? "cert has expired"
284 : "cert is not yet valid");
285 return 0;
286 }
287
288 if (!check_name(ctx,
289 "cert subject", X509_get_subject_name(cert),
290 "sender field", msg->header->sender->d.directoryName))
291 return 0;
292
293 if (!check_kid(ctx, cert, msg->header->senderKID))
294 return 0;
295 /* acceptable also if there is no senderKID in msg header */
296 ossl_cmp_info(ctx, " cert seems acceptable");
297 return 1;
298 }
299
300 static int check_msg_valid_cert(OSSL_CMP_CTX *ctx, X509_STORE *store,
301 X509 *scrt, const OSSL_CMP_MSG *msg)
302 {
303 if (!verify_signature(ctx, msg, scrt)) {
304 ossl_cmp_warn(ctx, "msg signature verification failed");
305 return 0;
306 }
307 if (OSSL_CMP_validate_cert_path(ctx, store, scrt))
308 return 1;
309
310 ossl_cmp_warn(ctx,
311 "msg signature validates but cert path validation failed");
312 return 0;
313 }
314
315 /*
316 * Exceptional handling for 3GPP TS 33.310 [3G/LTE Network Domain Security
317 * (NDS); Authentication Framework (AF)], only to use for IP messages
318 * and if the ctx option is explicitly set: use self-issued certificates
319 * from extraCerts as trust anchor to validate sender cert and msg -
320 * provided it also can validate the newly enrolled certificate
321 */
322 static int check_msg_valid_cert_3gpp(OSSL_CMP_CTX *ctx, X509 *scrt,
323 const OSSL_CMP_MSG *msg)
324 {
325 int valid = 0;
326 X509_STORE *store;
327
328 if (!ctx->permitTAInExtraCertsForIR)
329 return 0;
330
331 if ((store = X509_STORE_new()) == NULL
332 || !ossl_cmp_X509_STORE_add1_certs(store, msg->extraCerts,
333 1 /* self-issued only */))
334 goto err;
335
336 /* store does not include CRLs */
337 valid = OSSL_CMP_validate_cert_path(ctx, store, scrt);
338 if (!valid) {
339 ossl_cmp_warn(ctx,
340 "also exceptional 3GPP mode cert path validation failed");
341 } else {
342 /*
343 * verify that the newly enrolled certificate (which assumed rid ==
344 * OSSL_CMP_CERTREQID) can also be validated with the same trusted store
345 */
346 EVP_PKEY *privkey = OSSL_CMP_CTX_get0_newPkey(ctx, 1);
347 OSSL_CMP_CERTRESPONSE *crep =
348 ossl_cmp_certrepmessage_get0_certresponse(msg->body->value.ip,
349 OSSL_CMP_CERTREQID);
350 X509 *newcrt = ossl_cmp_certresponse_get1_certificate(privkey, crep);
351 /*
352 * maybe better use get_cert_status() from cmp_client.c, which catches
353 * errors
354 */
355 valid = OSSL_CMP_validate_cert_path(ctx, store, newcrt);
356 X509_free(newcrt);
357 }
358
359 err:
360 X509_STORE_free(store);
361 return valid;
362 }
363
364 /*
365 * Try all certs in given list for verifying msg, normally or in 3GPP mode.
366 * If already_checked1 == NULL then certs are assumed to be the msg->extraCerts.
367 */
368 static int check_msg_with_certs(OSSL_CMP_CTX *ctx, STACK_OF(X509) *certs,
369 const char *desc,
370 const STACK_OF(X509) *already_checked1,
371 const STACK_OF(X509) *already_checked2,
372 const OSSL_CMP_MSG *msg, int mode_3gpp)
373 {
374 int in_extraCerts = already_checked1 == NULL;
375 int n_acceptable_certs = 0;
376 int i;
377
378 if (sk_X509_num(certs) <= 0) {
379 ossl_cmp_log1(WARN, ctx, "no %s", desc);
380 return 0;
381 }
382
383 for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */
384 X509 *cert = sk_X509_value(certs, i);
385
386 if (!ossl_assert(cert != NULL))
387 return 0;
388 if (!cert_acceptable(ctx, "cert from", desc, cert,
389 already_checked1, already_checked2, msg))
390 continue;
391 n_acceptable_certs++;
392 if (mode_3gpp ? check_msg_valid_cert_3gpp(ctx, cert, msg)
393 : check_msg_valid_cert(ctx, ctx->trusted, cert, msg)) {
394 /* store successful sender cert for further msgs in transaction */
395 if (!X509_up_ref(cert))
396 return 0;
397 if (!ossl_cmp_ctx_set0_validatedSrvCert(ctx, cert)) {
398 X509_free(cert);
399 return 0;
400 }
401 return 1;
402 }
403 }
404 if (in_extraCerts && n_acceptable_certs == 0)
405 ossl_cmp_warn(ctx, "no acceptable cert in extraCerts");
406 return 0;
407 }
408
409 /*
410 * Verify msg trying first ctx->untrusted_certs, which should include extraCerts
411 * at its front, then trying the trusted certs in truststore (if any) of ctx.
412 */
413 static int check_msg_all_certs(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
414 int mode_3gpp)
415 {
416 int ret = 0;
417
418 if (mode_3gpp
419 && ((!ctx->permitTAInExtraCertsForIR
420 || ossl_cmp_msg_get_bodytype(msg) != OSSL_CMP_PKIBODY_IP)))
421 return 0;
422
423 ossl_cmp_info(ctx,
424 mode_3gpp ? "normal mode failed; trying now 3GPP mode trusting extraCerts"
425 : "trying first normal mode using trust store");
426 if (check_msg_with_certs(ctx, msg->extraCerts, "extraCerts",
427 NULL, NULL, msg, mode_3gpp))
428 return 1;
429 if (check_msg_with_certs(ctx, ctx->untrusted_certs, "untrusted certs",
430 msg->extraCerts, NULL, msg, mode_3gpp))
431 return 1;
432
433 if (ctx->trusted == NULL) {
434 ossl_cmp_warn(ctx, mode_3gpp ? "no self-issued extraCerts"
435 : "no trusted store");
436 } else {
437 STACK_OF(X509) *trusted = X509_STORE_get1_all_certs(ctx->trusted);
438 ret = check_msg_with_certs(ctx, trusted,
439 mode_3gpp ? "self-issued extraCerts"
440 : "certs in trusted store",
441 msg->extraCerts, ctx->untrusted_certs,
442 msg, mode_3gpp);
443 sk_X509_pop_free(trusted, X509_free);
444 }
445 return ret;
446 }
447
448 static int no_log_cb(const char *func, const char *file, int line,
449 OSSL_CMP_severity level, const char *msg)
450 {
451 return 1;
452 }
453
454 /* verify message signature with any acceptable and valid candidate cert */
455 static int check_msg_find_cert(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
456 {
457 X509 *scrt = ctx->validatedSrvCert; /* previous successful sender cert */
458 GENERAL_NAME *sender = msg->header->sender;
459 char *sname = NULL;
460 char *skid_str = NULL;
461 const ASN1_OCTET_STRING *skid = msg->header->senderKID;
462 OSSL_CMP_log_cb_t backup_log_cb = ctx->log_cb;
463 int res = 0;
464
465 if (sender == NULL || msg->body == NULL)
466 return 0; /* other NULL cases already have been checked */
467 if (sender->type != GEN_DIRNAME) {
468 CMPerr(0, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
469 return 0;
470 }
471
472 /* dump any hitherto errors to avoid confusion when printing further ones */
473 OSSL_CMP_CTX_print_errors(ctx);
474
475 /*
476 * try first cached scrt, used successfully earlier in same transaction,
477 * for validating this and any further msgs where extraCerts may be left out
478 */
479 if (scrt != NULL) {
480 (void)ERR_set_mark();
481 ossl_cmp_info(ctx,
482 "trying to verify msg signature with previously validated cert");
483 if (cert_acceptable(ctx, "previously validated", "sender cert", scrt,
484 NULL, NULL, msg)
485 && (check_msg_valid_cert(ctx, ctx->trusted, scrt, msg)
486 || check_msg_valid_cert_3gpp(ctx, scrt, msg))) {
487 (void)ERR_pop_to_mark();
488 return 1;
489 }
490 (void)ERR_pop_to_mark();
491 /* cached sender cert has shown to be no more successfully usable */
492 (void)ossl_cmp_ctx_set0_validatedSrvCert(ctx, NULL);
493 }
494
495 /* enable clearing irrelevant errors in attempts to validate sender certs */
496 (void)ERR_set_mark();
497 ctx->log_cb = no_log_cb; /* temporarily disable logging */
498 res = check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */)
499 || check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
500 ctx->log_cb = backup_log_cb;
501 if (res) {
502 /* discard any diagnostic information on trying to use certs */
503 (void)ERR_pop_to_mark();
504 goto end;
505 }
506 /* failed finding a sender cert that verifies the message signature */
507 (void)ERR_clear_last_mark();
508
509 sname = X509_NAME_oneline(sender->d.directoryName, NULL, 0);
510 skid_str = skid == NULL ? NULL
511 : OPENSSL_buf2hexstr(skid->data, skid->length);
512 if (ctx->log_cb != NULL) {
513 ossl_cmp_info(ctx, "trying to verify msg signature with a valid cert that..");
514 if (sname != NULL)
515 ossl_cmp_log1(INFO, ctx, "matches msg sender = %s", sname);
516 if (skid_str != NULL)
517 ossl_cmp_log1(INFO, ctx, "matches msg senderKID = %s", skid_str);
518 else
519 ossl_cmp_info(ctx, "while msg header does not contain senderKID");
520 /* re-do the above checks (just) for adding diagnostic information */
521 check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */);
522 check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
523 }
524
525 CMPerr(0, CMP_R_NO_SUITABLE_SENDER_CERT);
526 if (sname != NULL) {
527 ERR_add_error_txt(NULL, "for msg sender name = ");
528 ERR_add_error_txt(NULL, sname);
529 }
530 if (skid_str != NULL) {
531 ERR_add_error_txt(" and ", "for msg senderKID = ");
532 ERR_add_error_txt(NULL, skid_str);
533 }
534
535 end:
536 OPENSSL_free(sname);
537 OPENSSL_free(skid_str);
538 return res;
539 }
540
541 /*
542 * Validate the protection of the given PKIMessage using either password-
543 * based mac (PBM) or a signature algorithm. In the case of signature algorithm,
544 * the sender certificate can have been pinned by providing it in ctx->srvCert,
545 * else it is searched in msg->extraCerts, ctx->untrusted_certs, in ctx->trusted
546 * (in this order) and is path is validated against ctx->trusted.
547 *
548 * If ctx->permitTAInExtraCertsForIR is true and when validating a CMP IP msg,
549 * the trust anchor for validating the IP msg may be taken from msg->extraCerts
550 * if a self-issued certificate is found there that can be used to
551 * validate the enrolled certificate returned in the IP.
552 * This is according to the need given in 3GPP TS 33.310.
553 *
554 * Returns 1 on success, 0 on error or validation failed.
555 */
556 int OSSL_CMP_validate_msg(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
557 {
558 X509_ALGOR *alg;
559 int nid = NID_undef, pk_nid = NID_undef;
560 const ASN1_OBJECT *algorOID = NULL;
561 X509 *scrt;
562 const X509_NAME *expected_sender;
563
564 if (ctx == NULL || msg == NULL
565 || msg->header == NULL || msg->body == NULL) {
566 CMPerr(0, CMP_R_NULL_ARGUMENT);
567 return 0;
568 }
569
570 /* validate sender name of received msg */
571 if (msg->header->sender->type != GEN_DIRNAME) {
572 CMPerr(0, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
573 return 0; /* TODO FR#42: support for more than X509_NAME */
574 }
575 /*
576 * Compare actual sender name of response with expected sender name.
577 * Mitigates risk to accept misused PBM secret
578 * or misused certificate of an unauthorized entity of a trusted hierarchy.
579 */
580 expected_sender = ctx->expected_sender;
581 if (expected_sender == NULL && ctx->srvCert != NULL)
582 expected_sender = X509_get_subject_name(ctx->srvCert);
583 if (!check_name(ctx, "sender DN field",
584 msg->header->sender->d.directoryName,
585 "expected sender", expected_sender))
586 return 0;
587 /* Note: if recipient was NULL-DN it could be learned here if needed */
588
589 if ((alg = msg->header->protectionAlg) == NULL /* unprotected message */
590 || msg->protection == NULL || msg->protection->data == NULL) {
591 CMPerr(0, CMP_R_MISSING_PROTECTION);
592 return 0;
593 }
594
595 /* determine the nid for the used protection algorithm */
596 X509_ALGOR_get0(&algorOID, NULL, NULL, alg);
597 nid = OBJ_obj2nid(algorOID);
598
599 switch (nid) {
600 /* 5.1.3.1. Shared Secret Information */
601 case NID_id_PasswordBasedMAC:
602 if (ctx->secretValue == 0) {
603 CMPerr(0, CMP_R_CHECKING_PBM_NO_SECRET_AVAILABLE);
604 break;
605 }
606
607 if (verify_PBMAC(msg, ctx->secretValue)) {
608 /*
609 * RFC 4210, 5.3.2: 'Note that if the PKI Message Protection is
610 * "shared secret information", then any certificate transported in
611 * the caPubs field may be directly trusted as a root CA
612 * certificate by the initiator.'
613 */
614 switch (ossl_cmp_msg_get_bodytype(msg)) {
615 case -1:
616 return 0;
617 case OSSL_CMP_PKIBODY_IP:
618 case OSSL_CMP_PKIBODY_CP:
619 case OSSL_CMP_PKIBODY_KUP:
620 case OSSL_CMP_PKIBODY_CCP:
621 if (ctx->trusted != NULL) {
622 STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
623 /* value.ip is same for cp, kup, and ccp */
624
625 if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
626 /* adds both self-issued and not self-issued certs */
627 return 0;
628 }
629 break;
630 default:
631 break;
632 }
633 return 1;
634 }
635 break;
636
637 /*
638 * 5.1.3.2 DH Key Pairs
639 * Not yet supported
640 */
641 case NID_id_DHBasedMac:
642 CMPerr(0, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC);
643 break;
644
645 /*
646 * 5.1.3.3. Signature
647 */
648 default:
649 if (!OBJ_find_sigid_algs(OBJ_obj2nid(alg->algorithm), NULL, &pk_nid)
650 || pk_nid == NID_undef) {
651 CMPerr(0, CMP_R_UNKNOWN_ALGORITHM_ID);
652 break;
653 }
654 scrt = ctx->srvCert;
655 if (scrt == NULL) {
656 if (check_msg_find_cert(ctx, msg))
657 return 1;
658 } else { /* use pinned sender cert */
659 /* use ctx->srvCert for signature check even if not acceptable */
660 if (verify_signature(ctx, msg, scrt))
661 return 1;
662 ossl_cmp_warn(ctx, "msg signature verification failed");
663 CMPerr(0, CMP_R_SRVCERT_DOES_NOT_VALIDATE_MSG);
664 }
665 break;
666 }
667 return 0;
668 }
669
670
671 /*-
672 * Check received message (i.e., response by server or request from client)
673 * Any msg->extraCerts are prepended to ctx->untrusted_certs
674 *
675 * Ensures that:
676 * it has a valid body type
677 * its protection is valid (or invalid/absent, but only if a callback function
678 * is present and yields a positive result using also the supplied argument)
679 * its transaction ID matches the previous transaction ID stored in ctx (if any)
680 * its recipNonce matches the previous senderNonce stored in the ctx (if any)
681 *
682 * If everything is fine:
683 * learns the senderNonce from the received message,
684 * learns the transaction ID if it is not yet in ctx.
685 *
686 * returns body type (which is >= 0) of the message on success, -1 on error
687 */
688 int ossl_cmp_msg_check_received(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
689 ossl_cmp_allow_unprotected_cb_t cb, int cb_arg)
690 {
691 int rcvd_type;
692
693 if (!ossl_assert(ctx != NULL && msg != NULL))
694 return -1;
695
696 if (sk_X509_num(msg->extraCerts) > 10)
697 ossl_cmp_warn(ctx,
698 "received CMP message contains more than 10 extraCerts");
699
700 /* validate message protection */
701 if (msg->header->protectionAlg != 0) {
702 /* detect explicitly permitted exceptions for invalid protection */
703 if (!OSSL_CMP_validate_msg(ctx, msg)
704 && (cb == NULL || (*cb)(ctx, msg, 1, cb_arg) <= 0)) {
705 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
706 CMPerr(0, CMP_R_ERROR_VALIDATING_PROTECTION);
707 return -1;
708 #endif
709 }
710 } else {
711 /* detect explicitly permitted exceptions for missing protection */
712 if (cb == NULL || (*cb)(ctx, msg, 0, cb_arg) <= 0) {
713 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
714 CMPerr(0, CMP_R_MISSING_PROTECTION);
715 return -1;
716 #endif
717 }
718 }
719
720 /* check CMP version number in header */
721 if (ossl_cmp_hdr_get_pvno(OSSL_CMP_MSG_get0_header(msg)) != OSSL_CMP_PVNO) {
722 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
723 CMPerr(0, CMP_R_UNEXPECTED_PVNO);
724 return -1;
725 #endif
726 }
727
728 if ((rcvd_type = ossl_cmp_msg_get_bodytype(msg)) < 0) {
729 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
730 CMPerr(0, CMP_R_PKIBODY_ERROR);
731 return -1;
732 #endif
733 }
734
735 /* compare received transactionID with the expected one in previous msg */
736 if (ctx->transactionID != NULL
737 && (msg->header->transactionID == NULL
738 || ASN1_OCTET_STRING_cmp(ctx->transactionID,
739 msg->header->transactionID) != 0)) {
740 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
741 CMPerr(0, CMP_R_TRANSACTIONID_UNMATCHED);
742 return -1;
743 #endif
744 }
745
746 /* compare received nonce with the one we sent */
747 if (ctx->senderNonce != NULL
748 && (msg->header->recipNonce == NULL
749 || ASN1_OCTET_STRING_cmp(ctx->senderNonce,
750 msg->header->recipNonce) != 0)) {
751 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
752 CMPerr(0, CMP_R_RECIPNONCE_UNMATCHED);
753 return -1;
754 #endif
755 }
756
757 /*
758 * RFC 4210 section 5.1.1 states: the recipNonce is copied from
759 * the senderNonce of the previous message in the transaction.
760 * --> Store for setting in next message
761 */
762 if (!ossl_cmp_ctx_set1_recipNonce(ctx, msg->header->senderNonce))
763 return -1;
764
765 /* if not yet present, learn transactionID */
766 if (ctx->transactionID == NULL
767 && !OSSL_CMP_CTX_set1_transactionID(ctx, msg->header->transactionID))
768 return -1;
769
770 /*
771 * Store any provided extraCerts in ctx for future use,
772 * such that they are available to ctx->certConf_cb and
773 * the peer does not need to send them again in the same transaction.
774 * For efficiency, the extraCerts are prepended so they get used first.
775 */
776 if (!ossl_cmp_sk_X509_add1_certs(ctx->untrusted_certs, msg->extraCerts,
777 0 /* this allows self-issued certs */,
778 1 /* no_dups */, 1 /* prepend */))
779 return -1;
780
781 return rcvd_type;
782 }
783
784 int ossl_cmp_verify_popo(const OSSL_CMP_MSG *msg, int accept_RAVerified)
785 {
786 if (!ossl_assert(msg != NULL && msg->body != NULL))
787 return 0;
788 switch (msg->body->type) {
789 case OSSL_CMP_PKIBODY_P10CR:
790 {
791 X509_REQ *req = msg->body->value.p10cr;
792
793 if (X509_REQ_verify(req, X509_REQ_get0_pubkey(req)) <= 0) {
794 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
795 CMPerr(0, CMP_R_REQUEST_NOT_ACCEPTED);
796 return 0;
797 #endif
798 }
799 }
800 break;
801 case OSSL_CMP_PKIBODY_IR:
802 case OSSL_CMP_PKIBODY_CR:
803 case OSSL_CMP_PKIBODY_KUR:
804 if (!OSSL_CRMF_MSGS_verify_popo(msg->body->value.ir, OSSL_CMP_CERTREQID,
805 accept_RAVerified)) {
806 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
807 return 0;
808 #endif
809 }
810 break;
811 default:
812 CMPerr(0, CMP_R_PKIBODY_ERROR);
813 return 0;
814 }
815 return 1;
816 }