asn1_integer() ensures correct DER encoding of ASN1_INTEGER (two's complement)
[strongswan.git] / src / libstrongswan / plugins / gcrypt / gcrypt_rsa_private_key.c
1 /*
2 * Copyright (C) 2005-2009 Martin Willi
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include <gcrypt.h>
17
18 #include "gcrypt_rsa_private_key.h"
19
20 #include <debug.h>
21 #include <asn1/oid.h>
22 #include <asn1/asn1.h>
23 #include <asn1/asn1_parser.h>
24
25 typedef struct private_gcrypt_rsa_private_key_t private_gcrypt_rsa_private_key_t;
26
27 /**
28 * Private data of a gcrypt_rsa_private_key_t object.
29 */
30 struct private_gcrypt_rsa_private_key_t {
31
32 /**
33 * Public interface
34 */
35 gcrypt_rsa_private_key_t public;
36
37 /**
38 * gcrypt S-expression representing an RSA key
39 */
40 gcry_sexp_t key;
41
42 /**
43 * Keyid formed as a SHA-1 hash of a publicKey object
44 */
45 identification_t* keyid;
46
47 /**
48 * Keyid formed as a SHA-1 hash of a publicKeyInfo object
49 */
50 identification_t* keyid_info;
51
52 /**
53 * reference count
54 */
55 refcount_t ref;
56 };
57
58 /**
59 * Implemented in gcrypt_rsa_public_key.c
60 */
61 public_key_t *gcrypt_rsa_public_key_create_from_sexp(gcry_sexp_t key);
62
63 /**
64 * find a token in a S-expression
65 */
66 chunk_t gcrypt_rsa_find_token(gcry_sexp_t sexp, char *name)
67 {
68 gcry_sexp_t token;
69 chunk_t data = chunk_empty;
70
71 token = gcry_sexp_find_token(sexp, name, 1);
72 if (token)
73 {
74 data.ptr = (char*)gcry_sexp_nth_data(token, 1, &data.len);
75 if (!data.ptr)
76 {
77 data.len = 0;
78 }
79 data = chunk_clone(data);
80 gcry_sexp_release(token);
81 }
82 return data;
83 }
84
85 /**
86 * Implementation of gcrypt_rsa_private_key_t.build_emsa_pkcs1_signature.
87 */
88 static bool sign_pkcs1(private_gcrypt_rsa_private_key_t *this,
89 hash_algorithm_t hash_algorithm, char *hash_name,
90 chunk_t data, chunk_t *signature)
91 {
92 hasher_t *hasher;
93 chunk_t hash;
94 gcry_error_t err;
95 gcry_sexp_t in, out;
96 int hash_oid;
97
98 hash_oid = hasher_algorithm_to_oid(hash_algorithm);
99 if (hash_oid == OID_UNKNOWN)
100 {
101 return FALSE;
102 }
103 hasher = lib->crypto->create_hasher(lib->crypto, hash_algorithm);
104 if (!hasher)
105 {
106 return FALSE;
107 }
108 hasher->allocate_hash(hasher, data, &hash);
109 hasher->destroy(hasher);
110
111 err = gcry_sexp_build(&in, NULL, "(data(flags pkcs1)(hash %s %b))",
112 hash_name, hash.len, hash.ptr);
113 chunk_free(&hash);
114 if (err)
115 {
116 DBG1("building signature S-expression failed: %s", gpg_strerror(err));
117 return FALSE;
118 }
119 err = gcry_pk_sign(&out, in, this->key);
120 gcry_sexp_release(in);
121 if (err)
122 {
123 DBG1("creating pkcs1 signature failed: %s", gpg_strerror(err));
124 return FALSE;
125 }
126 *signature = gcrypt_rsa_find_token(out, "s");
127 gcry_sexp_release(out);
128 return !!signature->len;
129 }
130
131 /**
132 * Implementation of gcrypt_rsa_private_key.destroy.
133 */
134 static key_type_t get_type(private_gcrypt_rsa_private_key_t *this)
135 {
136 return KEY_RSA;
137 }
138
139 /**
140 * Implementation of gcrypt_rsa_private_key.destroy.
141 */
142 static bool sign(private_gcrypt_rsa_private_key_t *this, signature_scheme_t scheme,
143 chunk_t data, chunk_t *sig)
144 {
145 switch (scheme)
146 {
147 case SIGN_DEFAULT:
148 /* default is EMSA-PKCS1 using SHA1 */
149 case SIGN_RSA_EMSA_PKCS1_SHA1:
150 return sign_pkcs1(this, HASH_SHA1, "sha1", data, sig);
151 case SIGN_RSA_EMSA_PKCS1_SHA256:
152 return sign_pkcs1(this, HASH_SHA256, "sha256", data, sig);
153 case SIGN_RSA_EMSA_PKCS1_SHA384:
154 return sign_pkcs1(this, HASH_SHA384, "sha384", data, sig);
155 case SIGN_RSA_EMSA_PKCS1_SHA512:
156 return sign_pkcs1(this, HASH_SHA512, "sha512", data, sig);
157 case SIGN_RSA_EMSA_PKCS1_MD5:
158 return sign_pkcs1(this, HASH_MD5, "md5", data, sig);
159 default:
160 DBG1("signature scheme %N not supported in RSA",
161 signature_scheme_names, scheme);
162 return FALSE;
163 }
164 }
165
166 /**
167 * Implementation of gcrypt_rsa_private_key.destroy.
168 */
169 static bool decrypt(private_gcrypt_rsa_private_key_t *this,
170 chunk_t crypto, chunk_t *plain)
171 {
172 DBG1("RSA private key decryption not implemented");
173 return FALSE;
174 }
175
176 /**
177 * Implementation of gcrypt_rsa_private_key.get_keysize.
178 */
179 static size_t get_keysize(private_gcrypt_rsa_private_key_t *this)
180 {
181 return gcry_pk_get_nbits(this->key) / 8;
182 }
183
184 /**
185 * Implementation of gcrypt_rsa_private_key.destroy.
186 */
187 static identification_t* get_id(private_gcrypt_rsa_private_key_t *this,
188 id_type_t type)
189 {
190 switch (type)
191 {
192 case ID_PUBKEY_INFO_SHA1:
193 return this->keyid_info;
194 case ID_PUBKEY_SHA1:
195 return this->keyid;
196 default:
197 return NULL;
198 }
199 }
200
201 /**
202 * Implementation of gcrypt_rsa_private_key.get_public_key.
203 */
204 static public_key_t* get_public_key(private_gcrypt_rsa_private_key_t *this)
205 {
206 return gcrypt_rsa_public_key_create_from_sexp(this->key);
207 }
208
209 /**
210 * Implementation of gcrypt_rsa_private_key.equals.
211 */
212 static bool equals(private_gcrypt_rsa_private_key_t *this, private_key_t *other)
213 {
214 identification_t *keyid;
215
216 if (&this->public.interface == other)
217 {
218 return TRUE;
219 }
220 if (other->get_type(other) != KEY_RSA)
221 {
222 return FALSE;
223 }
224 keyid = other->get_id(other, ID_PUBKEY_SHA1);
225 if (keyid && keyid->equals(keyid, this->keyid))
226 {
227 return TRUE;
228 }
229 keyid = other->get_id(other, ID_PUBKEY_INFO_SHA1);
230 if (keyid && keyid->equals(keyid, this->keyid_info))
231 {
232 return TRUE;
233 }
234 return FALSE;
235 }
236
237 /**
238 * Implementation of gcrypt_rsa_private_key.belongs_to.
239 */
240 static bool belongs_to(private_gcrypt_rsa_private_key_t *this,
241 public_key_t *public)
242 {
243 identification_t *keyid;
244
245 if (public->get_type(public) != KEY_RSA)
246 {
247 return FALSE;
248 }
249 keyid = public->get_id(public, ID_PUBKEY_SHA1);
250 if (keyid && keyid->equals(keyid, this->keyid))
251 {
252 return TRUE;
253 }
254 keyid = public->get_id(public, ID_PUBKEY_INFO_SHA1);
255 if (keyid && keyid->equals(keyid, this->keyid_info))
256 {
257 return TRUE;
258 }
259 return FALSE;
260 }
261
262 /**
263 * Implementation of private_key_t.get_encoding.
264 */
265 static chunk_t get_encoding(private_gcrypt_rsa_private_key_t *this)
266 {
267 chunk_t cp, cq, cd, cexp1 = chunk_empty, cexp2 = chunk_empty;
268 gcry_mpi_t p = NULL, q = NULL, d = NULL, exp1, exp2;
269 gcry_error_t err;
270
271 /* p and q are swapped, gcrypt expects p < q */
272 cp = gcrypt_rsa_find_token(this->key, "q");
273 cq = gcrypt_rsa_find_token(this->key, "p");
274 cd = gcrypt_rsa_find_token(this->key, "d");
275
276 err = gcry_mpi_scan(&p, GCRYMPI_FMT_USG, cp.ptr, cp.len, NULL)
277 | gcry_mpi_scan(&q, GCRYMPI_FMT_USG, cq.ptr, cq.len, NULL)
278 | gcry_mpi_scan(&d, GCRYMPI_FMT_USG, cd.ptr, cd.len, NULL);
279 if (err)
280 {
281 gcry_mpi_release(p);
282 gcry_mpi_release(q);
283 gcry_mpi_release(d);
284 chunk_clear(&cp);
285 chunk_clear(&cq);
286 chunk_clear(&cd);
287 DBG1("scanning mpi for export failed: %s", gpg_strerror(err));
288 return chunk_empty;
289 }
290
291 gcry_mpi_sub_ui(p, p, 1);
292 exp1 = gcry_mpi_new(gcry_pk_get_nbits(this->key));
293 gcry_mpi_mod(exp1, d, p);
294 gcry_mpi_release(p);
295
296 gcry_mpi_sub_ui(q, q, 1);
297 exp2 = gcry_mpi_new(gcry_pk_get_nbits(this->key));
298 gcry_mpi_mod(exp1, d, q);
299 gcry_mpi_release(q);
300
301 err = gcry_mpi_aprint(GCRYMPI_FMT_USG, &cexp1.ptr, &cexp1.len, exp1)
302 | gcry_mpi_aprint(GCRYMPI_FMT_USG, &cexp2.ptr, &cexp2.len, exp2);
303
304 gcry_mpi_release(d);
305 gcry_mpi_release(exp1);
306 gcry_mpi_release(exp2);
307
308 if (err)
309 {
310 DBG1("printing mpi for export failed: %s", gpg_strerror(err));
311 chunk_clear(&cp);
312 chunk_clear(&cq);
313 chunk_clear(&cd);
314 chunk_clear(&cexp1);
315 chunk_clear(&cexp2);
316 return chunk_empty;
317 }
318
319 return asn1_wrap(ASN1_SEQUENCE, "cmmmmmmmm", ASN1_INTEGER_0,
320 asn1_integer("m", gcrypt_rsa_find_token(this->key, "n")),
321 asn1_integer("m", gcrypt_rsa_find_token(this->key, "e")),
322 asn1_integer("m", cd),
323 asn1_integer("m", cp),
324 asn1_integer("m", cq),
325 asn1_integer("m", cexp1),
326 asn1_integer("m", cexp2),
327 asn1_integer("m", gcrypt_rsa_find_token(this->key, "u")));
328 }
329
330 /**
331 * Implementation of gcrypt_rsa_private_key.get_ref.
332 */
333 static private_key_t* get_ref(private_gcrypt_rsa_private_key_t *this)
334 {
335 ref_get(&this->ref);
336 return &this->public.interface;
337 }
338
339 /**
340 * Implementation of gcrypt_rsa_private_key.destroy.
341 */
342 static void destroy(private_gcrypt_rsa_private_key_t *this)
343 {
344 if (ref_put(&this->ref))
345 {
346 DESTROY_IF(this->keyid);
347 DESTROY_IF(this->keyid_info);
348 gcry_sexp_release(this->key);
349 free(this);
350 }
351 }
352
353 /**
354 * Internal generic constructor
355 */
356 static private_gcrypt_rsa_private_key_t *gcrypt_rsa_private_key_create_empty()
357 {
358 private_gcrypt_rsa_private_key_t *this = malloc_thing(private_gcrypt_rsa_private_key_t);
359
360 this->public.interface.get_type = (key_type_t (*)(private_key_t *this))get_type;
361 this->public.interface.sign = (bool (*)(private_key_t *this, signature_scheme_t scheme, chunk_t data, chunk_t *signature))sign;
362 this->public.interface.decrypt = (bool (*)(private_key_t *this, chunk_t crypto, chunk_t *plain))decrypt;
363 this->public.interface.get_keysize = (size_t (*) (private_key_t *this))get_keysize;
364 this->public.interface.get_id = (identification_t* (*) (private_key_t *this,id_type_t))get_id;
365 this->public.interface.get_public_key = (public_key_t* (*)(private_key_t *this))get_public_key;
366 this->public.interface.equals = (bool (*) (private_key_t*, private_key_t*))equals;
367 this->public.interface.belongs_to = (bool (*) (private_key_t *this, public_key_t *public))belongs_to;
368 this->public.interface.get_encoding = (chunk_t(*)(private_key_t*))get_encoding;
369 this->public.interface.get_ref = (private_key_t* (*)(private_key_t *this))get_ref;
370 this->public.interface.destroy = (void (*)(private_key_t *this))destroy;
371
372 this->key = NULL;
373 this->keyid = NULL;
374 this->keyid_info = NULL;
375 this->ref = 1;
376
377 return this;
378 }
379
380 /**
381 * build the keyids of a private/public key
382 */
383 bool gcrypt_rsa_build_keyids(gcry_sexp_t key, identification_t **keyid,
384 identification_t **keyid_info)
385 {
386 chunk_t publicKeyInfo, publicKey, hash;
387 hasher_t *hasher;
388
389 hasher = lib->crypto->create_hasher(lib->crypto, HASH_SHA1);
390 if (!hasher)
391 {
392 DBG1("SHA1 hash algorithm not supported, unable to use RSA");
393 return FALSE;
394 }
395 publicKey = asn1_wrap(ASN1_SEQUENCE, "mm",
396 asn1_integer("m", gcrypt_rsa_find_token(key, "n")),
397 asn1_integer("m", gcrypt_rsa_find_token(key, "e")));
398 hasher->allocate_hash(hasher, publicKey, &hash);
399 *keyid = identification_create_from_encoding(ID_PUBKEY_SHA1, hash);
400 chunk_free(&hash);
401
402 publicKeyInfo = asn1_wrap(ASN1_SEQUENCE, "cm",
403 asn1_algorithmIdentifier(OID_RSA_ENCRYPTION),
404 asn1_bitstring("m", publicKey));
405 hasher->allocate_hash(hasher, publicKeyInfo, &hash);
406 *keyid_info = identification_create_from_encoding(ID_PUBKEY_INFO_SHA1, hash);
407 chunk_free(&hash);
408
409 hasher->destroy(hasher);
410 chunk_free(&publicKeyInfo);
411
412 return TRUE;
413 }
414
415 /**
416 * Generate an RSA key of specified key size
417 */
418 static gcrypt_rsa_private_key_t *generate(size_t key_size)
419 {
420 private_gcrypt_rsa_private_key_t *this;
421 gcry_sexp_t param, key;
422 gcry_error_t err;
423
424 err = gcry_sexp_build(&param, NULL, "(genkey(rsa(nbits %d)))", key_size);
425 if (err)
426 {
427 DBG1("building S-expression failed: %s", gpg_strerror(err));
428 return NULL;
429 }
430
431 err = gcry_pk_genkey(&key, param);
432 gcry_sexp_release(param);
433 if (err)
434 {
435 DBG1("generating RSA key failed: %s", gpg_strerror(err));
436 return NULL;
437 }
438 this = gcrypt_rsa_private_key_create_empty();
439 this->key = key;
440
441 if (!gcrypt_rsa_build_keyids(this->key, &this->keyid, &this->keyid_info))
442 {
443 destroy(this);
444 return NULL;
445 }
446
447 return &this->public;
448 }
449
450 /**
451 * ASN.1 definition of a PKCS#1 RSA private key
452 */
453 static const asn1Object_t privkeyObjects[] = {
454 { 0, "RSAPrivateKey", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
455 { 1, "version", ASN1_INTEGER, ASN1_BODY }, /* 1 */
456 { 1, "modulus", ASN1_INTEGER, ASN1_BODY }, /* 2 */
457 { 1, "publicExponent", ASN1_INTEGER, ASN1_BODY }, /* 3 */
458 { 1, "privateExponent", ASN1_INTEGER, ASN1_BODY }, /* 4 */
459 { 1, "prime1", ASN1_INTEGER, ASN1_BODY }, /* 5 */
460 { 1, "prime2", ASN1_INTEGER, ASN1_BODY }, /* 6 */
461 { 1, "exponent1", ASN1_INTEGER, ASN1_BODY }, /* 7 */
462 { 1, "exponent2", ASN1_INTEGER, ASN1_BODY }, /* 8 */
463 { 1, "coefficient", ASN1_INTEGER, ASN1_BODY }, /* 9 */
464 { 1, "otherPrimeInfos", ASN1_SEQUENCE, ASN1_OPT |
465 ASN1_LOOP }, /* 10 */
466 { 2, "otherPrimeInfo", ASN1_SEQUENCE, ASN1_NONE }, /* 11 */
467 { 3, "prime", ASN1_INTEGER, ASN1_BODY }, /* 12 */
468 { 3, "exponent", ASN1_INTEGER, ASN1_BODY }, /* 13 */
469 { 3, "coefficient", ASN1_INTEGER, ASN1_BODY }, /* 14 */
470 { 1, "end opt or loop", ASN1_EOC, ASN1_END }, /* 15 */
471 { 0, "exit", ASN1_EOC, ASN1_EXIT }
472 };
473 #define PRIV_KEY_VERSION 1
474 #define PRIV_KEY_MODULUS 2
475 #define PRIV_KEY_PUB_EXP 3
476 #define PRIV_KEY_PRIV_EXP 4
477 #define PRIV_KEY_PRIME1 5
478 #define PRIV_KEY_PRIME2 6
479 #define PRIV_KEY_EXP1 7
480 #define PRIV_KEY_EXP2 8
481 #define PRIV_KEY_COEFF 9
482
483 /**
484 * load private key from a ASN1 encoded blob
485 */
486 static gcrypt_rsa_private_key_t *load(chunk_t blob)
487 {
488 private_gcrypt_rsa_private_key_t *this;
489 asn1_parser_t *parser;
490 chunk_t object;
491 int objectID ;
492 bool success = FALSE;
493 chunk_t n, e, d, u, p, q;
494 gcry_error_t err;
495
496 parser = asn1_parser_create(privkeyObjects, blob);
497 parser->set_flags(parser, FALSE, TRUE);
498
499 while (parser->iterate(parser, &objectID, &object))
500 {
501 switch (objectID)
502 {
503 case PRIV_KEY_VERSION:
504 if (object.len > 0 && *object.ptr != 0)
505 {
506 goto end;
507 }
508 break;
509 case PRIV_KEY_MODULUS:
510 n = object;
511 break;
512 case PRIV_KEY_PUB_EXP:
513 e = object;
514 break;
515 case PRIV_KEY_PRIV_EXP:
516 d = object;
517 break;
518 case PRIV_KEY_PRIME1:
519 /* p and q are swapped, as gcrypt expects p < q */
520 q = object;
521 break;
522 case PRIV_KEY_PRIME2:
523 p = object;
524 break;
525 case PRIV_KEY_EXP1:
526 case PRIV_KEY_EXP2:
527 break;
528 case PRIV_KEY_COEFF:
529 u = object;
530 break;
531 }
532 }
533 success = parser->success(parser);
534
535 end:
536 parser->destroy(parser);
537
538 if (!success)
539 {
540 return NULL;
541 }
542
543 this = gcrypt_rsa_private_key_create_empty();
544 err = gcry_sexp_build(&this->key, NULL,
545 "(private-key(rsa(n %b)(e %b)(d %b)(p %b)(q %b)(u %b)))",
546 n.len, n.ptr, e.len, e.ptr, d.len, d.ptr,
547 p.len, p.ptr, q.len, q.ptr, u.len, u.ptr);
548 if (err)
549 {
550 DBG1("loading private key failed: %s", gpg_strerror(err));
551 free(this);
552 return NULL;
553 }
554 err = gcry_pk_testkey(this->key);
555 if (err)
556 {
557 DBG1("private key sanity check failed: %s", gpg_strerror(err));
558 destroy(this);
559 return NULL;
560 }
561 if (!gcrypt_rsa_build_keyids(this->key, &this->keyid, &this->keyid_info))
562 {
563 destroy(this);
564 return NULL;
565 }
566 return &this->public;
567 }
568
569 typedef struct private_builder_t private_builder_t;
570
571 /**
572 * Builder implementation for key loading/generation
573 */
574 struct private_builder_t {
575 /** implements the builder interface */
576 builder_t public;
577 /** loaded/generated private key */
578 gcrypt_rsa_private_key_t *key;
579 };
580
581 /**
582 * Implementation of builder_t.build
583 */
584 static gcrypt_rsa_private_key_t *build(private_builder_t *this)
585 {
586 gcrypt_rsa_private_key_t *key = this->key;
587
588 free(this);
589 return key;
590 }
591
592 /**
593 * Implementation of builder_t.add
594 */
595 static void add(private_builder_t *this, builder_part_t part, ...)
596 {
597 if (!this->key)
598 {
599 va_list args;
600
601 switch (part)
602 {
603 case BUILD_BLOB_ASN1_DER:
604 {
605 va_start(args, part);
606 this->key = load(va_arg(args, chunk_t));
607 va_end(args);
608 return;
609 }
610 case BUILD_KEY_SIZE:
611 {
612 va_start(args, part);
613 this->key = generate(va_arg(args, u_int));
614 va_end(args);
615 return;
616 }
617 default:
618 break;
619 }
620 }
621 if (this->key)
622 {
623 destroy((private_gcrypt_rsa_private_key_t*)this->key);
624 }
625 builder_cancel(&this->public);
626 }
627
628 /**
629 * Builder construction function
630 */
631 builder_t *gcrypt_rsa_private_key_builder(key_type_t type)
632 {
633 private_builder_t *this;
634
635 if (type != KEY_RSA)
636 {
637 return NULL;
638 }
639
640 this = malloc_thing(private_builder_t);
641
642 this->key = NULL;
643 this->public.add = (void(*)(builder_t *this, builder_part_t part, ...))add;
644 this->public.build = (void*(*)(builder_t *this))build;
645
646 return &this->public;
647 }
648