Clean up CMP chain building for CMP signer, TLS client, and newly enrolled certs
[openssl.git] / crypto / cmp / cmp_protect.c
1 /*
2  * Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright Nokia 2007-2019
4  * Copyright Siemens AG 2015-2019
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 #include "cmp_local.h"
13
14 /* explicit #includes not strictly needed since implied by the above: */
15 #include <openssl/asn1t.h>
16 #include <openssl/cmp.h>
17 #include <openssl/crmf.h>
18 #include <openssl/err.h>
19 #include <openssl/x509.h>
20
21 DEFINE_STACK_OF(X509)
22
23 /*
24  * This function is also used by the internal verify_PBMAC() in cmp_vfy.c.
25  *
26  * Calculate protection for given PKImessage according to
27  * the algorithm and parameters in the message header's protectionAlg
28  * using the credentials, library context, and property criteria in the ctx.
29  *
30  * returns ASN1_BIT_STRING representing the protection on success, else NULL
31  */
32 ASN1_BIT_STRING *ossl_cmp_calc_protection(const OSSL_CMP_CTX *ctx,
33                                           const OSSL_CMP_MSG *msg)
34 {
35     ASN1_BIT_STRING *prot = NULL;
36     OSSL_CMP_PROTECTEDPART prot_part;
37     const ASN1_OBJECT *algorOID = NULL;
38     const void *ppval = NULL;
39     int pptype = 0;
40
41     if (!ossl_assert(ctx != NULL && msg != NULL))
42         return NULL;
43
44     /* construct data to be signed */
45     prot_part.header = msg->header;
46     prot_part.body = msg->body;
47
48     if (msg->header->protectionAlg == NULL) {
49         CMPerr(0, CMP_R_UNKNOWN_ALGORITHM_ID);
50         return NULL;
51     }
52     X509_ALGOR_get0(&algorOID, &pptype, &ppval, msg->header->protectionAlg);
53
54     if (OBJ_obj2nid(algorOID) == NID_id_PasswordBasedMAC) {
55         int len;
56         size_t prot_part_der_len;
57         unsigned char *prot_part_der = NULL;
58         size_t sig_len;
59         unsigned char *protection = NULL;
60         OSSL_CRMF_PBMPARAMETER *pbm = NULL;
61         ASN1_STRING *pbm_str = NULL;
62         const unsigned char *pbm_str_uc = NULL;
63
64         if (ctx->secretValue == NULL) {
65             CMPerr(0, CMP_R_MISSING_PBM_SECRET);
66             return NULL;
67         }
68         if (ppval == NULL) {
69             CMPerr(0, CMP_R_ERROR_CALCULATING_PROTECTION);
70             return NULL;
71         }
72
73         len = i2d_OSSL_CMP_PROTECTEDPART(&prot_part, &prot_part_der);
74         if (len < 0 || prot_part_der == NULL) {
75             CMPerr(0, CMP_R_ERROR_CALCULATING_PROTECTION);
76             goto end;
77         }
78         prot_part_der_len = (size_t)len;
79
80         pbm_str = (ASN1_STRING *)ppval;
81         pbm_str_uc = pbm_str->data;
82         pbm = d2i_OSSL_CRMF_PBMPARAMETER(NULL, &pbm_str_uc, pbm_str->length);
83         if (pbm == NULL) {
84             CMPerr(0, CMP_R_WRONG_ALGORITHM_OID);
85             goto end;
86         }
87
88         if (!OSSL_CRMF_pbm_new(ctx->libctx, ctx->propq,
89                                pbm, prot_part_der, prot_part_der_len,
90                                ctx->secretValue->data, ctx->secretValue->length,
91                                &protection, &sig_len))
92             goto end;
93
94         if ((prot = ASN1_BIT_STRING_new()) == NULL)
95             return NULL;
96         /* OpenSSL defaults all bit strings to be encoded as ASN.1 NamedBitList */
97         prot->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
98         prot->flags |= ASN1_STRING_FLAG_BITS_LEFT;
99         if (!ASN1_BIT_STRING_set(prot, protection, sig_len)) {
100             ASN1_BIT_STRING_free(prot);
101             prot = NULL;
102         }
103     end:
104         OSSL_CRMF_PBMPARAMETER_free(pbm);
105         OPENSSL_free(protection);
106         OPENSSL_free(prot_part_der);
107         return prot;
108     } else {
109         int md_nid;
110         const EVP_MD *md = NULL;
111
112         if (ctx->pkey == NULL) {
113             CMPerr(0, CMP_R_MISSING_KEY_INPUT_FOR_CREATING_PROTECTION);
114             return NULL;
115         }
116         if (!OBJ_find_sigid_algs(OBJ_obj2nid(algorOID), &md_nid, NULL)
117                 || (md = EVP_get_digestbynid(md_nid)) == NULL) {
118             CMPerr(0, CMP_R_UNKNOWN_ALGORITHM_ID);
119             return NULL;
120         }
121
122         if ((prot = ASN1_BIT_STRING_new()) == NULL)
123             return NULL;
124         if (ASN1_item_sign_with_libctx(ASN1_ITEM_rptr(OSSL_CMP_PROTECTEDPART),
125                                        NULL, NULL, prot, &prot_part, NULL,
126                                        ctx->pkey, md, ctx->libctx, ctx->propq))
127             return prot;
128         ASN1_BIT_STRING_free(prot);
129         return NULL;
130     }
131 }
132
133 int ossl_cmp_msg_add_extraCerts(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg)
134 {
135     if (!ossl_assert(ctx != NULL && msg != NULL))
136         return 0;
137
138     if (msg->extraCerts == NULL
139             && (msg->extraCerts = sk_X509_new_null()) == NULL)
140         return 0;
141
142     /* Add first ctx->cert and its chain if using signature-based protection */
143     if (!ctx->unprotectedSend && ctx->secretValue == NULL) {
144         int flags_prepend = X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
145             | X509_ADD_FLAG_PREPEND | X509_ADD_FLAG_NO_SS;
146
147         /* if not yet done try to build chain using available untrusted certs */
148         if (ctx->chain == NULL) {
149             ossl_cmp_debug(ctx,
150                            "trying to build chain for own CMP signer cert");
151             ctx->chain =
152                 ossl_cmp_build_cert_chain(ctx->libctx, ctx->propq, NULL,
153                                           ctx->untrusted, ctx->cert);
154             if (ctx->chain != NULL) {
155                 ossl_cmp_debug(ctx,
156                                "success building chain for own CMP signer cert");
157             } else {
158                 /* dump errors to avoid confusion when printing further ones */
159                 OSSL_CMP_CTX_print_errors(ctx);
160                 ossl_cmp_warn(ctx,
161                               "could not build chain for own CMP signer cert");
162             }
163         }
164         if (ctx->chain != NULL) {
165             if (!X509_add_certs(msg->extraCerts, ctx->chain, flags_prepend))
166                 return 0;
167         } else {
168             /* make sure that at least our own signer cert is included first */
169             if (!X509_add_cert(msg->extraCerts, ctx->cert, flags_prepend))
170                 return 0;
171             ossl_cmp_debug(ctx,
172                            "fallback: adding just own CMP signer cert");
173         }
174     }
175
176     /* add any additional certificates from ctx->extraCertsOut */
177     if (!X509_add_certs(msg->extraCerts, ctx->extraCertsOut,
178                         X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
179         return 0;
180
181     /* if none was found avoid empty ASN.1 sequence */
182     if (sk_X509_num(msg->extraCerts) == 0) {
183         sk_X509_free(msg->extraCerts);
184         msg->extraCerts = NULL;
185     }
186     return 1;
187 }
188
189 /*
190  * Create an X509_ALGOR structure for PasswordBasedMAC protection based on
191  * the pbm settings in the context
192  */
193 static int set_pbmac_algor(const OSSL_CMP_CTX *ctx, X509_ALGOR **alg)
194 {
195     OSSL_CRMF_PBMPARAMETER *pbm = NULL;
196     unsigned char *pbm_der = NULL;
197     int pbm_der_len;
198     ASN1_STRING *pbm_str = NULL;
199
200     if (!ossl_assert(ctx != NULL))
201         return 0;
202
203     pbm = OSSL_CRMF_pbmp_new(ctx->libctx, ctx->pbm_slen,
204                              EVP_MD_type(ctx->pbm_owf), ctx->pbm_itercnt,
205                              ctx->pbm_mac);
206     pbm_str = ASN1_STRING_new();
207     if (pbm == NULL || pbm_str == NULL)
208         goto err;
209
210     if ((pbm_der_len = i2d_OSSL_CRMF_PBMPARAMETER(pbm, &pbm_der)) < 0)
211         goto err;
212
213     if (!ASN1_STRING_set(pbm_str, pbm_der, pbm_der_len))
214         goto err;
215     if (*alg == NULL && (*alg = X509_ALGOR_new()) == NULL)
216         goto err;
217     OPENSSL_free(pbm_der);
218
219     X509_ALGOR_set0(*alg, OBJ_nid2obj(NID_id_PasswordBasedMAC),
220                     V_ASN1_SEQUENCE, pbm_str);
221     OSSL_CRMF_PBMPARAMETER_free(pbm);
222     return 1;
223
224  err:
225     ASN1_STRING_free(pbm_str);
226     OPENSSL_free(pbm_der);
227     OSSL_CRMF_PBMPARAMETER_free(pbm);
228     return 0;
229 }
230
231 static int set_sig_algor(const OSSL_CMP_CTX *ctx, X509_ALGOR **alg)
232 {
233     int nid = 0;
234     ASN1_OBJECT *algo = NULL;
235
236     if (!OBJ_find_sigid_by_algs(&nid, EVP_MD_type(ctx->digest),
237                                 EVP_PKEY_id(ctx->pkey))) {
238         CMPerr(0, CMP_R_UNSUPPORTED_KEY_TYPE);
239         return 0;
240     }
241     if ((algo = OBJ_nid2obj(nid)) == NULL)
242         return 0;
243     if (*alg == NULL && (*alg = X509_ALGOR_new()) == NULL)
244         return 0;
245
246     if (X509_ALGOR_set0(*alg, algo, V_ASN1_UNDEF, NULL))
247         return 1;
248     ASN1_OBJECT_free(algo);
249     return 0;
250 }
251
252 static int set_senderKID(const OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg,
253                          const ASN1_OCTET_STRING *id)
254 {
255     if (id == NULL)
256         id = ctx->referenceValue; /* standard for PBM, fallback for sig-based */
257     return id == NULL || ossl_cmp_hdr_set1_senderKID(msg->header, id);
258 }
259
260 int ossl_cmp_msg_protect(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg)
261 {
262     if (!ossl_assert(ctx != NULL && msg != NULL))
263         return 0;
264
265     /*
266      * For the case of re-protection remove pre-existing protection.
267      * TODO: Consider also removing any pre-existing extraCerts.
268      */
269     X509_ALGOR_free(msg->header->protectionAlg);
270     msg->header->protectionAlg = NULL;
271     ASN1_BIT_STRING_free(msg->protection);
272     msg->protection = NULL;
273
274     if (ctx->unprotectedSend)
275         return 1;
276
277     /* use PasswordBasedMac according to 5.1.3.1 if secretValue is given */
278     if (ctx->secretValue != NULL) {
279         if (!set_pbmac_algor(ctx, &msg->header->protectionAlg))
280             goto err;
281         if (!set_senderKID(ctx, msg, NULL))
282             goto err;
283
284         /*
285          * will add any additional certificates from ctx->extraCertsOut
286          * while not needed to validate the protection certificate,
287          * the option to do this might be handy for certain use cases
288          */
289     } else if (ctx->cert != NULL && ctx->pkey != NULL) {
290         /* use MSG_SIG_ALG according to 5.1.3.3 if client cert and key given */
291
292         /* make sure that key and certificate match */
293         if (!X509_check_private_key(ctx->cert, ctx->pkey)) {
294             CMPerr(0, CMP_R_CERT_AND_KEY_DO_NOT_MATCH);
295             goto err;
296         }
297
298         if (!set_sig_algor(ctx, &msg->header->protectionAlg))
299             goto err;
300         /* set senderKID to keyIdentifier of the cert according to 5.1.1 */
301         if (!set_senderKID(ctx, msg, X509_get0_subject_key_id(ctx->cert)))
302             goto err;
303
304         /*
305          * will add ctx->cert followed, if possible, by its chain built
306          * from ctx->untrusted, and then ctx->extraCertsOut
307          */
308     } else {
309         CMPerr(0, CMP_R_MISSING_KEY_INPUT_FOR_CREATING_PROTECTION);
310         goto err;
311     }
312     if ((msg->protection = ossl_cmp_calc_protection(ctx, msg)) == NULL)
313         goto err;
314
315     /*
316      * If present, add ctx->cert followed by its chain as far as possible.
317      * Finally add any additional certificates from ctx->extraCertsOut;
318      * even if not needed to validate the protection
319      * the option to do this might be handy for certain use cases.
320      */
321     if (!ossl_cmp_msg_add_extraCerts(ctx, msg))
322         goto err;
323
324     /*
325      * As required by RFC 4210 section 5.1.1., if the sender name is not known
326      * to the client it set to NULL-DN. In this case for identification at least
327      * the senderKID must be set, where we took the referenceValue as fallback.
328      */
329     if (ossl_cmp_general_name_is_NULL_DN(msg->header->sender)
330             && msg->header->senderKID == NULL)
331         CMPerr(0, CMP_R_MISSING_SENDER_IDENTIFICATION);
332     else
333         return 1;
334
335  err:
336     CMPerr(0, CMP_R_ERROR_PROTECTING_MESSAGE);
337     return 0;
338 }