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