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