xref: /freebsd/crypto/openssl/crypto/cmp/cmp_vfy.c (revision 10a428653ee7216475f1ddce3fb4cbf1200319f8)
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 #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 
366 /* checks protection of msg but not cert revocation nor cert chain */
check_msg_given_cert(const OSSL_CMP_CTX * ctx,X509 * cert,const OSSL_CMP_MSG * msg)367 static int check_msg_given_cert(const OSSL_CMP_CTX *ctx, X509 *cert,
368     const OSSL_CMP_MSG *msg)
369 {
370     return cert_acceptable(ctx, "previously validated", "sender cert",
371         cert, NULL, NULL, msg);
372 }
373 
374 /*-
375  * Try all certs in given list for verifying msg, normally or in 3GPP mode.
376  * If already_checked1 == NULL then certs are assumed to be the msg->extraCerts.
377  * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
378  */
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)379 static int check_msg_with_certs(OSSL_CMP_CTX *ctx, const STACK_OF(X509) *certs,
380     const char *desc,
381     const STACK_OF(X509) *already_checked1,
382     const STACK_OF(X509) *already_checked2,
383     const OSSL_CMP_MSG *msg, int mode_3gpp)
384 {
385     int in_extraCerts = already_checked1 == NULL;
386     int n_acceptable_certs = 0;
387     int i;
388 
389     if (sk_X509_num(certs) <= 0) {
390         ossl_cmp_log1(WARN, ctx, "no %s", desc);
391         return 0;
392     }
393 
394     for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */
395         X509 *cert = sk_X509_value(certs, i);
396 
397         if (!ossl_assert(cert != NULL))
398             return 0;
399         if (!cert_acceptable(ctx, "cert from", desc, cert,
400                 already_checked1, already_checked2, msg))
401             continue;
402         n_acceptable_certs++;
403         if (mode_3gpp ? check_cert_path_3gpp(ctx, msg, cert)
404                       : check_cert_path(ctx, ctx->trusted, cert)) {
405             /* store successful sender cert for further msgs in transaction */
406             return ossl_cmp_ctx_set1_validatedSrvCert(ctx, cert);
407         }
408     }
409     if (in_extraCerts && n_acceptable_certs == 0)
410         ossl_cmp_warn(ctx, "no acceptable cert in extraCerts");
411     return 0;
412 }
413 
414 /*-
415  * Verify msg trying first ctx->untrusted, which should include extraCerts
416  * at its front, then trying the trusted certs in truststore (if any) of ctx.
417  * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
418  */
check_msg_all_certs(OSSL_CMP_CTX * ctx,const OSSL_CMP_MSG * msg,int mode_3gpp)419 static int check_msg_all_certs(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
420     int mode_3gpp)
421 {
422     int ret = 0;
423 
424     if (ctx->permitTAInExtraCertsForIR
425         && OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_IP)
426         ossl_cmp_info(ctx, mode_3gpp ? "normal mode failed; trying now 3GPP mode trusting extraCerts" : "trying first normal mode using trust store");
427     else if (mode_3gpp)
428         return 0;
429 
430     if (check_msg_with_certs(ctx, msg->extraCerts, "extraCerts",
431             NULL, NULL, msg, mode_3gpp))
432         return 1;
433     if (check_msg_with_certs(ctx, ctx->untrusted, "untrusted certs",
434             msg->extraCerts, NULL, msg, mode_3gpp))
435         return 1;
436 
437     if (ctx->trusted == NULL) {
438         ossl_cmp_warn(ctx, mode_3gpp ? "no self-issued extraCerts" : "no trusted store");
439     } else {
440         STACK_OF(X509) *trusted = X509_STORE_get1_all_certs(ctx->trusted);
441 
442         ret = check_msg_with_certs(ctx, trusted,
443             mode_3gpp ? "self-issued extraCerts"
444                       : "certs in trusted store",
445             msg->extraCerts, ctx->untrusted,
446             msg, mode_3gpp);
447         OSSL_STACK_OF_X509_free(trusted);
448     }
449     return ret;
450 }
451 
452 /*-
453  * Verify message signature with any acceptable and valid candidate cert.
454  * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
455  */
check_msg_find_cert(OSSL_CMP_CTX * ctx,const OSSL_CMP_MSG * msg)456 static int check_msg_find_cert(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
457 {
458     X509 *scrt = ctx->validatedSrvCert; /* previous successful sender cert */
459     GENERAL_NAME *sender = msg->header->sender;
460     char *sname = NULL;
461     char *skid_str = NULL;
462     const ASN1_OCTET_STRING *skid = msg->header->senderKID;
463     OSSL_CMP_log_cb_t backup_log_cb = ctx->log_cb;
464     int res = 0;
465 
466     if (sender == NULL || msg->body == NULL)
467         return 0; /* other NULL cases already have been checked */
468     if (sender->type != GEN_DIRNAME) {
469         /* So far, only X509_NAME is supported */
470         ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
471         return 0;
472     }
473 
474     /* dump any hitherto errors to avoid confusion when printing further ones */
475     OSSL_CMP_CTX_print_errors(ctx);
476 
477     /* enable clearing irrelevant errors in attempts to validate sender certs */
478     (void)ERR_set_mark();
479     ctx->log_cb = NULL; /* temporarily disable logging */
480 
481     if (scrt != NULL) {
482         /*-
483          * try first using cached message sender cert (in 'scrt' variable),
484          * which was used successfully earlier in the same transaction
485          * (assuming that the certificate itself was not revoked meanwhile and
486          *  is a good guess for use in validating also the current message)
487          */
488         if (check_msg_given_cert(ctx, scrt, msg)) {
489             ctx->log_cb = backup_log_cb;
490             (void)ERR_pop_to_mark();
491             return 1;
492         }
493         /* cached sender cert has shown to be no more successfully usable */
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         ctx->log_cb = backup_log_cb;
498         (void)check_msg_given_cert(ctx, scrt, msg);
499         ctx->log_cb = NULL;
500         (void)ossl_cmp_ctx_set1_validatedSrvCert(ctx, NULL); /* this invalidates scrt */
501     }
502 
503     res = check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */)
504         || check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
505     ctx->log_cb = backup_log_cb;
506     if (res) {
507         /* discard any diagnostic information on trying to use certs */
508         (void)ERR_pop_to_mark();
509         goto end;
510     }
511     /* failed finding a sender cert that verifies the message signature */
512     (void)ERR_clear_last_mark();
513 
514     sname = X509_NAME_oneline(sender->d.directoryName, NULL, 0);
515     skid_str = skid == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, skid);
516     if (ctx->log_cb != NULL) {
517         ossl_cmp_info(ctx, "trying to verify msg signature with a valid cert that..");
518         if (sname != NULL)
519             ossl_cmp_log1(INFO, ctx, "matches msg sender    = %s", sname);
520         if (skid_str != NULL)
521             ossl_cmp_log1(INFO, ctx, "matches msg senderKID = %s", skid_str);
522         else
523             ossl_cmp_info(ctx, "while msg header does not contain senderKID");
524         /* re-do the above checks (just) for adding diagnostic information */
525         (void)check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */);
526         (void)check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
527     }
528 
529     ERR_raise(ERR_LIB_CMP, CMP_R_NO_SUITABLE_SENDER_CERT);
530     if (sname != NULL) {
531         ERR_add_error_txt(NULL, "for msg sender name = ");
532         ERR_add_error_txt(NULL, sname);
533     }
534     if (skid_str != NULL) {
535         ERR_add_error_txt(" and ", "for msg senderKID = ");
536         ERR_add_error_txt(NULL, skid_str);
537     }
538 
539 end:
540     OPENSSL_free(sname);
541     OPENSSL_free(skid_str);
542     return res;
543 }
544 
545 /*-
546  * Validate the protection of the given PKIMessage using either password-
547  * based mac (PBM) or a signature algorithm. In the case of signature algorithm,
548  * the sender certificate can have been pinned by providing it in ctx->srvCert,
549  * else it is searched in msg->extraCerts, ctx->untrusted, in ctx->trusted
550  * (in this order) and is path is validated against ctx->trusted.
551  * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
552  *
553  * If ctx->permitTAInExtraCertsForIR is true and when validating a CMP IP msg,
554  * the trust anchor for validating the IP msg may be taken from msg->extraCerts
555  * if a self-issued certificate is found there that can be used to
556  * validate the enrolled certificate returned in the IP.
557  * This is according to the need given in 3GPP TS 33.310.
558  *
559  * Returns 1 on success, 0 on error or validation failed.
560  */
OSSL_CMP_validate_msg(OSSL_CMP_CTX * ctx,const OSSL_CMP_MSG * msg)561 int OSSL_CMP_validate_msg(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
562 {
563     X509 *scrt;
564 
565     ossl_cmp_debug(ctx, "validating CMP message");
566     if (ctx == NULL || msg == NULL
567         || msg->header == NULL || msg->body == NULL) {
568         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
569         return 0;
570     }
571 
572     if (msg->header->protectionAlg == NULL /* unprotected message */
573         || msg->protection == NULL || msg->protection->data == NULL) {
574         ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
575         return 0;
576     }
577 
578     switch (ossl_cmp_hdr_get_protection_nid(msg->header)) {
579         /* 5.1.3.1.  Shared Secret Information */
580     case NID_id_PasswordBasedMAC:
581         if (ctx->secretValue == NULL) {
582             ossl_cmp_info(ctx, "no secret available for verifying PBM-based CMP message protection");
583             ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_SECRET);
584             return 0;
585         }
586         if (verify_PBMAC(ctx, msg)) {
587             /*
588              * RFC 9810, 5.3.2: 'Note that if the PKI message protection is
589              * "shared secret information", then any certificate transported in
590              * the caPubs field may be directly trusted as a root CA
591              * certificate by the initiator.'
592              */
593             switch (OSSL_CMP_MSG_get_bodytype(msg)) {
594             case -1:
595                 return 0;
596             case OSSL_CMP_PKIBODY_IP:
597             case OSSL_CMP_PKIBODY_CP:
598             case OSSL_CMP_PKIBODY_KUP:
599             case OSSL_CMP_PKIBODY_CCP:
600                 if (ctx->trusted != NULL) {
601                     STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
602                     /* value.ip is same for cp, kup, and ccp */
603 
604                     if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
605                         /* adds both self-issued and not self-issued certs */
606                         return 0;
607                 }
608                 break;
609             default:
610                 break;
611             }
612             ossl_cmp_debug(ctx,
613                 "successfully validated PBM-based CMP message protection");
614             return 1;
615         }
616         ossl_cmp_warn(ctx, "verifying PBM-based CMP message protection failed");
617         break;
618 
619         /*
620          * 5.1.3.2 DH Key Pairs
621          * Not yet supported
622          */
623     case NID_id_DHBasedMac:
624         ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC);
625         break;
626 
627         /*
628          * 5.1.3.3.  Signature
629          */
630     default:
631         scrt = ctx->srvCert;
632         if (scrt == NULL) {
633             if (ctx->trusted == NULL && ctx->secretValue != NULL) {
634                 ossl_cmp_info(ctx, "no trust store nor pinned sender cert available for verifying signature-based CMP message protection");
635                 ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_ANCHOR);
636                 return 0;
637             }
638             if (check_msg_find_cert(ctx, msg)) {
639                 ossl_cmp_log1(DEBUG, ctx,
640                     "successfully validated signature-based CMP message protection using trust store%s",
641                     ctx->permitTAInExtraCertsForIR ? " or 3GPP mode" : "");
642                 return 1;
643             }
644         } else { /* use pinned sender cert */
645             /* use ctx->srvCert for signature check even if not acceptable */
646             if (verify_signature(ctx, msg, scrt)) {
647                 ossl_cmp_debug(ctx,
648                     "successfully validated signature-based CMP message protection using pinned sender cert");
649                 return ossl_cmp_ctx_set1_validatedSrvCert(ctx, scrt);
650             }
651             ossl_cmp_warn(ctx, "CMP message signature verification failed");
652             ERR_raise(ERR_LIB_CMP, CMP_R_SRVCERT_DOES_NOT_VALIDATE_MSG);
653         }
654         break;
655     }
656     return 0;
657 }
658 
check_transactionID_or_nonce(ASN1_OCTET_STRING * expected,ASN1_OCTET_STRING * actual,int reason)659 static int check_transactionID_or_nonce(ASN1_OCTET_STRING *expected,
660     ASN1_OCTET_STRING *actual, int reason)
661 {
662     if (expected != NULL
663         && (actual == NULL || ASN1_OCTET_STRING_cmp(expected, actual) != 0)) {
664 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
665         char *expected_str, *actual_str;
666 
667         expected_str = i2s_ASN1_OCTET_STRING(NULL, expected);
668         actual_str = actual == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, actual);
669         ERR_raise_data(ERR_LIB_CMP, reason,
670             "expected = %s, actual = %s",
671             expected_str == NULL ? "?" : expected_str,
672             actual == NULL ? "(none)" : actual_str == NULL ? "?"
673                                                            : actual_str);
674         OPENSSL_free(expected_str);
675         OPENSSL_free(actual_str);
676         return 0;
677 #endif
678     }
679     return 1;
680 }
681 
682 /*-
683  * Check received message (i.e., response by server or request from client)
684  * Any msg->extraCerts are prepended to ctx->untrusted.
685  *
686  * Ensures that:
687  * its sender is of appropriate type (currently only X509_NAME) and
688  *     matches any expected sender or srvCert subject given in the ctx
689  * it has a valid body type
690  * its protection is valid (or invalid/absent, but only if a callback function
691  *     is present and yields a positive result using also the supplied argument)
692  * its transaction ID matches the previous transaction ID stored in ctx (if any)
693  * its recipNonce matches the previous senderNonce stored in the ctx (if any)
694  *
695  * If everything is fine:
696  * learns the senderNonce from the received message,
697  * learns the transaction ID if it is not yet in ctx,
698  * and makes any certs in caPubs directly trusted.
699  *
700  * Returns 1 on success, 0 on error.
701  */
ossl_cmp_msg_check_update(OSSL_CMP_CTX * ctx,const OSSL_CMP_MSG * msg,ossl_cmp_allow_unprotected_cb_t cb,int cb_arg)702 int ossl_cmp_msg_check_update(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
703     ossl_cmp_allow_unprotected_cb_t cb, int cb_arg)
704 {
705     OSSL_CMP_PKIHEADER *hdr;
706     const X509_NAME *expected_sender;
707     int num_untrusted, num_added, res;
708 
709     if (!ossl_assert(ctx != NULL && msg != NULL && msg->header != NULL))
710         return 0;
711     hdr = OSSL_CMP_MSG_get0_header(msg);
712 
713     /* If expected_sender is given, validate sender name of received msg */
714     expected_sender = ctx->expected_sender;
715     if (expected_sender == NULL && ctx->srvCert != NULL)
716         expected_sender = X509_get_subject_name(ctx->srvCert);
717     if (expected_sender != NULL) {
718         const X509_NAME *actual_sender;
719         char *str;
720 
721         if (hdr->sender->type != GEN_DIRNAME) {
722             ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
723             return 0;
724         }
725         actual_sender = hdr->sender->d.directoryName;
726         /*
727          * Compare actual sender name of response with expected sender name.
728          * Mitigates risk of accepting misused PBM secret or
729          * misused certificate of an unauthorized entity of a trusted hierarchy.
730          */
731         if (!check_name(ctx, 0, "sender DN field", actual_sender,
732                 "expected sender", expected_sender)) {
733             str = X509_NAME_oneline(actual_sender, NULL, 0);
734             ERR_raise_data(ERR_LIB_CMP, CMP_R_UNEXPECTED_SENDER,
735                 str != NULL ? str : "<unknown>");
736             OPENSSL_free(str);
737             return 0;
738         }
739     }
740     /* Note: if recipient was NULL-DN it could be learned here if needed */
741 
742     num_added = sk_X509_num(msg->extraCerts);
743     if (num_added > 10)
744         ossl_cmp_log1(WARN, ctx, "received CMP message contains %d extraCerts",
745             num_added);
746     /*
747      * Store any provided extraCerts in ctx for use in OSSL_CMP_validate_msg()
748      * and for future use, such that they are available to ctx->certConf_cb and
749      * the peer does not need to send them again in the same transaction.
750      * Note that it does not help validating the message before storing the
751      * extraCerts because they do not belong to the protected msg part anyway.
752      * The extraCerts are prepended. Allows simple removal if they shall not be
753      * cached. Also they get used first, which is likely good for efficiency.
754      */
755     num_untrusted = ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted);
756     res = ossl_x509_add_certs_new(&ctx->untrusted, msg->extraCerts,
757         /* this allows self-signed certs */
758         X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
759             | X509_ADD_FLAG_PREPEND);
760     num_added = (ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted))
761         - num_untrusted;
762     if (!res) {
763         while (num_added-- > 0)
764             X509_free(sk_X509_shift(ctx->untrusted));
765         return 0;
766     }
767 
768     if (hdr->protectionAlg != NULL)
769         res = OSSL_CMP_validate_msg(ctx, msg)
770             /* explicitly permitted exceptions for invalid protection: */
771             || (cb != NULL && (*cb)(ctx, msg, 1, cb_arg) > 0);
772     else
773         /* explicitly permitted exceptions for missing protection: */
774         res = cb != NULL && (*cb)(ctx, msg, 0, cb_arg) > 0;
775 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
776     res = 1; /* support more aggressive fuzzing by letting invalid msg pass */
777 #endif
778 
779     /* remove extraCerts again if not caching */
780     if (ctx->noCacheExtraCerts)
781         while (num_added-- > 0)
782             X509_free(sk_X509_shift(ctx->untrusted));
783 
784     if (!res) {
785         if (hdr->protectionAlg != NULL)
786             ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_PROTECTION);
787         else
788             ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
789         return 0;
790     }
791 
792     /* check CMP version number in header */
793     if (ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_2
794         && ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_3) {
795 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
796         ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PVNO);
797         return 0;
798 #endif
799     }
800 
801     if (OSSL_CMP_MSG_get_bodytype(msg) < 0) {
802 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
803         ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
804         return 0;
805 #endif
806     }
807 
808     /* compare received transactionID with the expected one in previous msg */
809     if (!check_transactionID_or_nonce(ctx->transactionID, hdr->transactionID,
810             CMP_R_TRANSACTIONID_UNMATCHED))
811         return 0;
812 
813     /*
814      * enable clearing irrelevant errors
815      * in attempts to validate recipient nonce in case of delayed delivery.
816      */
817     (void)ERR_set_mark();
818     /* compare received nonce with the one we sent */
819     if (!check_transactionID_or_nonce(ctx->senderNonce, hdr->recipNonce,
820             CMP_R_RECIPNONCE_UNMATCHED)) {
821         /* check if we are polling and received final response */
822         if (ctx->first_senderNonce == NULL
823             || OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_POLLREP
824             /* compare received nonce with our sender nonce at poll start */
825             || !check_transactionID_or_nonce(ctx->first_senderNonce,
826                 hdr->recipNonce,
827                 CMP_R_RECIPNONCE_UNMATCHED)) {
828             (void)ERR_clear_last_mark();
829             return 0;
830         }
831     }
832     (void)ERR_pop_to_mark();
833 
834     /* if not yet present, learn transactionID */
835     if (ctx->transactionID == NULL
836         && !OSSL_CMP_CTX_set1_transactionID(ctx, hdr->transactionID))
837         return 0;
838 
839     /*
840      * RFC 9810 section 5.1.1 states: the recipNonce is copied from
841      * the senderNonce of the previous message in the transaction.
842      * --> Store for setting in next message
843      */
844     if (!ossl_cmp_ctx_set1_recipNonce(ctx, hdr->senderNonce))
845         return 0;
846 
847     if (ossl_cmp_hdr_get_protection_nid(hdr) == NID_id_PasswordBasedMAC) {
848         /*
849          * RFC 9810, 5.3.2: 'Note that if the PKI message protection is
850          * "shared secret information", then any certificate transported in
851          * the caPubs field may be directly trusted as a root CA
852          * certificate by the initiator.'
853          */
854         switch (OSSL_CMP_MSG_get_bodytype(msg)) {
855         case OSSL_CMP_PKIBODY_IP:
856         case OSSL_CMP_PKIBODY_CP:
857         case OSSL_CMP_PKIBODY_KUP:
858         case OSSL_CMP_PKIBODY_CCP:
859             if (ctx->trusted != NULL) {
860                 STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
861                 /* value.ip is same for cp, kup, and ccp */
862 
863                 if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
864                     /* adds both self-issued and not self-issued certs */
865                     return 0;
866             }
867             break;
868         default:
869             break;
870         }
871     }
872     return 1;
873 }
874 
ossl_cmp_verify_popo(const OSSL_CMP_CTX * ctx,const OSSL_CMP_MSG * msg,int acceptRAVerified)875 int ossl_cmp_verify_popo(const OSSL_CMP_CTX *ctx,
876     const OSSL_CMP_MSG *msg, int acceptRAVerified)
877 {
878     if (!ossl_assert(msg != NULL && msg->body != NULL))
879         return 0;
880     switch (msg->body->type) {
881     case OSSL_CMP_PKIBODY_P10CR: {
882         X509_REQ *req = msg->body->value.p10cr;
883 
884         if (X509_REQ_verify_ex(req, X509_REQ_get0_pubkey(req), ctx->libctx,
885                 ctx->propq)
886             <= 0) {
887 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
888             ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_NOT_ACCEPTED);
889             return 0;
890 #endif
891         }
892     } break;
893     case OSSL_CMP_PKIBODY_IR:
894     case OSSL_CMP_PKIBODY_CR:
895     case OSSL_CMP_PKIBODY_KUR:
896         if (!OSSL_CRMF_MSGS_verify_popo(msg->body->value.ir, OSSL_CMP_CERTREQID,
897                 acceptRAVerified,
898                 ctx->libctx, ctx->propq)) {
899 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
900             return 0;
901 #endif
902         }
903         break;
904     default:
905         ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
906         return 0;
907     }
908     return 1;
909 }
910