]> git.ipfire.org Git - thirdparty/strongswan.git/blob - programs/pluto/pkcs1.c
- import of strongswan-2.7.0
[thirdparty/strongswan.git] / programs / pluto / pkcs1.c
1 /* Support of PKCS#1 private key data structures
2 * Copyright (C) 2005 Jan Hutter, Martin Willi
3 * Copyright (C) 2002-2005 Andreas Steffen
4 * Hochschule fuer Technik Rapperswil, Switzerland
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 *
16 * RCSID $Id: pkcs1.c,v 1.17 2006/01/04 21:00:43 as Exp $
17 */
18
19 #include <stddef.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include <freeswan.h>
24
25 #include "constants.h"
26 #include "defs.h"
27 #include "mp_defs.h"
28 #include "asn1.h"
29 #include "oid.h"
30 #include "log.h"
31 #include "pkcs1.h"
32 #include "md2.h"
33 #include "md5.h"
34 #include "sha1.h"
35 #include "rnd.h"
36
37 const struct fld RSA_private_field[] =
38 {
39 { "Modulus", offsetof(RSA_private_key_t, pub.n) },
40 { "PublicExponent", offsetof(RSA_private_key_t, pub.e) },
41
42 { "PrivateExponent", offsetof(RSA_private_key_t, d) },
43 { "Prime1", offsetof(RSA_private_key_t, p) },
44 { "Prime2", offsetof(RSA_private_key_t, q) },
45 { "Exponent1", offsetof(RSA_private_key_t, dP) },
46 { "Exponent2", offsetof(RSA_private_key_t, dQ) },
47 { "Coefficient", offsetof(RSA_private_key_t, qInv) },
48 };
49
50 /* ASN.1 definition of a PKCS#1 RSA private key */
51
52 static const asn1Object_t privkeyObjects[] = {
53 { 0, "RSAPrivateKey", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
54 { 1, "version", ASN1_INTEGER, ASN1_BODY }, /* 1 */
55 { 1, "modulus", ASN1_INTEGER, ASN1_BODY }, /* 2 */
56 { 1, "publicExponent", ASN1_INTEGER, ASN1_BODY }, /* 3 */
57 { 1, "privateExponent", ASN1_INTEGER, ASN1_BODY }, /* 4 */
58 { 1, "prime1", ASN1_INTEGER, ASN1_BODY }, /* 5 */
59 { 1, "prime2", ASN1_INTEGER, ASN1_BODY }, /* 6 */
60 { 1, "exponent1", ASN1_INTEGER, ASN1_BODY }, /* 7 */
61 { 1, "exponent2", ASN1_INTEGER, ASN1_BODY }, /* 8 */
62 { 1, "coefficient", ASN1_INTEGER, ASN1_BODY }, /* 9 */
63 { 1, "otherPrimeInfos", ASN1_SEQUENCE, ASN1_OPT |
64 ASN1_LOOP }, /* 10 */
65 { 2, "otherPrimeInfo", ASN1_SEQUENCE, ASN1_NONE }, /* 11 */
66 { 3, "prime", ASN1_INTEGER, ASN1_BODY }, /* 12 */
67 { 3, "exponent", ASN1_INTEGER, ASN1_BODY }, /* 13 */
68 { 3, "coefficient", ASN1_INTEGER, ASN1_BODY }, /* 14 */
69 { 1, "end opt or loop", ASN1_EOC, ASN1_END } /* 15 */
70 };
71
72 #define PKCS1_PRIV_KEY_VERSION 1
73 #define PKCS1_PRIV_KEY_MODULUS 2
74 #define PKCS1_PRIV_KEY_PUB_EXP 3
75 #define PKCS1_PRIV_KEY_COEFF 9
76 #define PKCS1_PRIV_KEY_ROOF 16
77
78
79 /*
80 * forms the FreeS/WAN keyid from the public exponent e and modulus n
81 */
82 void
83 form_keyid(chunk_t e, chunk_t n, char* keyid, unsigned *keysize)
84 {
85 /* eliminate leading zero bytes in modulus from ASN.1 coding */
86 while (n.len > 1 && *n.ptr == 0x00)
87 {
88 n.ptr++; n.len--;
89 }
90
91 /* form the FreeS/WAN keyid */
92 keyid[0] = '\0'; /* in case of splitkeytoid failure */
93 splitkeytoid(e.ptr, e.len, n.ptr, n.len, keyid, KEYID_BUF);
94
95 /* return the RSA modulus size in octets */
96 *keysize = n.len;
97 }
98
99 /*
100 * initialize an RSA_public_key_t object
101 */
102 void
103 init_RSA_public_key(RSA_public_key_t *rsa, chunk_t e, chunk_t n)
104 {
105 n_to_mpz(&rsa->e, e.ptr, e.len);
106 n_to_mpz(&rsa->n, n.ptr, n.len);
107
108 form_keyid(e, n, rsa->keyid, &rsa->k);
109 }
110
111 #ifdef DEBUG
112 static void
113 RSA_show_key_fields(RSA_private_key_t *k, int fieldcnt)
114 {
115 const struct fld *p;
116
117 DBG_log(" keyid: *%s", k->pub.keyid);
118
119 for (p = RSA_private_field; p < &RSA_private_field[fieldcnt]; p++)
120 {
121 MP_INT *n = (MP_INT *) ((char *)k + p->offset);
122 size_t sz = mpz_sizeinbase(n, 16);
123 char buf[RSA_MAX_OCTETS * 2 + 2]; /* ought to be big enough */
124
125 passert(sz <= sizeof(buf));
126 mpz_get_str(buf, 16, n);
127
128 DBG_log(" %s: 0x%s", p->name, buf);
129 }
130 }
131
132 /* debugging info that compromises security! */
133 void
134 RSA_show_private_key(RSA_private_key_t *k)
135 {
136 RSA_show_key_fields(k, elemsof(RSA_private_field));
137 }
138
139 void
140 RSA_show_public_key(RSA_public_key_t *k)
141 {
142 /* Kludge: pretend that it is a private key, but only display the
143 * first two fields (which are the public key).
144 */
145 passert(offsetof(RSA_private_key_t, pub) == 0);
146 RSA_show_key_fields((RSA_private_key_t *)k, 2);
147 }
148 #endif
149
150 err_t
151 RSA_private_key_sanity(RSA_private_key_t *k)
152 {
153 /* note that the *last* error found is reported */
154 err_t ugh = NULL;
155 mpz_t t, u, q1;
156
157 #ifdef DEBUG /* debugging info that compromises security */
158 DBG(DBG_PRIVATE, RSA_show_private_key(k));
159 #endif
160
161 /* PKCS#1 1.5 section 6 requires modulus to have at least 12 octets.
162 * We actually require more (for security).
163 */
164 if (k->pub.k < RSA_MIN_OCTETS)
165 return RSA_MIN_OCTETS_UGH;
166
167 /* we picked a max modulus size to simplify buffer allocation */
168 if (k->pub.k > RSA_MAX_OCTETS)
169 return RSA_MAX_OCTETS_UGH;
170
171 mpz_init(t);
172 mpz_init(u);
173 mpz_init(q1);
174
175 /* check that n == p * q */
176 mpz_mul(u, &k->p, &k->q);
177 if (mpz_cmp(u, &k->pub.n) != 0)
178 ugh = "n != p * q";
179
180 /* check that e divides neither p-1 nor q-1 */
181 mpz_sub_ui(t, &k->p, 1);
182 mpz_mod(t, t, &k->pub.e);
183 if (mpz_cmp_ui(t, 0) == 0)
184 ugh = "e divides p-1";
185
186 mpz_sub_ui(t, &k->q, 1);
187 mpz_mod(t, t, &k->pub.e);
188 if (mpz_cmp_ui(t, 0) == 0)
189 ugh = "e divides q-1";
190
191 /* check that d is e^-1 (mod lcm(p-1, q-1)) */
192 /* see PKCS#1v2, aka RFC 2437, for the "lcm" */
193 mpz_sub_ui(q1, &k->q, 1);
194 mpz_sub_ui(u, &k->p, 1);
195 mpz_gcd(t, u, q1); /* t := gcd(p-1, q-1) */
196 mpz_mul(u, u, q1); /* u := (p-1) * (q-1) */
197 mpz_divexact(u, u, t); /* u := lcm(p-1, q-1) */
198
199 mpz_mul(t, &k->d, &k->pub.e);
200 mpz_mod(t, t, u);
201 if (mpz_cmp_ui(t, 1) != 0)
202 ugh = "(d * e) mod (lcm(p-1, q-1)) != 1";
203
204 /* check that dP is d mod (p-1) */
205 mpz_sub_ui(u, &k->p, 1);
206 mpz_mod(t, &k->d, u);
207 if (mpz_cmp(t, &k->dP) != 0)
208 ugh = "dP is not congruent to d mod (p-1)";
209
210 /* check that dQ is d mod (q-1) */
211 mpz_sub_ui(u, &k->q, 1);
212 mpz_mod(t, &k->d, u);
213 if (mpz_cmp(t, &k->dQ) != 0)
214 ugh = "dQ is not congruent to d mod (q-1)";
215
216 /* check that qInv is (q^-1) mod p */
217 mpz_mul(t, &k->qInv, &k->q);
218 mpz_mod(t, t, &k->p);
219 if (mpz_cmp_ui(t, 1) != 0)
220 ugh = "qInv is not conguent ot (q^-1) mod p";
221
222 mpz_clear(t);
223 mpz_clear(u);
224 mpz_clear(q1);
225 return ugh;
226 }
227
228 /*
229 * Check the equality of two RSA public keys
230 */
231 bool
232 same_RSA_public_key(const RSA_public_key_t *a, const RSA_public_key_t *b)
233 {
234 return a == b
235 || (a->k == b->k && mpz_cmp(&a->n, &b->n) == 0 && mpz_cmp(&a->e, &b->e) == 0);
236 }
237
238 /*
239 * Parses a PKCS#1 private key
240 */
241 bool
242 pkcs1_parse_private_key(chunk_t blob, RSA_private_key_t *key)
243 {
244 err_t ugh = NULL;
245 asn1_ctx_t ctx;
246 chunk_t object, modulus, exp;
247 u_int level;
248 int objectID = 0;
249
250 asn1_init(&ctx, blob, 0, FALSE, DBG_PRIVATE);
251
252 while (objectID < PKCS1_PRIV_KEY_ROOF) {
253
254 if (!extract_object(privkeyObjects, &objectID, &object, &level, &ctx))
255 return FALSE;
256
257 if (objectID == PKCS1_PRIV_KEY_VERSION)
258 {
259 if (object.len > 0 && *object.ptr != 0)
260 {
261 plog(" wrong PKCS#1 private key version");
262 return FALSE;
263 }
264 }
265 else if (objectID >= PKCS1_PRIV_KEY_MODULUS &&
266 objectID <= PKCS1_PRIV_KEY_COEFF)
267 {
268 MP_INT *u = (MP_INT *) ((char *)key
269 + RSA_private_field[objectID - PKCS1_PRIV_KEY_MODULUS].offset);
270
271 n_to_mpz(u, object.ptr, object.len);
272
273 if (objectID == PKCS1_PRIV_KEY_MODULUS)
274 modulus = object;
275 else if (objectID == PKCS1_PRIV_KEY_PUB_EXP)
276 exp = object;
277 }
278 objectID++;
279 }
280 form_keyid(exp, modulus, key->pub.keyid, &key->pub.k);
281 ugh = RSA_private_key_sanity(key);
282 return (ugh == NULL);
283 }
284
285 /*
286 * compute a digest over a binary blob
287 */
288 bool
289 compute_digest(chunk_t tbs, int alg, chunk_t *digest)
290 {
291 switch (alg)
292 {
293 case OID_MD2:
294 case OID_MD2_WITH_RSA:
295 {
296 MD2_CTX context;
297 MD2Init(&context);
298 MD2Update(&context, tbs.ptr, tbs.len);
299 MD2Final(digest->ptr, &context);
300 digest->len = MD2_DIGEST_SIZE;
301 return TRUE;
302 }
303 case OID_MD5:
304 case OID_MD5_WITH_RSA:
305 {
306 MD5_CTX context;
307 MD5Init(&context);
308 MD5Update(&context, tbs.ptr, tbs.len);
309 MD5Final(digest->ptr, &context);
310 digest->len = MD5_DIGEST_SIZE;
311 return TRUE;
312 }
313 case OID_SHA1:
314 case OID_SHA1_WITH_RSA:
315 case OID_SHA1_WITH_RSA_OIW:
316 {
317 SHA1_CTX context;
318
319 SHA1Init(&context);
320 SHA1Update(&context, tbs.ptr, tbs.len);
321 SHA1Final(digest->ptr, &context);
322 digest->len = SHA1_DIGEST_SIZE;
323 return TRUE;
324 }
325 default:
326 digest->len = 0;
327 return FALSE;
328 }
329 }
330
331 /*
332 * compute an RSA signature with PKCS#1 padding
333 */
334 void
335 sign_hash(const RSA_private_key_t *k, const u_char *hash_val, size_t hash_len
336 , u_char *sig_val, size_t sig_len)
337 {
338 chunk_t ch;
339 mpz_t t1, t2;
340 size_t padlen;
341 u_char *p = sig_val;
342
343 DBG(DBG_CONTROL | DBG_CRYPT,
344 DBG_log("signing hash with RSA Key *%s", k->pub.keyid)
345 )
346 /* PKCS#1 v1.5 8.1 encryption-block formatting */
347 *p++ = 0x00;
348 *p++ = 0x01; /* BT (block type) 01 */
349 padlen = sig_len - 3 - hash_len;
350 memset(p, 0xFF, padlen);
351 p += padlen;
352 *p++ = 0x00;
353 memcpy(p, hash_val, hash_len);
354 passert(p + hash_len - sig_val == (ptrdiff_t)sig_len);
355
356 /* PKCS#1 v1.5 8.2 octet-string-to-integer conversion */
357 n_to_mpz(t1, sig_val, sig_len); /* (could skip leading 0x00) */
358
359 /* PKCS#1 v1.5 8.3 RSA computation y = x^c mod n
360 * Better described in PKCS#1 v2.0 5.1 RSADP.
361 * There are two methods, depending on the form of the private key.
362 * We use the one based on the Chinese Remainder Theorem.
363 */
364 mpz_init(t2);
365
366 mpz_powm(t2, t1, &k->dP, &k->p); /* m1 = c^dP mod p */
367
368 mpz_powm(t1, t1, &k->dQ, &k->q); /* m2 = c^dQ mod Q */
369
370 mpz_sub(t2, t2, t1); /* h = qInv (m1 - m2) mod p */
371 mpz_mod(t2, t2, &k->p);
372 mpz_mul(t2, t2, &k->qInv);
373 mpz_mod(t2, t2, &k->p);
374
375 mpz_mul(t2, t2, &k->q); /* m = m2 + h q */
376 mpz_add(t1, t1, t2);
377
378 /* PKCS#1 v1.5 8.4 integer-to-octet-string conversion */
379 ch = mpz_to_n(t1, sig_len);
380 memcpy(sig_val, ch.ptr, sig_len);
381 pfree(ch.ptr);
382
383 mpz_clear(t1);
384 mpz_clear(t2);
385 }
386
387 /*
388 * encrypt data with an RSA public key after padding
389 */
390 chunk_t
391 RSA_encrypt(const RSA_public_key_t *key, chunk_t in)
392 {
393 u_char padded[RSA_MAX_OCTETS];
394 u_char *pos = padded;
395 int padding = key->k - in.len - 3;
396 int i;
397
398 if (padding < 8 || key->k > RSA_MAX_OCTETS)
399 return empty_chunk;
400
401 /* add padding according to PKCS#1 7.2.1 1.+2. */
402 *pos++ = 0x00;
403 *pos++ = 0x02;
404
405 /* pad with pseudo random bytes unequal to zero */
406 get_rnd_bytes(pos, padding);
407 for (i = 0; i < padding; i++)
408 {
409 while (!*pos)
410 get_rnd_bytes(pos, 1);
411 pos++;
412 }
413
414 /* append the padding terminator */
415 *pos++ = 0x00;
416
417 /* now add the data */
418 memcpy(pos, in.ptr, in.len);
419 DBG(DBG_RAW,
420 DBG_dump_chunk("data for rsa encryption:\n", in);
421 DBG_dump("padded data for rsa encryption:\n", padded, key->k)
422 )
423
424 /* convert chunk to integer (PKCS#1 7.2.1 3.a) */
425 {
426 chunk_t out;
427 mpz_t m, c;
428
429 mpz_init(c);
430 n_to_mpz(m, padded, key->k);
431
432 /* encrypt(PKCS#1 7.2.1 3.b) */
433 mpz_powm(c, m, &key->e, &key->n);
434
435 /* convert integer back to a chunk (PKCS#1 7.2.1 3.c) */
436 out = mpz_to_n(c, key->k);
437 mpz_clear(c);
438 mpz_clear(m);
439
440 DBG(DBG_RAW,
441 DBG_dump_chunk("rsa encrypted data:\n", out)
442 )
443 return out;
444 }
445 }
446
447 /*
448 * decrypt data with an RSA private key and remove padding
449 */
450 bool
451 RSA_decrypt(const RSA_private_key_t *key, chunk_t in, chunk_t *out)
452 {
453 chunk_t padded;
454 u_char *pos;
455 mpz_t t1, t2;
456
457 n_to_mpz(t1, in.ptr,in.len);
458
459 /* PKCS#1 v1.5 8.3 RSA computation y = x^c mod n
460 * Better described in PKCS#1 v2.0 5.1 RSADP.
461 * There are two methods, depending on the form of the private key.
462 * We use the one based on the Chinese Remainder Theorem.
463 */
464 mpz_init(t2);
465
466 mpz_powm(t2, t1, &key->dP, &key->p); /* m1 = c^dP mod p */
467 mpz_powm(t1, t1, &key->dQ, &key->q); /* m2 = c^dQ mod Q */
468
469 mpz_sub(t2, t2, t1); /* h = qInv (m1 - m2) mod p */
470 mpz_mod(t2, t2, &key->p);
471 mpz_mul(t2, t2, &key->qInv);
472 mpz_mod(t2, t2, &key->p);
473
474 mpz_mul(t2, t2, &key->q); /* m = m2 + h q */
475 mpz_add(t1, t1, t2);
476
477 padded = mpz_to_n(t1, key->pub.k);
478 mpz_clear(t1);
479 mpz_clear(t2);
480
481 DBG(DBG_PRIVATE,
482 DBG_dump_chunk("rsa decrypted data with padding:\n", padded)
483 )
484 pos = padded.ptr;
485
486 /* PKCS#1 v1.5 8.1 encryption-block formatting (EB = 00 || 02 || PS || 00 || D) */
487
488 /* check for hex pattern 00 02 in decrypted message */
489 if ((*pos++ != 0x00) || (*(pos++) != 0x02))
490 {
491 plog("incorrect padding - probably wrong RSA key");
492 freeanychunk(padded);
493 return FALSE;
494 }
495 padded.len -= 2;
496
497 /* the plaintext data starts after first 0x00 byte */
498 while (padded.len-- > 0 && *pos++ != 0x00)
499
500 if (padded.len == 0)
501 {
502 plog("no plaintext data");
503 freeanychunk(padded);
504 return FALSE;
505 }
506
507 clonetochunk(*out, pos, padded.len, "decrypted data");
508 freeanychunk(padded);
509 return TRUE;
510 }
511
512 /*
513 * build signatureValue
514 */
515 chunk_t
516 pkcs1_build_signature(chunk_t tbs, int hash_alg, const RSA_private_key_t *key
517 , bool bit_string)
518 {
519
520 size_t siglen = key->pub.k;
521
522 u_char digest_buf[MAX_DIGEST_LEN];
523 chunk_t digest = { digest_buf, MAX_DIGEST_LEN };
524 chunk_t digestInfo, alg_id, signatureValue;
525 u_char *pos;
526
527 switch (hash_alg)
528 {
529 case OID_MD5:
530 case OID_MD5_WITH_RSA:
531 alg_id = ASN1_md5_id;
532 break;
533 case OID_SHA1:
534 case OID_SHA1_WITH_RSA:
535 alg_id = ASN1_sha1_id;
536 break;
537 default:
538 return empty_chunk;
539 }
540 compute_digest(tbs, hash_alg, &digest);
541
542 /* according to PKCS#1 v2.1 digest must be packaged into
543 * an ASN.1 structure for encryption
544 */
545 digestInfo = asn1_wrap(ASN1_SEQUENCE, "cm"
546 , alg_id
547 , asn1_simple_object(ASN1_OCTET_STRING, digest));
548
549 /* generate the RSA signature */
550 if (bit_string)
551 {
552 pos = build_asn1_object(&signatureValue, ASN1_BIT_STRING, 1 + siglen);
553 *pos++ = 0x00;
554 }
555 else
556 {
557 pos = build_asn1_object(&signatureValue, ASN1_OCTET_STRING, siglen);
558 }
559 sign_hash(key, digestInfo.ptr, digestInfo.len, pos, siglen);
560 pfree(digestInfo.ptr);
561
562 return signatureValue;
563 }
564
565 /*
566 * build a DER-encoded PKCS#1 private key object
567 */
568 chunk_t
569 pkcs1_build_private_key(const RSA_private_key_t *key)
570 {
571 chunk_t pkcs1 = asn1_wrap(ASN1_SEQUENCE, "cmmmmmmmm"
572 , ASN1_INTEGER_0
573 , asn1_integer_from_mpz(&key->pub.n)
574 , asn1_integer_from_mpz(&key->pub.e)
575 , asn1_integer_from_mpz(&key->d)
576 , asn1_integer_from_mpz(&key->p)
577 , asn1_integer_from_mpz(&key->q)
578 , asn1_integer_from_mpz(&key->dP)
579 , asn1_integer_from_mpz(&key->dQ)
580 , asn1_integer_from_mpz(&key->qInv));
581
582 DBG(DBG_PRIVATE,
583 DBG_dump_chunk("PKCS#1 encoded private key:", pkcs1)
584 )
585 return pkcs1;
586 }
587
588 /*
589 * build a DER-encoded PKCS#1 public key object
590 */
591 chunk_t
592 pkcs1_build_public_key(const RSA_public_key_t *rsa)
593 {
594 return asn1_wrap(ASN1_SEQUENCE, "mm"
595 , asn1_integer_from_mpz(&rsa->n)
596 , asn1_integer_from_mpz(&rsa->e));
597 }
598
599 /*
600 * build a DER-encoded publicKeyInfo object
601 */
602 chunk_t
603 pkcs1_build_publicKeyInfo(const RSA_public_key_t *rsa)
604 {
605 chunk_t publicKey;
606 chunk_t rawKey = pkcs1_build_public_key(rsa);
607
608 u_char *pos = build_asn1_object(&publicKey, ASN1_BIT_STRING
609 , 1 + rawKey.len);
610 *pos++ = 0x00;
611 mv_chunk(&pos, rawKey);
612
613 return asn1_wrap(ASN1_SEQUENCE, "cm"
614 , ASN1_rsaEncryption_id
615 , publicKey);
616 }
617 void
618 free_RSA_public_content(RSA_public_key_t *rsa)
619 {
620 mpz_clear(&rsa->n);
621 mpz_clear(&rsa->e);
622 }
623
624 void
625 free_RSA_private_content(RSA_private_key_t *rsak)
626 {
627 free_RSA_public_content(&rsak->pub);
628 mpz_clear(&rsak->d);
629 mpz_clear(&rsak->p);
630 mpz_clear(&rsak->q);
631 mpz_clear(&rsak->dP);
632 mpz_clear(&rsak->dQ);
633 mpz_clear(&rsak->qInv);
634 }
635