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