Debian Codegraph @

external/boringssl/crypto/ec/ec_asn1.c

raw
1 /* Written by Nils Larsch for the OpenSSL project. */
2 /* ====================================================================
3 * Copyright (c) 2000-2003 The OpenSSL Project. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 *
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in
14 * the documentation and/or other materials provided with the
15 * distribution.
16 *
17 * 3. All advertising materials mentioning features or use of this
18 * software must display the following acknowledgment:
19 * "This product includes software developed by the OpenSSL Project
20 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
21 *
22 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23 * endorse or promote products derived from this software without
24 * prior written permission. For written permission, please contact
25 * [email protected].
26 *
27 * 5. Products derived from this software may not be called "OpenSSL"
28 * nor may "OpenSSL" appear in their names without prior written
29 * permission of the OpenSSL Project.
30 *
31 * 6. Redistributions of any form whatsoever must retain the following
32 * acknowledgment:
33 * "This product includes software developed by the OpenSSL Project
34 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
35 *
36 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
40 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47 * OF THE POSSIBILITY OF SUCH DAMAGE.
48 * ====================================================================
49 *
50 * This product includes cryptographic software written by Eric Young
51 * ([email protected]). This product includes software written by Tim
52 * Hudson ([email protected]). */
53
54 #include <openssl/ec.h>
55
56 #include <limits.h>
57 #include <string.h>
58
59 #include <openssl/bytestring.h>
60 #include <openssl/bn.h>
61 #include <openssl/err.h>
62 #include <openssl/mem.h>
63 #include <openssl/nid.h>
64
65 #include "internal.h"
66 #include "../bytestring/internal.h"
67
68
69 static const uint8_t kParametersTag =
70 CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0;
71 static const uint8_t kPublicKeyTag =
72 CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 1;
73
74 EC_KEY *EC_KEY_parse_private_key(CBS *cbs, const EC_GROUP *group) {
75 CBS ec_private_key, private_key;
76 uint64_t version;
77 if (!CBS_get_asn1(cbs, &ec_private_key, CBS_ASN1_SEQUENCE) ||
78 !CBS_get_asn1_uint64(&ec_private_key, &version) ||
79 version != 1 ||
80 !CBS_get_asn1(&ec_private_key, &private_key, CBS_ASN1_OCTETSTRING)) {
81 OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
82 return NULL;
83 }
84
85 /* Parse the optional parameters field. */
86 EC_GROUP *inner_group = NULL;
87 EC_KEY *ret = NULL;
88 if (CBS_peek_asn1_tag(&ec_private_key, kParametersTag)) {
89 /* Per SEC 1, as an alternative to omitting it, one is allowed to specify
90 * this field and put in a NULL to mean inheriting this value. This was
91 * omitted in a previous version of this logic without problems, so leave it
92 * unimplemented. */
93 CBS child;
94 if (!CBS_get_asn1(&ec_private_key, &child, kParametersTag)) {
95 OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
96 goto err;
97 }
98 inner_group = EC_KEY_parse_parameters(&child);
99 if (inner_group == NULL) {
100 goto err;
101 }
102 if (group == NULL) {
103 group = inner_group;
104 } else if (EC_GROUP_cmp(group, inner_group, NULL) != 0) {
105 /* If a group was supplied externally, it must match. */
106 OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH);
107 goto err;
108 }
109 if (CBS_len(&child) != 0) {
110 OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
111 goto err;
112 }
113 }
114
115 if (group == NULL) {
116 OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS);
117 goto err;
118 }
119
120 ret = EC_KEY_new();
121 if (ret == NULL || !EC_KEY_set_group(ret, group)) {
122 goto err;
123 }
124
125 /* Although RFC 5915 specifies the length of the key, OpenSSL historically
126 * got this wrong, so accept any length. See upstream's
127 * 30cd4ff294252c4b6a4b69cbef6a5b4117705d22. */
128 ret->priv_key =
129 BN_bin2bn(CBS_data(&private_key), CBS_len(&private_key), NULL);
130 ret->pub_key = EC_POINT_new(group);
131 if (ret->priv_key == NULL || ret->pub_key == NULL) {
132 goto err;
133 }
134
135 if (BN_cmp(ret->priv_key, EC_GROUP_get0_order(group)) >= 0) {
136 OPENSSL_PUT_ERROR(EC, EC_R_WRONG_ORDER);
137 goto err;
138 }
139
140 if (CBS_peek_asn1_tag(&ec_private_key, kPublicKeyTag)) {
141 CBS child, public_key;
142 uint8_t padding;
143 if (!CBS_get_asn1(&ec_private_key, &child, kPublicKeyTag) ||
144 !CBS_get_asn1(&child, &public_key, CBS_ASN1_BITSTRING) ||
145 /* As in a SubjectPublicKeyInfo, the byte-encoded public key is then
146 * encoded as a BIT STRING with bits ordered as in the DER encoding. */
147 !CBS_get_u8(&public_key, &padding) ||
148 padding != 0 ||
149 /* Explicitly check |public_key| is non-empty to save the conversion
150 * form later. */
151 CBS_len(&public_key) == 0 ||
152 !EC_POINT_oct2point(group, ret->pub_key, CBS_data(&public_key),
153 CBS_len(&public_key), NULL) ||
154 CBS_len(&child) != 0) {
155 OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
156 goto err;
157 }
158
159 /* Save the point conversion form.
160 * TODO(davidben): Consider removing this. */
161 ret->conv_form = (point_conversion_form_t)(CBS_data(&public_key)[0] & ~0x01);
162 } else {
163 /* Compute the public key instead. */
164 if (!EC_POINT_mul(group, ret->pub_key, ret->priv_key, NULL, NULL, NULL)) {
165 goto err;
166 }
167 /* Remember the original private-key-only encoding.
168 * TODO(davidben): Consider removing this. */
169 ret->enc_flag |= EC_PKEY_NO_PUBKEY;
170 }
171
172 if (CBS_len(&ec_private_key) != 0) {
173 OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
174 goto err;
175 }
176
177 /* Ensure the resulting key is valid. */
178 if (!EC_KEY_check_key(ret)) {
179 goto err;
180 }
181
182 EC_GROUP_free(inner_group);
183 return ret;
184
185 err:
186 EC_KEY_free(ret);
187 EC_GROUP_free(inner_group);
188 return NULL;
189 }
190
191 int EC_KEY_marshal_private_key(CBB *cbb, const EC_KEY *key,
192 unsigned enc_flags) {
193 if (key == NULL || key->group == NULL || key->priv_key == NULL) {
194 OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
195 return 0;
196 }
197
198 CBB ec_private_key, private_key;
199 if (!CBB_add_asn1(cbb, &ec_private_key, CBS_ASN1_SEQUENCE) ||
200 !CBB_add_asn1_uint64(&ec_private_key, 1 /* version */) ||
201 !CBB_add_asn1(&ec_private_key, &private_key, CBS_ASN1_OCTETSTRING) ||
202 !BN_bn2cbb_padded(&private_key,
203 BN_num_bytes(EC_GROUP_get0_order(key->group)),
204 key->priv_key)) {
205 OPENSSL_PUT_ERROR(EC, EC_R_ENCODE_ERROR);
206 return 0;
207 }
208
209 if (!(enc_flags & EC_PKEY_NO_PARAMETERS)) {
210 CBB child;
211 if (!CBB_add_asn1(&ec_private_key, &child, kParametersTag) ||
212 !EC_KEY_marshal_curve_name(&child, key->group) ||
213 !CBB_flush(&ec_private_key)) {
214 OPENSSL_PUT_ERROR(EC, EC_R_ENCODE_ERROR);
215 return 0;
216 }
217 }
218
219 /* TODO(fork): replace this flexibility with sensible default? */
220 if (!(enc_flags & EC_PKEY_NO_PUBKEY) && key->pub_key != NULL) {
221 CBB child, public_key;
222 if (!CBB_add_asn1(&ec_private_key, &child, kPublicKeyTag) ||
223 !CBB_add_asn1(&child, &public_key, CBS_ASN1_BITSTRING) ||
224 /* As in a SubjectPublicKeyInfo, the byte-encoded public key is then
225 * encoded as a BIT STRING with bits ordered as in the DER encoding. */
226 !CBB_add_u8(&public_key, 0 /* padding */) ||
227 !EC_POINT_point2cbb(&public_key, key->group, key->pub_key,
228 key->conv_form, NULL) ||
229 !CBB_flush(&ec_private_key)) {
230 OPENSSL_PUT_ERROR(EC, EC_R_ENCODE_ERROR);
231 return 0;
232 }
233 }
234
235 if (!CBB_flush(cbb)) {
236 OPENSSL_PUT_ERROR(EC, EC_R_ENCODE_ERROR);
237 return 0;
238 }
239
240 return 1;
241 }
242
243 /* is_unsigned_integer returns one if |cbs| is a valid unsigned DER INTEGER and
244 * zero otherwise. */
245 static int is_unsigned_integer(const CBS *cbs) {
246 if (CBS_len(cbs) == 0) {
247 return 0;
248 }
249 uint8_t byte = CBS_data(cbs)[0];
250 if ((byte & 0x80) ||
251 (byte == 0 && CBS_len(cbs) > 1 && (CBS_data(cbs)[1] & 0x80) == 0)) {
252 /* Negative or not minimally-encoded. */
253 return 0;
254 }
255 return 1;
256 }
257
258 /* kPrimeFieldOID is the encoding of 1.2.840.10045.1.1. */
259 static const uint8_t kPrimeField[] = {0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01};
260
261 static int parse_explicit_prime_curve(CBS *in, CBS *out_prime, CBS *out_a,
262 CBS *out_b, CBS *out_base_x,
263 CBS *out_base_y, CBS *out_order) {
264 /* See RFC 3279, section 2.3.5. Note that RFC 3279 calls this structure an
265 * ECParameters while RFC 5480 calls it a SpecifiedECDomain. */
266 CBS params, field_id, field_type, curve, base;
267 uint64_t version;
268 if (!CBS_get_asn1(in, &params, CBS_ASN1_SEQUENCE) ||
269 !CBS_get_asn1_uint64(&params, &version) ||
270 version != 1 ||
271 !CBS_get_asn1(&params, &field_id, CBS_ASN1_SEQUENCE) ||
272 !CBS_get_asn1(&field_id, &field_type, CBS_ASN1_OBJECT) ||
273 CBS_len(&field_type) != sizeof(kPrimeField) ||
274 memcmp(CBS_data(&field_type), kPrimeField, sizeof(kPrimeField)) != 0 ||
275 !CBS_get_asn1(&field_id, out_prime, CBS_ASN1_INTEGER) ||
276 !is_unsigned_integer(out_prime) ||
277 CBS_len(&field_id) != 0 ||
278 !CBS_get_asn1(&params, &curve, CBS_ASN1_SEQUENCE) ||
279 !CBS_get_asn1(&curve, out_a, CBS_ASN1_OCTETSTRING) ||
280 !CBS_get_asn1(&curve, out_b, CBS_ASN1_OCTETSTRING) ||
281 /* |curve| has an optional BIT STRING seed which we ignore. */
282 !CBS_get_asn1(&params, &base, CBS_ASN1_OCTETSTRING) ||
283 !CBS_get_asn1(&params, out_order, CBS_ASN1_INTEGER) ||
284 !is_unsigned_integer(out_order)) {
285 OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
286 return 0;
287 }
288
289 /* |params| has an optional cofactor which we ignore. With the optional seed
290 * in |curve|, a group already has arbitrarily many encodings. Parse enough to
291 * uniquely determine the curve. */
292
293 /* Require that the base point use uncompressed form. */
294 uint8_t form;
295 if (!CBS_get_u8(&base, &form) || form != POINT_CONVERSION_UNCOMPRESSED) {
296 OPENSSL_PUT_ERROR(EC, EC_R_INVALID_FORM);
297 return 0;
298 }
299
300 if (CBS_len(&base) % 2 != 0) {
301 OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
302 return 0;
303 }
304 size_t field_len = CBS_len(&base) / 2;
305 CBS_init(out_base_x, CBS_data(&base), field_len);
306 CBS_init(out_base_y, CBS_data(&base) + field_len, field_len);
307
308 return 1;
309 }
310
311 /* integers_equal returns one if |a| and |b| are equal, up to leading zeros, and
312 * zero otherwise. */
313 static int integers_equal(const CBS *a, const uint8_t *b, size_t b_len) {
314 /* Remove leading zeros from |a| and |b|. */
315 CBS a_copy = *a;
316 while (CBS_len(&a_copy) > 0 && CBS_data(&a_copy)[0] == 0) {
317 CBS_skip(&a_copy, 1);
318 }
319 while (b_len > 0 && b[0] == 0) {
320 b++;
321 b_len--;
322 }
323 return CBS_mem_equal(&a_copy, b, b_len);
324 }
325
326 EC_GROUP *EC_KEY_parse_curve_name(CBS *cbs) {
327 CBS named_curve;
328 if (!CBS_get_asn1(cbs, &named_curve, CBS_ASN1_OBJECT)) {
329 OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
330 return NULL;
331 }
332
333 /* Look for a matching curve. */
334 unsigned i;
335 for (i = 0; OPENSSL_built_in_curves[i].nid != NID_undef; i++) {
336 const struct built_in_curve *curve = &OPENSSL_built_in_curves[i];
337 if (CBS_len(&named_curve) == curve->oid_len &&
338 memcmp(CBS_data(&named_curve), curve->oid, curve->oid_len) == 0) {
339 return EC_GROUP_new_by_curve_name(curve->nid);
340 }
341 }
342
343 OPENSSL_PUT_ERROR(EC, EC_R_UNKNOWN_GROUP);
344 return NULL;
345 }
346
347 int EC_KEY_marshal_curve_name(CBB *cbb, const EC_GROUP *group) {
348 int nid = EC_GROUP_get_curve_name(group);
349 if (nid == NID_undef) {
350 OPENSSL_PUT_ERROR(EC, EC_R_UNKNOWN_GROUP);
351 return 0;
352 }
353
354 unsigned i;
355 for (i = 0; OPENSSL_built_in_curves[i].nid != NID_undef; i++) {
356 const struct built_in_curve *curve = &OPENSSL_built_in_curves[i];
357 if (curve->nid == nid) {
358 CBB child;
359 return CBB_add_asn1(cbb, &child, CBS_ASN1_OBJECT) &&
360 CBB_add_bytes(&child, curve->oid, curve->oid_len) &&
361 CBB_flush(cbb);
362 }
363 }
364
365 OPENSSL_PUT_ERROR(EC, EC_R_UNKNOWN_GROUP);
366 return 0;
367 }
368
369 EC_GROUP *EC_KEY_parse_parameters(CBS *cbs) {
370 if (!CBS_peek_asn1_tag(cbs, CBS_ASN1_SEQUENCE)) {
371 return EC_KEY_parse_curve_name(cbs);
372 }
373
374 /* OpenSSL sometimes produces ECPrivateKeys with explicitly-encoded versions
375 * of named curves.
376 *
377 * TODO(davidben): Remove support for this. */
378 CBS prime, a, b, base_x, base_y, order;
379 if (!parse_explicit_prime_curve(cbs, &prime, &a, &b, &base_x, &base_y,
380 &order)) {
381 return NULL;
382 }
383
384 /* Look for a matching prime curve. */
385 unsigned i;
386 for (i = 0; OPENSSL_built_in_curves[i].nid != NID_undef; i++) {
387 const struct built_in_curve *curve = &OPENSSL_built_in_curves[i];
388 const unsigned param_len = curve->data->param_len;
389 /* |curve->data->data| is ordered p, a, b, x, y, order, each component
390 * zero-padded up to the field length. Although SEC 1 states that the
391 * Field-Element-to-Octet-String conversion also pads, OpenSSL mis-encodes
392 * |a| and |b|, so this comparison must allow omitting leading zeros. (This
393 * is relevant for P-521 whose |b| has a leading 0.) */
394 if (integers_equal(&prime, curve->data->data, param_len) &&
395 integers_equal(&a, curve->data->data + param_len, param_len) &&
396 integers_equal(&b, curve->data->data + param_len * 2, param_len) &&
397 integers_equal(&base_x, curve->data->data + param_len * 3, param_len) &&
398 integers_equal(&base_y, curve->data->data + param_len * 4, param_len) &&
399 integers_equal(&order, curve->data->data + param_len * 5, param_len)) {
400 return EC_GROUP_new_by_curve_name(curve->nid);
401 }
402 }
403
404 OPENSSL_PUT_ERROR(EC, EC_R_UNKNOWN_GROUP);
405 return NULL;
406 }
407
408 EC_KEY *d2i_ECPrivateKey(EC_KEY **out, const uint8_t **inp, long len) {
409 /* This function treats its |out| parameter differently from other |d2i|
410 * functions. If supplied, take the group from |*out|. */
411 const EC_GROUP *group = NULL;
412 if (out != NULL && *out != NULL) {
413 group = EC_KEY_get0_group(*out);
414 }
415
416 if (len < 0) {
417 OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
418 return NULL;
419 }
420 CBS cbs;
421 CBS_init(&cbs, *inp, (size_t)len);
422 EC_KEY *ret = EC_KEY_parse_private_key(&cbs, group);
423 if (ret == NULL) {
424 return NULL;
425 }
426 if (out != NULL) {
427 EC_KEY_free(*out);
428 *out = ret;
429 }
430 *inp = CBS_data(&cbs);
431 return ret;
432 }
433
434 int i2d_ECPrivateKey(const EC_KEY *key, uint8_t **outp) {
435 CBB cbb;
436 if (!CBB_init(&cbb, 0) ||
437 !EC_KEY_marshal_private_key(&cbb, key, EC_KEY_get_enc_flags(key))) {
438 CBB_cleanup(&cbb);
439 return -1;
440 }
441 return CBB_finish_i2d(&cbb, outp);
442 }
443
444 EC_KEY *d2i_ECParameters(EC_KEY **out_key, const uint8_t **inp, long len) {
445 if (len < 0) {
446 return NULL;
447 }
448
449 CBS cbs;
450 CBS_init(&cbs, *inp, (size_t)len);
451 EC_GROUP *group = EC_KEY_parse_parameters(&cbs);
452 if (group == NULL) {
453 return NULL;
454 }
455
456 EC_KEY *ret = EC_KEY_new();
457 if (ret == NULL || !EC_KEY_set_group(ret, group)) {
458 EC_GROUP_free(group);
459 EC_KEY_free(ret);
460 return NULL;
461 }
462 EC_GROUP_free(group);
463
464 if (out_key != NULL) {
465 EC_KEY_free(*out_key);
466 *out_key = ret;
467 }
468 *inp = CBS_data(&cbs);
469 return ret;
470 }
471
472 int i2d_ECParameters(const EC_KEY *key, uint8_t **outp) {
473 if (key == NULL || key->group == NULL) {
474 OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
475 return -1;
476 }
477
478 CBB cbb;
479 if (!CBB_init(&cbb, 0) ||
480 !EC_KEY_marshal_curve_name(&cbb, key->group)) {
481 CBB_cleanup(&cbb);
482 return -1;
483 }
484 return CBB_finish_i2d(&cbb, outp);
485 }
486
487 EC_KEY *o2i_ECPublicKey(EC_KEY **keyp, const uint8_t **inp, long len) {
488 EC_KEY *ret = NULL;
489
490 if (keyp == NULL || *keyp == NULL || (*keyp)->group == NULL) {
491 OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
492 return NULL;
493 }
494 ret = *keyp;
495 if (ret->pub_key == NULL &&
496 (ret->pub_key = EC_POINT_new(ret->group)) == NULL) {
497 OPENSSL_PUT_ERROR(EC, ERR_R_MALLOC_FAILURE);
498 return NULL;
499 }
500 if (!EC_POINT_oct2point(ret->group, ret->pub_key, *inp, len, NULL)) {
501 OPENSSL_PUT_ERROR(EC, ERR_R_EC_LIB);
502 return NULL;
503 }
504 /* save the point conversion form */
505 ret->conv_form = (point_conversion_form_t)(*inp[0] & ~0x01);
506 *inp += len;
507 return ret;
508 }
509
510 int i2o_ECPublicKey(const EC_KEY *key, uint8_t **outp) {
511 size_t buf_len = 0;
512 int new_buffer = 0;
513
514 if (key == NULL) {
515 OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
516 return 0;
517 }
518
519 buf_len = EC_POINT_point2oct(key->group, key->pub_key, key->conv_form, NULL,
520 0, NULL);
521
522 if (outp == NULL || buf_len == 0) {
523 /* out == NULL => just return the length of the octet string */
524 return buf_len;
525 }
526
527 if (*outp == NULL) {
528 *outp = OPENSSL_malloc(buf_len);
529 if (*outp == NULL) {
530 OPENSSL_PUT_ERROR(EC, ERR_R_MALLOC_FAILURE);
531 return 0;
532 }
533 new_buffer = 1;
534 }
535 if (!EC_POINT_point2oct(key->group, key->pub_key, key->conv_form, *outp,
536 buf_len, NULL)) {
537 OPENSSL_PUT_ERROR(EC, ERR_R_EC_LIB);
538 if (new_buffer) {
539 OPENSSL_free(*outp);
540 *outp = NULL;
541 }
542 return 0;
543 }
544
545 if (!new_buffer) {
546 *outp += buf_len;
547 }
548 return buf_len;
549 }