Debian Codegraph @

debian/rust-vendor/openssl-src/openssl/crypto/cmp/cmp_vfy.c

raw
1 /*
2 * Copyright 2007-2026 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
16 /* Verify a message protected by signature according to RFC section 5.1.3.3 */
17 static int verify_signature(const OSSL_CMP_CTX *cmp_ctx,
18 const OSSL_CMP_MSG *msg, X509 *cert)
19 {
20 OSSL_CMP_PROTECTEDPART prot_part;
21 EVP_PKEY *pubkey = NULL;
22 BIO *bio;
23 int res = 0;
24
25 if (!ossl_assert(cmp_ctx != NULL && msg != NULL && cert != NULL))
26 return 0;
27
28 bio = BIO_new(BIO_s_mem()); /* may be NULL */
29 if (bio == NULL)
30 return 0;
31 /* verify that keyUsage, if present, contains digitalSignature */
32 if (!cmp_ctx->ignore_keyusage
33 && (X509_get_key_usage(cert) & X509v3_KU_DIGITAL_SIGNATURE) == 0) {
34 ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE);
35 goto sig_err;
36 }
37
38 pubkey = X509_get_pubkey(cert);
39 if (pubkey == NULL) {
40 ERR_raise(ERR_LIB_CMP, CMP_R_FAILED_EXTRACTING_PUBKEY);
41 goto sig_err;
42 }
43
44 prot_part.header = msg->header;
45 prot_part.body = msg->body;
46
47 if (ASN1_item_verify_ex(ASN1_ITEM_rptr(OSSL_CMP_PROTECTEDPART),
48 msg->header->protectionAlg, msg->protection,
49 &prot_part, NULL, pubkey, cmp_ctx->libctx,
50 cmp_ctx->propq)
51 > 0) {
52 res = 1;
53 goto end;
54 }
55
56 sig_err:
57 res = ossl_x509_print_ex_brief(bio, cert, X509_FLAG_NO_EXTENSIONS);
58 ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_SIGNATURE);
59 if (res)
60 ERR_add_error_mem_bio("\n", bio);
61 res = 0;
62
63 end:
64 EVP_PKEY_free(pubkey);
65 BIO_free(bio);
66
67 return res;
68 }
69
70 /* Verify a message protected with PBMAC */
71 static int verify_PBMAC(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
72 {
73 ASN1_BIT_STRING *protection = NULL;
74 int valid = 0;
75
76 /* generate expected protection for the message */
77 if ((protection = ossl_cmp_calc_protection(ctx, msg)) == NULL)
78 return 0; /* failed to generate protection string! */
79
80 valid = msg->protection != NULL && msg->protection->length >= 0
81 && msg->protection->type == protection->type
82 && msg->protection->length == protection->length
83 && CRYPTO_memcmp(msg->protection->data, protection->data,
84 protection->length)
85 == 0;
86 ASN1_BIT_STRING_free(protection);
87 if (!valid)
88 ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_PBM_VALUE);
89
90 return valid;
91 }
92
93 /*-
94 * Attempt to validate certificate and path using any given store with trusted
95 * certs (possibly including CRLs and a cert verification callback function)
96 * and non-trusted intermediate certs from the given ctx.
97 *
98 * Returns 1 on successful validation and 0 otherwise.
99 */
100 int OSSL_CMP_validate_cert_path(const OSSL_CMP_CTX *ctx,
101 X509_STORE *trusted_store, X509 *cert)
102 {
103 int valid = 0;
104 X509_STORE_CTX *csc = NULL;
105 int err;
106
107 if (ctx == NULL || cert == NULL) {
108 ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
109 return 0;
110 }
111
112 if (trusted_store == NULL) {
113 ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_STORE);
114 return 0;
115 }
116
117 if ((csc = X509_STORE_CTX_new_ex(ctx->libctx, ctx->propq)) == NULL
118 || !X509_STORE_CTX_init(csc, trusted_store,
119 cert, ctx->untrusted))
120 goto err;
121
122 valid = X509_verify_cert(csc) > 0;
123
124 /* make sure suitable error is queued even if callback did not do */
125 err = ERR_peek_last_error();
126 if (!valid && ERR_GET_REASON(err) != CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
127 ERR_raise(ERR_LIB_CMP, CMP_R_POTENTIALLY_INVALID_CERTIFICATE);
128
129 err:
130 /* directly output any fresh errors, needed for check_msg_find_cert() */
131 OSSL_CMP_CTX_print_errors(ctx);
132 X509_STORE_CTX_free(csc);
133 return valid;
134 }
135
136 static int verify_cb_cert(X509_STORE *ts, X509 *cert, int err)
137 {
138 X509_STORE_CTX_verify_cb verify_cb;
139 X509_STORE_CTX *csc;
140 int ok = 0;
141
142 if (ts == NULL || (verify_cb = X509_STORE_get_verify_cb(ts)) == NULL)
143 return ok;
144 if ((csc = X509_STORE_CTX_new()) != NULL
145 && X509_STORE_CTX_init(csc, ts, cert, NULL)) {
146 X509_STORE_CTX_set_error(csc, err);
147 X509_STORE_CTX_set_current_cert(csc, cert);
148 ok = (*verify_cb)(0, csc);
149 }
150 X509_STORE_CTX_free(csc);
151 return ok;
152 }
153
154 /* Return 0 if expect_name != NULL and there is no matching actual_name */
155 static int check_name(const OSSL_CMP_CTX *ctx, int log_success,
156 const char *actual_desc, const X509_NAME *actual_name,
157 const char *expect_desc, const X509_NAME *expect_name)
158 {
159 char *str;
160
161 if (expect_name == NULL)
162 return 1; /* no expectation, thus trivially fulfilled */
163
164 /* make sure that a matching name is there */
165 if (actual_name == NULL) {
166 ossl_cmp_log1(WARN, ctx, "missing %s", actual_desc);
167 return 0;
168 }
169 str = X509_NAME_oneline(actual_name, NULL, 0);
170 if (X509_NAME_cmp(actual_name, expect_name) == 0) {
171 if (log_success && str != NULL)
172 ossl_cmp_log3(INFO, ctx, " %s matches %s: %s",
173 actual_desc, expect_desc, str);
174 OPENSSL_free(str);
175 return 1;
176 }
177
178 if (str != NULL)
179 ossl_cmp_log2(INFO, ctx, " actual name in %s = %s", actual_desc, str);
180 OPENSSL_free(str);
181 if ((str = X509_NAME_oneline(expect_name, NULL, 0)) != NULL)
182 ossl_cmp_log2(INFO, ctx, " does not match %s = %s", expect_desc, str);
183 OPENSSL_free(str);
184 return 0;
185 }
186
187 /* Return 0 if skid != NULL and there is no matching subject key ID in cert */
188 static int check_kid(const OSSL_CMP_CTX *ctx,
189 const ASN1_OCTET_STRING *ckid,
190 const ASN1_OCTET_STRING *skid)
191 {
192 char *str;
193
194 if (skid == NULL)
195 return 1; /* no expectation, thus trivially fulfilled */
196
197 /* make sure that the expected subject key identifier is there */
198 if (ckid == NULL) {
199 ossl_cmp_warn(ctx, "missing Subject Key Identifier in certificate");
200 return 0;
201 }
202 str = i2s_ASN1_OCTET_STRING(NULL, ckid);
203 if (ASN1_OCTET_STRING_cmp(ckid, skid) == 0) {
204 if (str != NULL)
205 ossl_cmp_log1(INFO, ctx, " subjectKID matches senderKID: %s", str);
206 OPENSSL_free(str);
207 return 1;
208 }
209
210 if (str != NULL)
211 ossl_cmp_log1(INFO, ctx, " cert Subject Key Identifier = %s", str);
212 OPENSSL_free(str);
213 if ((str = i2s_ASN1_OCTET_STRING(NULL, skid)) != NULL)
214 ossl_cmp_log1(INFO, ctx, " does not match senderKID = %s", str);
215 OPENSSL_free(str);
216 return 0;
217 }
218
219 static int already_checked(const X509 *cert,
220 const STACK_OF(X509) *already_checked)
221 {
222 int i;
223
224 for (i = sk_X509_num(already_checked /* may be NULL */); i > 0; i--)
225 if (X509_cmp(sk_X509_value(already_checked, i - 1), cert) == 0)
226 return 1;
227 return 0;
228 }
229
230 /*-
231 * Check if the given cert is acceptable as sender cert of the given message.
232 * The subject DN must match, the subject key ID as well if present in the msg,
233 * and the cert must be current (checked if ctx->trusted is not NULL).
234 * Note that cert revocation etc. is checked by OSSL_CMP_validate_cert_path().
235 *
236 * Returns 0 on error or not acceptable, else 1.
237 */
238 static int cert_acceptable(const OSSL_CMP_CTX *ctx,
239 const char *desc1, const char *desc2, X509 *cert,
240 const STACK_OF(X509) *already_checked1,
241 const STACK_OF(X509) *already_checked2,
242 const OSSL_CMP_MSG *msg)
243 {
244 X509_STORE *ts = ctx->trusted;
245 int self_issued = X509_check_issued(cert, cert) == X509_V_OK;
246 char *str;
247 X509_VERIFY_PARAM *vpm = ts != NULL ? X509_STORE_get0_param(ts) : NULL;
248 int time_cmp;
249
250 ossl_cmp_log3(INFO, ctx, " considering %s%s %s with..",
251 self_issued ? "self-issued " : "", desc1, desc2);
252 if ((str = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0)) != NULL)
253 ossl_cmp_log1(INFO, ctx, " subject = %s", str);
254 OPENSSL_free(str);
255 if (!self_issued) {
256 str = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
257 if (str != NULL)
258 ossl_cmp_log1(INFO, ctx, " issuer = %s", str);
259 OPENSSL_free(str);
260 }
261
262 if (already_checked(cert, already_checked1)
263 || already_checked(cert, already_checked2)) {
264 ossl_cmp_info(ctx, " cert has already been checked");
265 return 0;
266 }
267
268 time_cmp = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
269 X509_get0_notAfter(cert));
270 if (time_cmp != 0) {
271 int err = time_cmp > 0 ? X509_V_ERR_CERT_HAS_EXPIRED
272 : X509_V_ERR_CERT_NOT_YET_VALID;
273
274 ossl_cmp_warn(ctx, time_cmp > 0 ? "cert has expired" : "cert is not yet valid");
275 if (ctx->log_cb != NULL /* logging not temporarily disabled */
276 && verify_cb_cert(ts, cert, err) <= 0)
277 return 0;
278 }
279
280 if (!check_name(ctx, 1,
281 "cert subject", X509_get_subject_name(cert),
282 "sender field", msg->header->sender->d.directoryName))
283 return 0;
284
285 if (!check_kid(ctx, X509_get0_subject_key_id(cert), msg->header->senderKID))
286 return 0;
287 /* prevent misleading error later in case x509v3_cache_extensions() fails */
288 if (!ossl_x509v3_cache_extensions(cert)) {
289 ossl_cmp_warn(ctx, "cert appears to be invalid");
290 return 0;
291 }
292 if (!verify_signature(ctx, msg, cert)) {
293 ossl_cmp_warn(ctx, "msg signature verification failed");
294 return 0;
295 }
296 /* acceptable also if there is no senderKID in msg header */
297 ossl_cmp_info(ctx, " cert seems acceptable");
298 return 1;
299 }
300
301 static int check_cert_path(const OSSL_CMP_CTX *ctx, X509_STORE *store,
302 X509 *scrt)
303 {
304 if (OSSL_CMP_validate_cert_path(ctx, store, scrt))
305 return 1;
306
307 ossl_cmp_warn(ctx,
308 "msg signature validates but cert path validation failed");
309 return 0;
310 }
311
312 /*
313 * Exceptional handling for 3GPP TS 33.310 [3G/LTE Network Domain Security
314 * (NDS); Authentication Framework (AF)], only to use for IP messages
315 * and if the ctx option is explicitly set: use self-issued certificates
316 * from extraCerts as trust anchor to validate sender cert -
317 * provided it also can validate the newly enrolled certificate
318 */
319 static int check_cert_path_3gpp(const OSSL_CMP_CTX *ctx,
320 const OSSL_CMP_MSG *msg, X509 *scrt)
321 {
322 int valid = 0;
323 X509_STORE *store;
324
325 if (!ctx->permitTAInExtraCertsForIR)
326 return 0;
327
328 if ((store = X509_STORE_new()) == NULL
329 || !ossl_cmp_X509_STORE_add1_certs(store, msg->extraCerts,
330 1 /* self-issued only */))
331 goto err;
332
333 /* store does not include CRLs */
334 valid = OSSL_CMP_validate_cert_path(ctx, store, scrt);
335 if (!valid) {
336 ossl_cmp_warn(ctx,
337 "also exceptional 3GPP mode cert path validation failed");
338 } else if (OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_IP) {
339 /*
340 * verify that the newly enrolled certificate (which assumed rid ==
341 * OSSL_CMP_CERTREQID) can also be validated with the same trusted store
342 */
343 OSSL_CMP_CERTRESPONSE *crep = ossl_cmp_certrepmessage_get0_certresponse(msg->body->value.ip,
344 OSSL_CMP_CERTREQID);
345 X509 *newcrt = NULL;
346
347 valid = crep != NULL
348 && (newcrt = ossl_cmp_certresponse_get1_cert(ctx, crep)) != NULL
349 && OSSL_CMP_validate_cert_path(ctx, store, newcrt);
350 X509_free(newcrt);
351 }
352
353 err:
354 X509_STORE_free(store);
355 return valid;
356 }
357
358 /* checks protection of msg but not cert revocation nor cert chain */
359 static int check_msg_given_cert(const OSSL_CMP_CTX *ctx, X509 *cert,
360 const OSSL_CMP_MSG *msg)
361 {
362 return cert_acceptable(ctx, "previously validated", "sender cert",
363 cert, NULL, NULL, msg);
364 }
365
366 /*-
367 * Try all certs in given list for verifying msg, normally or in 3GPP mode.
368 * If already_checked1 == NULL then certs are assumed to be the msg->extraCerts.
369 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
370 */
371 static int check_msg_with_certs(OSSL_CMP_CTX *ctx, const STACK_OF(X509) *certs,
372 const char *desc,
373 const STACK_OF(X509) *already_checked1,
374 const STACK_OF(X509) *already_checked2,
375 const OSSL_CMP_MSG *msg, int mode_3gpp)
376 {
377 int in_extraCerts = already_checked1 == NULL;
378 int n_acceptable_certs = 0;
379 int i;
380
381 if (sk_X509_num(certs) <= 0) {
382 ossl_cmp_log1(WARN, ctx, "no %s", desc);
383 return 0;
384 }
385
386 for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */
387 X509 *cert = sk_X509_value(certs, i);
388
389 if (!ossl_assert(cert != NULL))
390 return 0;
391 if (!cert_acceptable(ctx, "cert from", desc, cert,
392 already_checked1, already_checked2, msg))
393 continue;
394 n_acceptable_certs++;
395 if (mode_3gpp ? check_cert_path_3gpp(ctx, msg, cert)
396 : check_cert_path(ctx, ctx->trusted, cert)) {
397 /* store successful sender cert for further msgs in transaction */
398 return ossl_cmp_ctx_set1_validatedSrvCert(ctx, cert);
399 }
400 }
401 if (in_extraCerts && n_acceptable_certs == 0)
402 ossl_cmp_warn(ctx, "no acceptable cert in extraCerts");
403 return 0;
404 }
405
406 /*-
407 * Verify msg trying first ctx->untrusted, which should include extraCerts
408 * at its front, then trying the trusted certs in truststore (if any) of ctx.
409 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
410 */
411 static int check_msg_all_certs(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
412 int mode_3gpp)
413 {
414 int ret = 0;
415
416 if (ctx->permitTAInExtraCertsForIR
417 && OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_IP)
418 ossl_cmp_info(ctx, mode_3gpp ? "normal mode failed; trying now 3GPP mode trusting extraCerts" : "trying first normal mode using trust store");
419 else if (mode_3gpp)
420 return 0;
421
422 if (check_msg_with_certs(ctx, msg->extraCerts, "extraCerts",
423 NULL, NULL, msg, mode_3gpp))
424 return 1;
425 if (check_msg_with_certs(ctx, ctx->untrusted, "untrusted certs",
426 msg->extraCerts, NULL, msg, mode_3gpp))
427 return 1;
428
429 if (ctx->trusted == NULL) {
430 ossl_cmp_warn(ctx, mode_3gpp ? "no self-issued extraCerts" : "no trusted store");
431 } else {
432 STACK_OF(X509) *trusted = X509_STORE_get1_all_certs(ctx->trusted);
433
434 ret = check_msg_with_certs(ctx, trusted,
435 mode_3gpp ? "self-issued extraCerts"
436 : "certs in trusted store",
437 msg->extraCerts, ctx->untrusted,
438 msg, mode_3gpp);
439 OSSL_STACK_OF_X509_free(trusted);
440 }
441 return ret;
442 }
443
444 /*-
445 * Verify message signature with any acceptable and valid candidate cert.
446 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
447 */
448 static int check_msg_find_cert(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
449 {
450 X509 *scrt = ctx->validatedSrvCert; /* previous successful sender cert */
451 GENERAL_NAME *sender = msg->header->sender;
452 char *sname = NULL;
453 char *skid_str = NULL;
454 const ASN1_OCTET_STRING *skid = msg->header->senderKID;
455 OSSL_CMP_log_cb_t backup_log_cb = ctx->log_cb;
456 int res = 0;
457
458 if (sender == NULL || msg->body == NULL)
459 return 0; /* other NULL cases already have been checked */
460 if (sender->type != GEN_DIRNAME) {
461 /* So far, only X509_NAME is supported */
462 ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
463 return 0;
464 }
465
466 /* dump any hitherto errors to avoid confusion when printing further ones */
467 OSSL_CMP_CTX_print_errors(ctx);
468
469 /* enable clearing irrelevant errors in attempts to validate sender certs */
470 (void)ERR_set_mark();
471 ctx->log_cb = NULL; /* temporarily disable logging */
472
473 if (scrt != NULL) {
474 /*-
475 * try first using cached message sender cert (in 'scrt' variable),
476 * which was used successfully earlier in the same transaction
477 * (assuming that the certificate itself was not revoked meanwhile and
478 * is a good guess for use in validating also the current message)
479 */
480 if (check_msg_given_cert(ctx, scrt, msg)) {
481 ctx->log_cb = backup_log_cb;
482 (void)ERR_pop_to_mark();
483 return 1;
484 }
485 /* cached sender cert has shown to be no more successfully usable */
486 /* re-do the above check (just) for adding diagnostic information */
487 ossl_cmp_info(ctx,
488 "trying to verify msg signature with previously validated cert");
489 ctx->log_cb = backup_log_cb;
490 (void)check_msg_given_cert(ctx, scrt, msg);
491 ctx->log_cb = NULL;
492 (void)ossl_cmp_ctx_set1_validatedSrvCert(ctx, NULL); /* this invalidates scrt */
493 }
494
495 res = check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */)
496 || check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
497 ctx->log_cb = backup_log_cb;
498 if (res) {
499 /* discard any diagnostic information on trying to use certs */
500 (void)ERR_pop_to_mark();
501 goto end;
502 }
503 /* failed finding a sender cert that verifies the message signature */
504 (void)ERR_clear_last_mark();
505
506 sname = X509_NAME_oneline(sender->d.directoryName, NULL, 0);
507 skid_str = skid == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, skid);
508 if (ctx->log_cb != NULL) {
509 ossl_cmp_info(ctx, "trying to verify msg signature with a valid cert that..");
510 if (sname != NULL)
511 ossl_cmp_log1(INFO, ctx, "matches msg sender = %s", sname);
512 if (skid_str != NULL)
513 ossl_cmp_log1(INFO, ctx, "matches msg senderKID = %s", skid_str);
514 else
515 ossl_cmp_info(ctx, "while msg header does not contain senderKID");
516 /* re-do the above checks (just) for adding diagnostic information */
517 (void)check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */);
518 (void)check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
519 }
520
521 ERR_raise(ERR_LIB_CMP, CMP_R_NO_SUITABLE_SENDER_CERT);
522 if (sname != NULL) {
523 ERR_add_error_txt(NULL, "for msg sender name = ");
524 ERR_add_error_txt(NULL, sname);
525 }
526 if (skid_str != NULL) {
527 ERR_add_error_txt(" and ", "for msg senderKID = ");
528 ERR_add_error_txt(NULL, skid_str);
529 }
530
531 end:
532 OPENSSL_free(sname);
533 OPENSSL_free(skid_str);
534 return res;
535 }
536
537 /*-
538 * Validate the protection of the given PKIMessage using either password-
539 * based mac (PBM) or a signature algorithm. In the case of signature algorithm,
540 * the sender certificate can have been pinned by providing it in ctx->srvCert,
541 * else it is searched in msg->extraCerts, ctx->untrusted, in ctx->trusted
542 * (in this order) and is path is validated against ctx->trusted.
543 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
544 *
545 * If ctx->permitTAInExtraCertsForIR is true and when validating a CMP IP msg,
546 * the trust anchor for validating the IP msg may be taken from msg->extraCerts
547 * if a self-issued certificate is found there that can be used to
548 * validate the enrolled certificate returned in the IP.
549 * This is according to the need given in 3GPP TS 33.310.
550 *
551 * Returns 1 on success, 0 on error or validation failed.
552 */
553 int OSSL_CMP_validate_msg(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
554 {
555 X509 *scrt;
556
557 ossl_cmp_debug(ctx, "validating CMP message");
558 if (ctx == NULL || msg == NULL
559 || msg->header == NULL || msg->body == NULL) {
560 ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
561 return 0;
562 }
563
564 if (msg->header->protectionAlg == NULL /* unprotected message */
565 || msg->protection == NULL || msg->protection->data == NULL) {
566 ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
567 return 0;
568 }
569
570 switch (ossl_cmp_hdr_get_protection_nid(msg->header)) {
571 /* 5.1.3.1. Shared Secret Information */
572 case NID_id_PasswordBasedMAC:
573 if (ctx->secretValue == NULL) {
574 ossl_cmp_info(ctx, "no secret available for verifying PBM-based CMP message protection");
575 ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_SECRET);
576 return 0;
577 }
578 if (verify_PBMAC(ctx, msg)) {
579 /*
580 * RFC 9810, 5.3.2: 'Note that if the PKI message protection is
581 * "shared secret information", then any certificate transported in
582 * the caPubs field may be directly trusted as a root CA
583 * certificate by the initiator.'
584 */
585 switch (OSSL_CMP_MSG_get_bodytype(msg)) {
586 case -1:
587 return 0;
588 case OSSL_CMP_PKIBODY_IP:
589 case OSSL_CMP_PKIBODY_CP:
590 case OSSL_CMP_PKIBODY_KUP:
591 case OSSL_CMP_PKIBODY_CCP:
592 if (ctx->trusted != NULL) {
593 STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
594 /* value.ip is same for cp, kup, and ccp */
595
596 if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
597 /* adds both self-issued and not self-issued certs */
598 return 0;
599 }
600 break;
601 default:
602 break;
603 }
604 ossl_cmp_debug(ctx,
605 "successfully validated PBM-based CMP message protection");
606 return 1;
607 }
608 ossl_cmp_warn(ctx, "verifying PBM-based CMP message protection failed");
609 break;
610
611 /*
612 * 5.1.3.2 DH Key Pairs
613 * Not yet supported
614 */
615 case NID_id_DHBasedMac:
616 ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC);
617 break;
618
619 /*
620 * 5.1.3.3. Signature
621 */
622 default:
623 scrt = ctx->srvCert;
624 if (scrt == NULL) {
625 if (ctx->trusted == NULL && ctx->secretValue != NULL) {
626 ossl_cmp_info(ctx, "no trust store nor pinned sender cert available for verifying signature-based CMP message protection");
627 ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_ANCHOR);
628 return 0;
629 }
630 if (check_msg_find_cert(ctx, msg)) {
631 ossl_cmp_log1(DEBUG, ctx,
632 "successfully validated signature-based CMP message protection using trust store%s",
633 ctx->permitTAInExtraCertsForIR ? " or 3GPP mode" : "");
634 return 1;
635 }
636 } else { /* use pinned sender cert */
637 /* use ctx->srvCert for signature check even if not acceptable */
638 if (verify_signature(ctx, msg, scrt)) {
639 ossl_cmp_debug(ctx,
640 "successfully validated signature-based CMP message protection using pinned sender cert");
641 return ossl_cmp_ctx_set1_validatedSrvCert(ctx, scrt);
642 }
643 ossl_cmp_warn(ctx, "CMP message signature verification failed");
644 ERR_raise(ERR_LIB_CMP, CMP_R_SRVCERT_DOES_NOT_VALIDATE_MSG);
645 }
646 break;
647 }
648 return 0;
649 }
650
651 static int check_transactionID_or_nonce(ASN1_OCTET_STRING *expected,
652 ASN1_OCTET_STRING *actual, int reason)
653 {
654 if (expected != NULL
655 && (actual == NULL || ASN1_OCTET_STRING_cmp(expected, actual) != 0)) {
656 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
657 char *expected_str, *actual_str;
658
659 expected_str = i2s_ASN1_OCTET_STRING(NULL, expected);
660 actual_str = actual == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, actual);
661 ERR_raise_data(ERR_LIB_CMP, reason,
662 "expected = %s, actual = %s",
663 expected_str == NULL ? "?" : expected_str,
664 actual == NULL ? "(none)" : actual_str == NULL ? "?"
665 : actual_str);
666 OPENSSL_free(expected_str);
667 OPENSSL_free(actual_str);
668 return 0;
669 #endif
670 }
671 return 1;
672 }
673
674 /*-
675 * Check received message (i.e., response by server or request from client)
676 * Any msg->extraCerts are prepended to ctx->untrusted.
677 *
678 * Ensures that:
679 * its sender is of appropriate type (currently only X509_NAME) and
680 * matches any expected sender or srvCert subject given in the ctx
681 * it has a valid body type
682 * its protection is valid (or invalid/absent, but only if a callback function
683 * is present and yields a positive result using also the supplied argument)
684 * its transaction ID matches the previous transaction ID stored in ctx (if any)
685 * its recipNonce matches the previous senderNonce stored in the ctx (if any)
686 *
687 * If everything is fine:
688 * learns the senderNonce from the received message,
689 * learns the transaction ID if it is not yet in ctx,
690 * and makes any certs in caPubs directly trusted.
691 *
692 * Returns 1 on success, 0 on error.
693 */
694 int ossl_cmp_msg_check_update(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
695 ossl_cmp_allow_unprotected_cb_t cb, int cb_arg)
696 {
697 OSSL_CMP_PKIHEADER *hdr;
698 const X509_NAME *expected_sender;
699 int num_untrusted, num_added, res;
700
701 if (!ossl_assert(ctx != NULL && msg != NULL && msg->header != NULL))
702 return 0;
703 hdr = OSSL_CMP_MSG_get0_header(msg);
704
705 /* If expected_sender is given, validate sender name of received msg */
706 expected_sender = ctx->expected_sender;
707 if (expected_sender == NULL && ctx->srvCert != NULL)
708 expected_sender = X509_get_subject_name(ctx->srvCert);
709 if (expected_sender != NULL) {
710 const X509_NAME *actual_sender;
711 char *str;
712
713 if (hdr->sender->type != GEN_DIRNAME) {
714 ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
715 return 0;
716 }
717 actual_sender = hdr->sender->d.directoryName;
718 /*
719 * Compare actual sender name of response with expected sender name.
720 * Mitigates risk of accepting misused PBM secret or
721 * misused certificate of an unauthorized entity of a trusted hierarchy.
722 */
723 if (!check_name(ctx, 0, "sender DN field", actual_sender,
724 "expected sender", expected_sender)) {
725 str = X509_NAME_oneline(actual_sender, NULL, 0);
726 ERR_raise_data(ERR_LIB_CMP, CMP_R_UNEXPECTED_SENDER,
727 str != NULL ? str : "<unknown>");
728 OPENSSL_free(str);
729 return 0;
730 }
731 }
732 /* Note: if recipient was NULL-DN it could be learned here if needed */
733
734 num_added = sk_X509_num(msg->extraCerts);
735 if (num_added > 10)
736 ossl_cmp_log1(WARN, ctx, "received CMP message contains %d extraCerts",
737 num_added);
738 /*
739 * Store any provided extraCerts in ctx for use in OSSL_CMP_validate_msg()
740 * and for future use, such that they are available to ctx->certConf_cb and
741 * the peer does not need to send them again in the same transaction.
742 * Note that it does not help validating the message before storing the
743 * extraCerts because they do not belong to the protected msg part anyway.
744 * The extraCerts are prepended. Allows simple removal if they shall not be
745 * cached. Also they get used first, which is likely good for efficiency.
746 */
747 num_untrusted = ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted);
748 res = ossl_x509_add_certs_new(&ctx->untrusted, msg->extraCerts,
749 /* this allows self-signed certs */
750 X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
751 | X509_ADD_FLAG_PREPEND);
752 num_added = (ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted))
753 - num_untrusted;
754 if (!res) {
755 while (num_added-- > 0)
756 X509_free(sk_X509_shift(ctx->untrusted));
757 return 0;
758 }
759
760 if (hdr->protectionAlg != NULL)
761 res = OSSL_CMP_validate_msg(ctx, msg)
762 /* explicitly permitted exceptions for invalid protection: */
763 || (cb != NULL && (*cb)(ctx, msg, 1, cb_arg) > 0);
764 else
765 /* explicitly permitted exceptions for missing protection: */
766 res = cb != NULL && (*cb)(ctx, msg, 0, cb_arg) > 0;
767 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
768 res = 1; /* support more aggressive fuzzing by letting invalid msg pass */
769 #endif
770
771 /* remove extraCerts again if not caching */
772 if (ctx->noCacheExtraCerts)
773 while (num_added-- > 0)
774 X509_free(sk_X509_shift(ctx->untrusted));
775
776 if (!res) {
777 if (hdr->protectionAlg != NULL)
778 ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_PROTECTION);
779 else
780 ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
781 return 0;
782 }
783
784 /* check CMP version number in header */
785 if (ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_2
786 && ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_3) {
787 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
788 ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PVNO);
789 return 0;
790 #endif
791 }
792
793 if (OSSL_CMP_MSG_get_bodytype(msg) < 0) {
794 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
795 ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
796 return 0;
797 #endif
798 }
799
800 /* compare received transactionID with the expected one in previous msg */
801 if (!check_transactionID_or_nonce(ctx->transactionID, hdr->transactionID,
802 CMP_R_TRANSACTIONID_UNMATCHED))
803 return 0;
804
805 /*
806 * enable clearing irrelevant errors
807 * in attempts to validate recipient nonce in case of delayed delivery.
808 */
809 (void)ERR_set_mark();
810 /* compare received nonce with the one we sent */
811 if (!check_transactionID_or_nonce(ctx->senderNonce, hdr->recipNonce,
812 CMP_R_RECIPNONCE_UNMATCHED)) {
813 /* check if we are polling and received final response */
814 if (ctx->first_senderNonce == NULL
815 || OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_POLLREP
816 /* compare received nonce with our sender nonce at poll start */
817 || !check_transactionID_or_nonce(ctx->first_senderNonce,
818 hdr->recipNonce,
819 CMP_R_RECIPNONCE_UNMATCHED)) {
820 (void)ERR_clear_last_mark();
821 return 0;
822 }
823 }
824 (void)ERR_pop_to_mark();
825
826 /* if not yet present, learn transactionID */
827 if (ctx->transactionID == NULL
828 && !OSSL_CMP_CTX_set1_transactionID(ctx, hdr->transactionID))
829 return 0;
830
831 /*
832 * RFC 9810 section 5.1.1 states: the recipNonce is copied from
833 * the senderNonce of the previous message in the transaction.
834 * --> Store for setting in next message
835 */
836 if (!ossl_cmp_ctx_set1_recipNonce(ctx, hdr->senderNonce))
837 return 0;
838
839 if (ossl_cmp_hdr_get_protection_nid(hdr) == NID_id_PasswordBasedMAC) {
840 /*
841 * RFC 9810, 5.3.2: 'Note that if the PKI message protection is
842 * "shared secret information", then any certificate transported in
843 * the caPubs field may be directly trusted as a root CA
844 * certificate by the initiator.'
845 */
846 switch (OSSL_CMP_MSG_get_bodytype(msg)) {
847 case OSSL_CMP_PKIBODY_IP:
848 case OSSL_CMP_PKIBODY_CP:
849 case OSSL_CMP_PKIBODY_KUP:
850 case OSSL_CMP_PKIBODY_CCP:
851 if (ctx->trusted != NULL) {
852 STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
853 /* value.ip is same for cp, kup, and ccp */
854
855 if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
856 /* adds both self-issued and not self-issued certs */
857 return 0;
858 }
859 break;
860 default:
861 break;
862 }
863 }
864 return 1;
865 }
866
867 int ossl_cmp_verify_popo(const OSSL_CMP_CTX *ctx,
868 const OSSL_CMP_MSG *msg, int acceptRAVerified)
869 {
870 if (!ossl_assert(msg != NULL && msg->body != NULL))
871 return 0;
872 switch (msg->body->type) {
873 case OSSL_CMP_PKIBODY_P10CR: {
874 X509_REQ *req = msg->body->value.p10cr;
875
876 if (X509_REQ_verify_ex(req, X509_REQ_get0_pubkey(req), ctx->libctx,
877 ctx->propq)
878 <= 0) {
879 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
880 ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_NOT_ACCEPTED);
881 return 0;
882 #endif
883 }
884 } break;
885 case OSSL_CMP_PKIBODY_IR:
886 case OSSL_CMP_PKIBODY_CR:
887 case OSSL_CMP_PKIBODY_KUR:
888 if (!OSSL_CRMF_MSGS_verify_popo(msg->body->value.ir, OSSL_CMP_CERTREQID,
889 acceptRAVerified,
890 ctx->libctx, ctx->propq)) {
891 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
892 return 0;
893 #endif
894 }
895 break;
896 default:
897 ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
898 return 0;
899 }
900 return 1;
901 }