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