removed trailing spaces ([[:space:]]+$)
[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 * reference count
44 */
45 refcount_t ref;
46 };
47
48 /**
49 * find a token in a S-expression. If a key is given, its length is used to
50 * pad the output to a given length.
51 */
52 chunk_t gcrypt_rsa_find_token(gcry_sexp_t sexp, char *name, gcry_sexp_t key)
53 {
54 gcry_sexp_t token;
55 chunk_t data = chunk_empty, tmp;
56 size_t len = 0;
57
58 token = gcry_sexp_find_token(sexp, name, 1);
59 if (token)
60 {
61 data.ptr = (char*)gcry_sexp_nth_data(token, 1, &data.len);
62 if (!data.ptr)
63 {
64 data.len = 0;
65 }
66 else
67 {
68 if (key)
69 {
70 /* gcrypt might return more bytes than necessary. Truncate
71 * to key lenght if key given, or prepend zeros if needed */
72 len = gcry_pk_get_nbits(key);
73 len = len / 8 + (len % 8 ? 1 : 0);
74 if (len > data.len)
75 {
76 tmp = chunk_alloc(len);
77 len -= data.len;
78 memset(tmp.ptr, 0, tmp.len - len);
79 memcpy(tmp.ptr + len, data.ptr, data.len);
80 data = tmp;
81 }
82 else if (len < data.len)
83 {
84 data = chunk_clone(chunk_skip(data, data.len - len));
85 }
86 else
87 {
88 data = chunk_clone(data);
89 }
90 }
91 else
92 {
93 data = chunk_clone(data);
94 }
95 }
96 gcry_sexp_release(token);
97 }
98 return data;
99 }
100
101 /**
102 * Sign a chunk of data with direct PKCS#1 encoding, no hash OID
103 */
104 static bool sign_raw(private_gcrypt_rsa_private_key_t *this,
105 chunk_t data, chunk_t *signature)
106 {
107 gcry_sexp_t in, out;
108 gcry_error_t err;
109 chunk_t em;
110 size_t k;
111
112 /* EM = 0x00 || 0x01 || PS || 0x00 || T
113 * PS = 0xFF padding, with length to fill em
114 * T = data
115 */
116 k = gcry_pk_get_nbits(this->key) / 8;
117 if (data.len > k - 3)
118 {
119 return FALSE;
120 }
121 em = chunk_alloc(k);
122 memset(em.ptr, 0xFF, em.len);
123 em.ptr[0] = 0x00;
124 em.ptr[1] = 0x01;
125 em.ptr[em.len - data.len - 1] = 0x00;
126 memcpy(em.ptr + em.len - data.len, data.ptr, data.len);
127
128 err = gcry_sexp_build(&in, NULL, "(data(flags raw)(value %b))",
129 em.len, em.ptr);
130 chunk_free(&em);
131 if (err)
132 {
133 DBG1("building signature S-expression failed: %s", gpg_strerror(err));
134 return FALSE;
135 }
136 err = gcry_pk_sign(&out, in, this->key);
137 gcry_sexp_release(in);
138 if (err)
139 {
140 DBG1("creating pkcs1 signature failed: %s", gpg_strerror(err));
141 return FALSE;
142 }
143 *signature = gcrypt_rsa_find_token(out, "s", this->key);
144 gcry_sexp_release(out);
145 return !!signature->len;
146 }
147
148 /**
149 * Sign a chunk of data using hashing and PKCS#1 encoding
150 */
151 static bool sign_pkcs1(private_gcrypt_rsa_private_key_t *this,
152 hash_algorithm_t hash_algorithm, char *hash_name,
153 chunk_t data, chunk_t *signature)
154 {
155 hasher_t *hasher;
156 chunk_t hash;
157 gcry_error_t err;
158 gcry_sexp_t in, out;
159 int hash_oid;
160
161 hash_oid = hasher_algorithm_to_oid(hash_algorithm);
162 if (hash_oid == OID_UNKNOWN)
163 {
164 return FALSE;
165 }
166 hasher = lib->crypto->create_hasher(lib->crypto, hash_algorithm);
167 if (!hasher)
168 {
169 return FALSE;
170 }
171 hasher->allocate_hash(hasher, data, &hash);
172 hasher->destroy(hasher);
173
174 err = gcry_sexp_build(&in, NULL, "(data(flags pkcs1)(hash %s %b))",
175 hash_name, hash.len, hash.ptr);
176 chunk_free(&hash);
177 if (err)
178 {
179 DBG1("building signature S-expression failed: %s", gpg_strerror(err));
180 return FALSE;
181 }
182 err = gcry_pk_sign(&out, in, this->key);
183 gcry_sexp_release(in);
184 if (err)
185 {
186 DBG1("creating pkcs1 signature failed: %s", gpg_strerror(err));
187 return FALSE;
188 }
189 *signature = gcrypt_rsa_find_token(out, "s", this->key);
190 gcry_sexp_release(out);
191 return !!signature->len;
192 }
193
194 /**
195 * Implementation of gcrypt_rsa_private_key.destroy.
196 */
197 static key_type_t get_type(private_gcrypt_rsa_private_key_t *this)
198 {
199 return KEY_RSA;
200 }
201
202 /**
203 * Implementation of gcrypt_rsa_private_key.destroy.
204 */
205 static bool sign(private_gcrypt_rsa_private_key_t *this, signature_scheme_t scheme,
206 chunk_t data, chunk_t *sig)
207 {
208 switch (scheme)
209 {
210 case SIGN_RSA_EMSA_PKCS1_NULL:
211 return sign_raw(this, data, sig);
212 case SIGN_RSA_EMSA_PKCS1_SHA1:
213 return sign_pkcs1(this, HASH_SHA1, "sha1", data, sig);
214 case SIGN_RSA_EMSA_PKCS1_SHA224:
215 return sign_pkcs1(this, HASH_SHA224, "sha224", data, sig);
216 case SIGN_RSA_EMSA_PKCS1_SHA256:
217 return sign_pkcs1(this, HASH_SHA256, "sha256", data, sig);
218 case SIGN_RSA_EMSA_PKCS1_SHA384:
219 return sign_pkcs1(this, HASH_SHA384, "sha384", data, sig);
220 case SIGN_RSA_EMSA_PKCS1_SHA512:
221 return sign_pkcs1(this, HASH_SHA512, "sha512", data, sig);
222 case SIGN_RSA_EMSA_PKCS1_MD5:
223 return sign_pkcs1(this, HASH_MD5, "md5", data, sig);
224 default:
225 DBG1("signature scheme %N not supported in RSA",
226 signature_scheme_names, scheme);
227 return FALSE;
228 }
229 }
230
231 /**
232 * Implementation of gcrypt_rsa_private_key.destroy.
233 */
234 static bool decrypt(private_gcrypt_rsa_private_key_t *this,
235 chunk_t encrypted, chunk_t *plain)
236 {
237 gcry_error_t err;
238 gcry_sexp_t in, out;
239 chunk_t padded;
240 u_char *pos = NULL;;
241
242 err = gcry_sexp_build(&in, NULL, "(enc-val(flags)(rsa(a %b)))",
243 encrypted.len, encrypted.ptr);
244 if (err)
245 {
246 DBG1("building decryption S-expression failed: %s", gpg_strerror(err));
247 return FALSE;
248 }
249 err = gcry_pk_decrypt(&out, in, this->key);
250 gcry_sexp_release(in);
251 if (err)
252 {
253 DBG1("decrypting pkcs1 data failed: %s", gpg_strerror(err));
254 return FALSE;
255 }
256 padded.ptr = (u_char*)gcry_sexp_nth_data(out, 1, &padded.len);
257 /* result is padded, but gcrypt strips leading zero:
258 * 00 | 02 | RANDOM | 00 | DATA */
259 if (padded.ptr && padded.len > 2 && padded.ptr[0] == 0x02)
260 {
261 pos = memchr(padded.ptr, 0x00, padded.len - 1);
262 if (pos)
263 {
264 pos++;
265 *plain = chunk_clone(chunk_create(
266 pos, padded.len - (pos - padded.ptr)));
267 }
268 }
269 gcry_sexp_release(out);
270 if (!pos)
271 {
272 DBG1("decrypted data has invalid pkcs1 padding");
273 return FALSE;
274 }
275 return TRUE;
276 }
277
278 /**
279 * Implementation of gcrypt_rsa_private_key.get_keysize.
280 */
281 static size_t get_keysize(private_gcrypt_rsa_private_key_t *this)
282 {
283 return gcry_pk_get_nbits(this->key) / 8;
284 }
285
286 /**
287 * Implementation of gcrypt_rsa_private_key.get_public_key.
288 */
289 static public_key_t* get_public_key(private_gcrypt_rsa_private_key_t *this)
290 {
291 chunk_t n, e;
292 public_key_t *public;
293
294 n = gcrypt_rsa_find_token(this->key, "n", NULL);
295 e = gcrypt_rsa_find_token(this->key, "e", NULL);
296
297 public = lib->creds->create(lib->creds, CRED_PUBLIC_KEY, KEY_RSA,
298 BUILD_RSA_MODULUS, n, BUILD_RSA_PUB_EXP, e, BUILD_END);
299 chunk_free(&n);
300 chunk_free(&e);
301
302 return public;
303 }
304
305 /**
306 * Implementation of private_key_t.get_encoding
307 */
308 static bool get_encoding(private_gcrypt_rsa_private_key_t *this,
309 key_encoding_type_t type, chunk_t *encoding)
310 {
311 chunk_t cn, ce, cp, cq, cd, cu, cexp1 = chunk_empty, cexp2 = chunk_empty;
312 gcry_mpi_t p = NULL, q = NULL, d = NULL, exp1, exp2;
313 gcry_error_t err;
314 bool success;
315
316 /* p and q are swapped, gcrypt expects p < q */
317 cp = gcrypt_rsa_find_token(this->key, "q", NULL);
318 cq = gcrypt_rsa_find_token(this->key, "p", NULL);
319 cd = gcrypt_rsa_find_token(this->key, "d", NULL);
320
321 err = gcry_mpi_scan(&p, GCRYMPI_FMT_USG, cp.ptr, cp.len, NULL)
322 | gcry_mpi_scan(&q, GCRYMPI_FMT_USG, cq.ptr, cq.len, NULL)
323 | gcry_mpi_scan(&d, GCRYMPI_FMT_USG, cd.ptr, cd.len, NULL);
324 if (err)
325 {
326 gcry_mpi_release(p);
327 gcry_mpi_release(q);
328 gcry_mpi_release(d);
329 chunk_clear(&cp);
330 chunk_clear(&cq);
331 chunk_clear(&cd);
332 DBG1("scanning mpi for export failed: %s", gpg_strerror(err));
333 return FALSE;
334 }
335
336 gcry_mpi_sub_ui(p, p, 1);
337 exp1 = gcry_mpi_new(gcry_pk_get_nbits(this->key));
338 gcry_mpi_mod(exp1, d, p);
339 gcry_mpi_release(p);
340
341 gcry_mpi_sub_ui(q, q, 1);
342 exp2 = gcry_mpi_new(gcry_pk_get_nbits(this->key));
343 gcry_mpi_mod(exp1, d, q);
344 gcry_mpi_release(q);
345
346 err = gcry_mpi_aprint(GCRYMPI_FMT_USG, &cexp1.ptr, &cexp1.len, exp1)
347 | gcry_mpi_aprint(GCRYMPI_FMT_USG, &cexp2.ptr, &cexp2.len, exp2);
348
349 gcry_mpi_release(d);
350 gcry_mpi_release(exp1);
351 gcry_mpi_release(exp2);
352
353 if (err)
354 {
355 DBG1("printing mpi for export failed: %s", gpg_strerror(err));
356 chunk_clear(&cp);
357 chunk_clear(&cq);
358 chunk_clear(&cd);
359 chunk_clear(&cexp1);
360 chunk_clear(&cexp2);
361 return FALSE;
362 }
363
364 cn = gcrypt_rsa_find_token(this->key, "n", NULL);
365 ce = gcrypt_rsa_find_token(this->key, "e", NULL);
366 cu = gcrypt_rsa_find_token(this->key, "u", NULL);
367
368 success = lib->encoding->encode(lib->encoding, type, NULL, encoding,
369 KEY_PART_RSA_MODULUS, cn,
370 KEY_PART_RSA_PUB_EXP, ce, KEY_PART_RSA_PRIV_EXP, cd,
371 KEY_PART_RSA_PRIME1, cp, KEY_PART_RSA_PRIME2, cq,
372 KEY_PART_RSA_EXP1, cexp1, KEY_PART_RSA_EXP2, cexp2,
373 KEY_PART_RSA_COEFF, cu, KEY_PART_END);
374 chunk_free(&cn);
375 chunk_free(&ce);
376 chunk_clear(&cd);
377 chunk_clear(&cp);
378 chunk_clear(&cq);
379 chunk_clear(&cexp1);
380 chunk_clear(&cexp2);
381 chunk_clear(&cu);
382
383 return success;
384 }
385
386 /**
387 * Implementation of private_key_t.get_fingerprint
388 */
389 static bool get_fingerprint(private_gcrypt_rsa_private_key_t *this,
390 key_encoding_type_t type, chunk_t *fp)
391 {
392 chunk_t n, e;
393 bool success;
394
395 if (lib->encoding->get_cache(lib->encoding, type, this, fp))
396 {
397 return TRUE;
398 }
399 n = gcrypt_rsa_find_token(this->key, "n", NULL);
400 e = gcrypt_rsa_find_token(this->key, "e", NULL);
401
402 success = lib->encoding->encode(lib->encoding,
403 type, this, fp, KEY_PART_RSA_MODULUS, n,
404 KEY_PART_RSA_PUB_EXP, e, KEY_PART_END);
405 chunk_free(&n);
406 chunk_free(&e);
407 return success;
408 }
409
410 /**
411 * Implementation of gcrypt_rsa_private_key.get_ref.
412 */
413 static private_key_t* get_ref(private_gcrypt_rsa_private_key_t *this)
414 {
415 ref_get(&this->ref);
416 return &this->public.interface;
417 }
418
419 /**
420 * Implementation of gcrypt_rsa_private_key.destroy.
421 */
422 static void destroy(private_gcrypt_rsa_private_key_t *this)
423 {
424 if (ref_put(&this->ref))
425 {
426 gcry_sexp_release(this->key);
427 lib->encoding->clear_cache(lib->encoding, this);
428 free(this);
429 }
430 }
431
432 /**
433 * Internal generic constructor
434 */
435 static private_gcrypt_rsa_private_key_t *gcrypt_rsa_private_key_create_empty()
436 {
437 private_gcrypt_rsa_private_key_t *this = malloc_thing(private_gcrypt_rsa_private_key_t);
438
439 this->public.interface.get_type = (key_type_t (*)(private_key_t *this))get_type;
440 this->public.interface.sign = (bool (*)(private_key_t *this, signature_scheme_t scheme, chunk_t data, chunk_t *signature))sign;
441 this->public.interface.decrypt = (bool (*)(private_key_t *this, chunk_t crypto, chunk_t *plain))decrypt;
442 this->public.interface.get_keysize = (size_t (*) (private_key_t *this))get_keysize;
443 this->public.interface.get_public_key = (public_key_t* (*)(private_key_t *this))get_public_key;
444 this->public.interface.equals = private_key_equals;
445 this->public.interface.belongs_to = private_key_belongs_to;
446 this->public.interface.get_fingerprint = (bool(*)(private_key_t*, key_encoding_type_t type, chunk_t *fp))get_fingerprint;
447 this->public.interface.get_encoding = (bool(*)(private_key_t*, key_encoding_type_t type, chunk_t *encoding))get_encoding;
448 this->public.interface.get_ref = (private_key_t* (*)(private_key_t *this))get_ref;
449 this->public.interface.destroy = (void (*)(private_key_t *this))destroy;
450
451 this->key = NULL;
452 this->ref = 1;
453
454 return this;
455 }
456
457 /**
458 * Generate an RSA key of specified key size
459 */
460 static gcrypt_rsa_private_key_t *generate(size_t key_size)
461 {
462 private_gcrypt_rsa_private_key_t *this;
463 gcry_sexp_t param, key;
464 gcry_error_t err;
465
466 err = gcry_sexp_build(&param, NULL, "(genkey(rsa(nbits %d)))", key_size);
467 if (err)
468 {
469 DBG1("building S-expression failed: %s", gpg_strerror(err));
470 return NULL;
471 }
472
473 err = gcry_pk_genkey(&key, param);
474 gcry_sexp_release(param);
475 if (err)
476 {
477 DBG1("generating RSA key failed: %s", gpg_strerror(err));
478 return NULL;
479 }
480 this = gcrypt_rsa_private_key_create_empty();
481 this->key = key;
482
483 return &this->public;
484 }
485
486 /**
487 * Load a private key from components
488 */
489 static gcrypt_rsa_private_key_t *load(chunk_t n, chunk_t e, chunk_t d,
490 chunk_t p, chunk_t q, chunk_t u)
491 {
492 gcry_error_t err;
493 private_gcrypt_rsa_private_key_t *this = gcrypt_rsa_private_key_create_empty();
494
495 err = gcry_sexp_build(&this->key, NULL,
496 "(private-key(rsa(n %b)(e %b)(d %b)(p %b)(q %b)(u %b)))",
497 n.len, n.ptr, e.len, e.ptr, d.len, d.ptr,
498 p.len, p.ptr, q.len, q.ptr, u.len, u.ptr);
499 if (err)
500 {
501 DBG1("loading private key failed: %s", gpg_strerror(err));
502 free(this);
503 return NULL;
504 }
505 err = gcry_pk_testkey(this->key);
506 if (err)
507 {
508 DBG1("private key sanity check failed: %s", gpg_strerror(err));
509 destroy(this);
510 return NULL;
511 }
512 return &this->public;
513 }
514
515 typedef struct private_builder_t private_builder_t;
516
517 /**
518 * Builder implementation for key loading/generation
519 */
520 struct private_builder_t {
521 /** implements the builder interface */
522 builder_t public;
523 /** key size, if generating */
524 u_int key_size;
525 /** rsa key parameters */
526 chunk_t n, e, d, p, q, u;
527 };
528
529 /**
530 * Implementation of builder_t.build
531 */
532 static gcrypt_rsa_private_key_t *build(private_builder_t *this)
533 {
534 gcrypt_rsa_private_key_t *key = NULL;
535
536 if (this->key_size)
537 {
538 key = generate(this->key_size);
539 }
540 else
541 {
542 key = load(this->n, this->e, this->d, this->p, this->q, this->u);
543 }
544 free(this);
545 return key;
546 }
547
548 /**
549 * Implementation of builder_t.add
550 */
551 static void add(private_builder_t *this, builder_part_t part, ...)
552 {
553 va_list args;
554
555 va_start(args, part);
556 switch (part)
557 {
558 case BUILD_KEY_SIZE:
559 this->key_size = va_arg(args, u_int);
560 return;
561 case BUILD_RSA_MODULUS:
562 this->n = va_arg(args, chunk_t);
563 break;
564 case BUILD_RSA_PUB_EXP:
565 this->e = va_arg(args, chunk_t);
566 break;
567 case BUILD_RSA_PRIV_EXP:
568 this->d = va_arg(args, chunk_t);
569 break;
570 case BUILD_RSA_PRIME1:
571 /* swap p and q, gcrypt expects p < q */
572 this->q = va_arg(args, chunk_t);
573 break;
574 case BUILD_RSA_PRIME2:
575 this->p = va_arg(args, chunk_t);
576 break;
577 case BUILD_RSA_EXP1:
578 case BUILD_RSA_EXP2:
579 /* not required for gcrypt */
580 break;
581 case BUILD_RSA_COEFF:
582 this->u = va_arg(args, chunk_t);
583 break;
584 default:
585 builder_cancel(&this->public);
586 break;
587 }
588 va_end(args);
589 }
590
591 /**
592 * Builder construction function
593 */
594 builder_t *gcrypt_rsa_private_key_builder(key_type_t type)
595 {
596 private_builder_t *this;
597
598 if (type != KEY_RSA)
599 {
600 return NULL;
601 }
602
603 this = malloc_thing(private_builder_t);
604
605 this->key_size = 0;
606 this->n = this->e = this->d = this->p = this->q = this->u = chunk_empty;
607 this->public.add = (void(*)(builder_t *this, builder_part_t part, ...))add;
608 this->public.build = (void*(*)(builder_t *this))build;
609
610 return &this->public;
611 }
612