chunk 6 of CMP contribution to OpenSSL
[openssl.git] / crypto / cmp / cmp_protect.c
1 /*
2  * Copyright 2007-2019 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 for verification from cmp_vfy.
23  *
24  * Calculate protection for given PKImessage utilizing the given credentials
25  * and the algorithm parameters set inside the message header's protectionAlg.
26  *
27  * Either secret or pkey must be set, the other must be NULL. Attempts doing
28  * PBMAC in case 'secret' is set and signature if 'pkey' is set - but will only
29  * do the protection already marked in msg->header->protectionAlg.
30  *
31  * returns ptr to ASN1_BIT_STRING containing protection on success, else NULL
32  */
33 ASN1_BIT_STRING *ossl_cmp_calc_protection(const OSSL_CMP_MSG *msg,
34                                           const ASN1_OCTET_STRING *secret,
35                                           EVP_PKEY *pkey)
36 {
37     ASN1_BIT_STRING *prot = NULL;
38     CMP_PROTECTEDPART prot_part;
39     const ASN1_OBJECT *algorOID = NULL;
40     int len;
41     size_t prot_part_der_len;
42     unsigned char *prot_part_der = NULL;
43     size_t sig_len;
44     unsigned char *protection = NULL;
45     const void *ppval = NULL;
46     int pptype = 0;
47     OSSL_CRMF_PBMPARAMETER *pbm = NULL;
48     ASN1_STRING *pbm_str = NULL;
49     const unsigned char *pbm_str_uc = NULL;
50     EVP_MD_CTX *evp_ctx = NULL;
51     int md_NID;
52     const EVP_MD *md = NULL;
53
54     if (!ossl_assert(msg != NULL))
55         return NULL;
56
57     /* construct data to be signed */
58     prot_part.header = msg->header;
59     prot_part.body = msg->body;
60
61     len = i2d_CMP_PROTECTEDPART(&prot_part, &prot_part_der);
62     if (len < 0 || prot_part_der == NULL) {
63         CMPerr(0, CMP_R_ERROR_CALCULATING_PROTECTION);
64         goto end;
65     }
66     prot_part_der_len = (size_t) len;
67
68     if (msg->header->protectionAlg == NULL) {
69         CMPerr(0, CMP_R_UNKNOWN_ALGORITHM_ID);
70         goto end;
71     }
72     X509_ALGOR_get0(&algorOID, &pptype, &ppval, msg->header->protectionAlg);
73
74     if (secret != NULL && pkey == NULL) {
75         if (ppval == NULL) {
76             CMPerr(0, CMP_R_ERROR_CALCULATING_PROTECTION);
77             goto end;
78         }
79         if (NID_id_PasswordBasedMAC != OBJ_obj2nid(algorOID)) {
80             CMPerr(0, CMP_R_WRONG_ALGORITHM_OID);
81             goto end;
82         }
83         pbm_str = (ASN1_STRING *)ppval;
84         pbm_str_uc = pbm_str->data;
85         pbm = d2i_OSSL_CRMF_PBMPARAMETER(NULL, &pbm_str_uc, pbm_str->length);
86         if (pbm == NULL) {
87             CMPerr(0, CMP_R_WRONG_ALGORITHM_OID);
88             goto end;
89         }
90
91         if (!OSSL_CRMF_pbm_new(pbm, prot_part_der, prot_part_der_len,
92                                secret->data, secret->length,
93                                &protection, &sig_len))
94             goto end;
95     } else if (secret == NULL && pkey != NULL) {
96         /* TODO combine this with large parts of CRMF_poposigningkey_init() */
97         /* EVP_DigestSignInit() checks that pkey type is correct for the alg */
98
99         if (!OBJ_find_sigid_algs(OBJ_obj2nid(algorOID), &md_NID, NULL)
100                 || (md = EVP_get_digestbynid(md_NID)) == NULL
101                 || (evp_ctx = EVP_MD_CTX_new()) == NULL) {
102             CMPerr(0, CMP_R_UNKNOWN_ALGORITHM_ID);
103             goto end;
104         }
105         if (EVP_DigestSignInit(evp_ctx, NULL, md, NULL, pkey) <= 0
106                 || EVP_DigestSignUpdate(evp_ctx, prot_part_der,
107                                         prot_part_der_len) <= 0
108                 || EVP_DigestSignFinal(evp_ctx, NULL, &sig_len) <= 0
109                 || (protection = OPENSSL_malloc(sig_len)) == NULL
110                 || EVP_DigestSignFinal(evp_ctx, protection, &sig_len) <= 0) {
111             CMPerr(0, CMP_R_ERROR_CALCULATING_PROTECTION);
112             goto end;
113         }
114     } else {
115         CMPerr(0, CMP_R_INVALID_ARGS);
116         goto end;
117     }
118
119     if ((prot = ASN1_BIT_STRING_new()) == NULL)
120         goto end;
121     /* OpenSSL defaults all bit strings to be encoded as ASN.1 NamedBitList */
122     prot->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
123     prot->flags |= ASN1_STRING_FLAG_BITS_LEFT;
124     if (!ASN1_BIT_STRING_set(prot, protection, sig_len)) {
125         ASN1_BIT_STRING_free(prot);
126         prot = NULL;
127     }
128
129  end:
130     OSSL_CRMF_PBMPARAMETER_free(pbm);
131     EVP_MD_CTX_free(evp_ctx);
132     OPENSSL_free(protection);
133     OPENSSL_free(prot_part_der);
134     return prot;
135 }
136
137 int ossl_cmp_msg_add_extraCerts(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg)
138 {
139     if (!ossl_assert(ctx != NULL && msg != NULL))
140         return 0;
141
142     if (msg->extraCerts == NULL
143             && (msg->extraCerts = sk_X509_new_null()) == NULL)
144         return 0;
145
146     if (ctx->clCert != NULL) {
147         /* Make sure that our own cert gets sent, in the first position */
148         if (!X509_up_ref(ctx->clCert))
149             return 0;
150         if (!sk_X509_push(msg->extraCerts, ctx->clCert)) {
151             X509_free(ctx->clCert);
152             return 0;
153         }
154         /* if we have untrusted store, try to add intermediate certs */
155         if (ctx->untrusted_certs != NULL) {
156             STACK_OF(X509) *chain =
157                 ossl_cmp_build_cert_chain(ctx->untrusted_certs, ctx->clCert);
158             int res = ossl_cmp_sk_X509_add1_certs(msg->extraCerts, chain,
159                                                   1 /* no self-signed */,
160                                                   1 /* no duplicates */, 0);
161             sk_X509_pop_free(chain, X509_free);
162             if (res == 0)
163                 return 0;
164         }
165     }
166
167     /* add any additional certificates from ctx->extraCertsOut */
168     if (!ossl_cmp_sk_X509_add1_certs(msg->extraCerts, ctx->extraCertsOut, 0,
169                                      1 /* no duplicates */, 0))
170         return 0;
171
172     /* if none was found avoid empty ASN.1 sequence */
173     if (sk_X509_num(msg->extraCerts) == 0) {
174         sk_X509_free(msg->extraCerts);
175         msg->extraCerts = NULL;
176     }
177     return 1;
178 }
179
180 /*
181  * Create an X509_ALGOR structure for PasswordBasedMAC protection based on
182  * the pbm settings in the context
183  * returns pointer to X509_ALGOR on success, NULL on error
184  */
185 static X509_ALGOR *create_pbmac_algor(OSSL_CMP_CTX *ctx)
186 {
187     X509_ALGOR *alg = NULL;
188     OSSL_CRMF_PBMPARAMETER *pbm = NULL;
189     unsigned char *pbm_der = NULL;
190     int pbm_der_len;
191     ASN1_STRING *pbm_str = NULL;
192
193     if (!ossl_assert(ctx != NULL))
194         return NULL;
195
196     alg = X509_ALGOR_new();
197     pbm = OSSL_CRMF_pbmp_new(ctx->pbm_slen, ctx->pbm_owf, ctx->pbm_itercnt,
198                              ctx->pbm_mac);
199     pbm_str = ASN1_STRING_new();
200     if (alg == NULL || pbm == NULL || pbm_str == NULL)
201         goto err;
202
203     if ((pbm_der_len = i2d_OSSL_CRMF_PBMPARAMETER(pbm, &pbm_der)) < 0)
204         goto err;
205
206     if (!ASN1_STRING_set(pbm_str, pbm_der, pbm_der_len))
207         goto err;
208     OPENSSL_free(pbm_der);
209
210     X509_ALGOR_set0(alg, OBJ_nid2obj(NID_id_PasswordBasedMAC),
211                     V_ASN1_SEQUENCE, pbm_str);
212     OSSL_CRMF_PBMPARAMETER_free(pbm);
213     return alg;
214
215  err:
216     ASN1_STRING_free(pbm_str);
217     X509_ALGOR_free(alg);
218     OPENSSL_free(pbm_der);
219     OSSL_CRMF_PBMPARAMETER_free(pbm);
220     return NULL;
221 }
222
223 int ossl_cmp_msg_protect(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg)
224 {
225     if (!ossl_assert(ctx != NULL && msg != NULL))
226         return 0;
227
228     if (ctx->unprotectedSend)
229         return 1;
230
231     /* use PasswordBasedMac according to 5.1.3.1 if secretValue is given */
232     if (ctx->secretValue != NULL) {
233         if ((msg->header->protectionAlg = create_pbmac_algor(ctx)) == NULL)
234             goto err;
235         if (ctx->referenceValue != NULL
236                 && !ossl_cmp_hdr_set1_senderKID(msg->header,
237                                                 ctx->referenceValue))
238             goto err;
239
240         /*
241          * add any additional certificates from ctx->extraCertsOut
242          * while not needed to validate the signing cert, the option to do
243          * this might be handy for certain use cases
244          */
245         if (!ossl_cmp_msg_add_extraCerts(ctx, msg))
246             goto err;
247
248         if ((msg->protection =
249              ossl_cmp_calc_protection(msg, ctx->secretValue, NULL)) == NULL)
250             goto err;
251     } else {
252         /*
253          * use MSG_SIG_ALG according to 5.1.3.3 if client Certificate and
254          * private key is given
255          */
256         if (ctx->clCert != NULL && ctx->pkey != NULL) {
257             const ASN1_OCTET_STRING *subjKeyIDStr = NULL;
258             int algNID = 0;
259             ASN1_OBJECT *alg = NULL;
260
261             /* make sure that key and certificate match */
262             if (!X509_check_private_key(ctx->clCert, ctx->pkey)) {
263                 CMPerr(0, CMP_R_CERT_AND_KEY_DO_NOT_MATCH);
264                 goto err;
265             }
266
267             if (msg->header->protectionAlg == NULL)
268                 if ((msg->header->protectionAlg = X509_ALGOR_new()) == NULL)
269                     goto err;
270
271             if (!OBJ_find_sigid_by_algs(&algNID, ctx->digest,
272                                         EVP_PKEY_id(ctx->pkey))) {
273                 CMPerr(0, CMP_R_UNSUPPORTED_KEY_TYPE);
274                 goto err;
275             }
276             if ((alg = OBJ_nid2obj(algNID)) == NULL)
277                 goto err;
278             if (!X509_ALGOR_set0(msg->header->protectionAlg,
279                                  alg, V_ASN1_UNDEF, NULL)) {
280                 ASN1_OBJECT_free(alg);
281                 goto err;
282             }
283
284             /*
285              * set senderKID to keyIdentifier of the used certificate according
286              * to section 5.1.1
287              */
288             subjKeyIDStr = X509_get0_subject_key_id(ctx->clCert);
289             if (subjKeyIDStr != NULL
290                     && !ossl_cmp_hdr_set1_senderKID(msg->header, subjKeyIDStr))
291                 goto err;
292
293             /*
294              * Add ctx->clCert followed, if possible, by its chain built
295              * from ctx->untrusted_certs, and then ctx->extraCertsOut
296              */
297             if (!ossl_cmp_msg_add_extraCerts(ctx, msg))
298                 goto err;
299
300             if ((msg->protection =
301                  ossl_cmp_calc_protection(msg, NULL, ctx->pkey)) == NULL)
302                 goto err;
303         } else {
304             CMPerr(0, CMP_R_MISSING_KEY_INPUT_FOR_CREATING_PROTECTION);
305             goto err;
306         }
307     }
308
309     return 1;
310  err:
311     CMPerr(0, CMP_R_ERROR_PROTECTING_MESSAGE);
312     return 0;
313 }