Fix a couple of code paths on which, if fxp_readdir returned an error,
[u/mdw/putty] / sshrsa.c
1 /*
2 * RSA implementation for PuTTY.
3 */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <assert.h>
9
10 #include "ssh.h"
11 #include "misc.h"
12
13 int makekey(unsigned char *data, int len, struct RSAKey *result,
14 unsigned char **keystr, int order)
15 {
16 unsigned char *p = data;
17 int i, n;
18
19 if (len < 4)
20 return -1;
21
22 if (result) {
23 result->bits = 0;
24 for (i = 0; i < 4; i++)
25 result->bits = (result->bits << 8) + *p++;
26 } else
27 p += 4;
28
29 len -= 4;
30
31 /*
32 * order=0 means exponent then modulus (the keys sent by the
33 * server). order=1 means modulus then exponent (the keys
34 * stored in a keyfile).
35 */
36
37 if (order == 0) {
38 n = ssh1_read_bignum(p, len, result ? &result->exponent : NULL);
39 if (n < 0) return -1;
40 p += n;
41 len -= n;
42 }
43
44 n = ssh1_read_bignum(p, len, result ? &result->modulus : NULL);
45 if (n < 0 || (result && bignum_bitcount(result->modulus) == 0)) return -1;
46 if (result)
47 result->bytes = n - 2;
48 if (keystr)
49 *keystr = p + 2;
50 p += n;
51 len -= n;
52
53 if (order == 1) {
54 n = ssh1_read_bignum(p, len, result ? &result->exponent : NULL);
55 if (n < 0) return -1;
56 p += n;
57 len -= n;
58 }
59 return p - data;
60 }
61
62 int makeprivate(unsigned char *data, int len, struct RSAKey *result)
63 {
64 return ssh1_read_bignum(data, len, &result->private_exponent);
65 }
66
67 int rsaencrypt(unsigned char *data, int length, struct RSAKey *key)
68 {
69 Bignum b1, b2;
70 int i;
71 unsigned char *p;
72
73 if (key->bytes < length + 4)
74 return 0; /* RSA key too short! */
75
76 memmove(data + key->bytes - length, data, length);
77 data[0] = 0;
78 data[1] = 2;
79
80 for (i = 2; i < key->bytes - length - 1; i++) {
81 do {
82 data[i] = random_byte();
83 } while (data[i] == 0);
84 }
85 data[key->bytes - length - 1] = 0;
86
87 b1 = bignum_from_bytes(data, key->bytes);
88
89 b2 = modpow(b1, key->exponent, key->modulus);
90
91 p = data;
92 for (i = key->bytes; i--;) {
93 *p++ = bignum_byte(b2, i);
94 }
95
96 freebn(b1);
97 freebn(b2);
98
99 return 1;
100 }
101
102 static void sha512_mpint(SHA512_State * s, Bignum b)
103 {
104 unsigned char lenbuf[4];
105 int len;
106 len = (bignum_bitcount(b) + 8) / 8;
107 PUT_32BIT(lenbuf, len);
108 SHA512_Bytes(s, lenbuf, 4);
109 while (len-- > 0) {
110 lenbuf[0] = bignum_byte(b, len);
111 SHA512_Bytes(s, lenbuf, 1);
112 }
113 smemclr(lenbuf, sizeof(lenbuf));
114 }
115
116 /*
117 * Compute (base ^ exp) % mod, provided mod == p * q, with p,q
118 * distinct primes, and iqmp is the multiplicative inverse of q mod p.
119 * Uses Chinese Remainder Theorem to speed computation up over the
120 * obvious implementation of a single big modpow.
121 */
122 Bignum crt_modpow(Bignum base, Bignum exp, Bignum mod,
123 Bignum p, Bignum q, Bignum iqmp)
124 {
125 Bignum pm1, qm1, pexp, qexp, presult, qresult, diff, multiplier, ret0, ret;
126
127 /*
128 * Reduce the exponent mod phi(p) and phi(q), to save time when
129 * exponentiating mod p and mod q respectively. Of course, since p
130 * and q are prime, phi(p) == p-1 and similarly for q.
131 */
132 pm1 = copybn(p);
133 decbn(pm1);
134 qm1 = copybn(q);
135 decbn(qm1);
136 pexp = bigmod(exp, pm1);
137 qexp = bigmod(exp, qm1);
138
139 /*
140 * Do the two modpows.
141 */
142 presult = modpow(base, pexp, p);
143 qresult = modpow(base, qexp, q);
144
145 /*
146 * Recombine the results. We want a value which is congruent to
147 * qresult mod q, and to presult mod p.
148 *
149 * We know that iqmp * q is congruent to 1 * mod p (by definition
150 * of iqmp) and to 0 mod q (obviously). So we start with qresult
151 * (which is congruent to qresult mod both primes), and add on
152 * (presult-qresult) * (iqmp * q) which adjusts it to be congruent
153 * to presult mod p without affecting its value mod q.
154 */
155 if (bignum_cmp(presult, qresult) < 0) {
156 /*
157 * Can't subtract presult from qresult without first adding on
158 * p.
159 */
160 Bignum tmp = presult;
161 presult = bigadd(presult, p);
162 freebn(tmp);
163 }
164 diff = bigsub(presult, qresult);
165 multiplier = bigmul(iqmp, q);
166 ret0 = bigmuladd(multiplier, diff, qresult);
167
168 /*
169 * Finally, reduce the result mod n.
170 */
171 ret = bigmod(ret0, mod);
172
173 /*
174 * Free all the intermediate results before returning.
175 */
176 freebn(pm1);
177 freebn(qm1);
178 freebn(pexp);
179 freebn(qexp);
180 freebn(presult);
181 freebn(qresult);
182 freebn(diff);
183 freebn(multiplier);
184 freebn(ret0);
185
186 return ret;
187 }
188
189 /*
190 * This function is a wrapper on modpow(). It has the same effect as
191 * modpow(), but employs RSA blinding to protect against timing
192 * attacks and also uses the Chinese Remainder Theorem (implemented
193 * above, in crt_modpow()) to speed up the main operation.
194 */
195 static Bignum rsa_privkey_op(Bignum input, struct RSAKey *key)
196 {
197 Bignum random, random_encrypted, random_inverse;
198 Bignum input_blinded, ret_blinded;
199 Bignum ret;
200
201 SHA512_State ss;
202 unsigned char digest512[64];
203 int digestused = lenof(digest512);
204 int hashseq = 0;
205
206 /*
207 * Start by inventing a random number chosen uniformly from the
208 * range 2..modulus-1. (We do this by preparing a random number
209 * of the right length and retrying if it's greater than the
210 * modulus, to prevent any potential Bleichenbacher-like
211 * attacks making use of the uneven distribution within the
212 * range that would arise from just reducing our number mod n.
213 * There are timing implications to the potential retries, of
214 * course, but all they tell you is the modulus, which you
215 * already knew.)
216 *
217 * To preserve determinism and avoid Pageant needing to share
218 * the random number pool, we actually generate this `random'
219 * number by hashing stuff with the private key.
220 */
221 while (1) {
222 int bits, byte, bitsleft, v;
223 random = copybn(key->modulus);
224 /*
225 * Find the topmost set bit. (This function will return its
226 * index plus one.) Then we'll set all bits from that one
227 * downwards randomly.
228 */
229 bits = bignum_bitcount(random);
230 byte = 0;
231 bitsleft = 0;
232 while (bits--) {
233 if (bitsleft <= 0) {
234 bitsleft = 8;
235 /*
236 * Conceptually the following few lines are equivalent to
237 * byte = random_byte();
238 */
239 if (digestused >= lenof(digest512)) {
240 unsigned char seqbuf[4];
241 PUT_32BIT(seqbuf, hashseq);
242 SHA512_Init(&ss);
243 SHA512_Bytes(&ss, "RSA deterministic blinding", 26);
244 SHA512_Bytes(&ss, seqbuf, sizeof(seqbuf));
245 sha512_mpint(&ss, key->private_exponent);
246 SHA512_Final(&ss, digest512);
247 hashseq++;
248
249 /*
250 * Now hash that digest plus the signature
251 * input.
252 */
253 SHA512_Init(&ss);
254 SHA512_Bytes(&ss, digest512, sizeof(digest512));
255 sha512_mpint(&ss, input);
256 SHA512_Final(&ss, digest512);
257
258 digestused = 0;
259 }
260 byte = digest512[digestused++];
261 }
262 v = byte & 1;
263 byte >>= 1;
264 bitsleft--;
265 bignum_set_bit(random, bits, v);
266 }
267
268 /*
269 * Now check that this number is strictly greater than
270 * zero, and strictly less than modulus.
271 */
272 if (bignum_cmp(random, Zero) <= 0 ||
273 bignum_cmp(random, key->modulus) >= 0) {
274 freebn(random);
275 continue;
276 } else {
277 break;
278 }
279 }
280
281 /*
282 * RSA blinding relies on the fact that (xy)^d mod n is equal
283 * to (x^d mod n) * (y^d mod n) mod n. We invent a random pair
284 * y and y^d; then we multiply x by y, raise to the power d mod
285 * n as usual, and divide by y^d to recover x^d. Thus an
286 * attacker can't correlate the timing of the modpow with the
287 * input, because they don't know anything about the number
288 * that was input to the actual modpow.
289 *
290 * The clever bit is that we don't have to do a huge modpow to
291 * get y and y^d; we will use the number we just invented as
292 * _y^d_, and use the _public_ exponent to compute (y^d)^e = y
293 * from it, which is much faster to do.
294 */
295 random_encrypted = crt_modpow(random, key->exponent,
296 key->modulus, key->p, key->q, key->iqmp);
297 random_inverse = modinv(random, key->modulus);
298 input_blinded = modmul(input, random_encrypted, key->modulus);
299 ret_blinded = crt_modpow(input_blinded, key->private_exponent,
300 key->modulus, key->p, key->q, key->iqmp);
301 ret = modmul(ret_blinded, random_inverse, key->modulus);
302
303 freebn(ret_blinded);
304 freebn(input_blinded);
305 freebn(random_inverse);
306 freebn(random_encrypted);
307 freebn(random);
308
309 return ret;
310 }
311
312 Bignum rsadecrypt(Bignum input, struct RSAKey *key)
313 {
314 return rsa_privkey_op(input, key);
315 }
316
317 int rsastr_len(struct RSAKey *key)
318 {
319 Bignum md, ex;
320 int mdlen, exlen;
321
322 md = key->modulus;
323 ex = key->exponent;
324 mdlen = (bignum_bitcount(md) + 15) / 16;
325 exlen = (bignum_bitcount(ex) + 15) / 16;
326 return 4 * (mdlen + exlen) + 20;
327 }
328
329 void rsastr_fmt(char *str, struct RSAKey *key)
330 {
331 Bignum md, ex;
332 int len = 0, i, nibbles;
333 static const char hex[] = "0123456789abcdef";
334
335 md = key->modulus;
336 ex = key->exponent;
337
338 len += sprintf(str + len, "0x");
339
340 nibbles = (3 + bignum_bitcount(ex)) / 4;
341 if (nibbles < 1)
342 nibbles = 1;
343 for (i = nibbles; i--;)
344 str[len++] = hex[(bignum_byte(ex, i / 2) >> (4 * (i % 2))) & 0xF];
345
346 len += sprintf(str + len, ",0x");
347
348 nibbles = (3 + bignum_bitcount(md)) / 4;
349 if (nibbles < 1)
350 nibbles = 1;
351 for (i = nibbles; i--;)
352 str[len++] = hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF];
353
354 str[len] = '\0';
355 }
356
357 /*
358 * Generate a fingerprint string for the key. Compatible with the
359 * OpenSSH fingerprint code.
360 */
361 void rsa_fingerprint(char *str, int len, struct RSAKey *key)
362 {
363 struct MD5Context md5c;
364 unsigned char digest[16];
365 char buffer[16 * 3 + 40];
366 int numlen, slen, i;
367
368 MD5Init(&md5c);
369 numlen = ssh1_bignum_length(key->modulus) - 2;
370 for (i = numlen; i--;) {
371 unsigned char c = bignum_byte(key->modulus, i);
372 MD5Update(&md5c, &c, 1);
373 }
374 numlen = ssh1_bignum_length(key->exponent) - 2;
375 for (i = numlen; i--;) {
376 unsigned char c = bignum_byte(key->exponent, i);
377 MD5Update(&md5c, &c, 1);
378 }
379 MD5Final(digest, &md5c);
380
381 sprintf(buffer, "%d ", bignum_bitcount(key->modulus));
382 for (i = 0; i < 16; i++)
383 sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
384 digest[i]);
385 strncpy(str, buffer, len);
386 str[len - 1] = '\0';
387 slen = strlen(str);
388 if (key->comment && slen < len - 1) {
389 str[slen] = ' ';
390 strncpy(str + slen + 1, key->comment, len - slen - 1);
391 str[len - 1] = '\0';
392 }
393 }
394
395 /*
396 * Verify that the public data in an RSA key matches the private
397 * data. We also check the private data itself: we ensure that p >
398 * q and that iqmp really is the inverse of q mod p.
399 */
400 int rsa_verify(struct RSAKey *key)
401 {
402 Bignum n, ed, pm1, qm1;
403 int cmp;
404
405 /* n must equal pq. */
406 n = bigmul(key->p, key->q);
407 cmp = bignum_cmp(n, key->modulus);
408 freebn(n);
409 if (cmp != 0)
410 return 0;
411
412 /* e * d must be congruent to 1, modulo (p-1) and modulo (q-1). */
413 pm1 = copybn(key->p);
414 decbn(pm1);
415 ed = modmul(key->exponent, key->private_exponent, pm1);
416 cmp = bignum_cmp(ed, One);
417 sfree(ed);
418 if (cmp != 0)
419 return 0;
420
421 qm1 = copybn(key->q);
422 decbn(qm1);
423 ed = modmul(key->exponent, key->private_exponent, qm1);
424 cmp = bignum_cmp(ed, One);
425 sfree(ed);
426 if (cmp != 0)
427 return 0;
428
429 /*
430 * Ensure p > q.
431 *
432 * I have seen key blobs in the wild which were generated with
433 * p < q, so instead of rejecting the key in this case we
434 * should instead flip them round into the canonical order of
435 * p > q. This also involves regenerating iqmp.
436 */
437 if (bignum_cmp(key->p, key->q) <= 0) {
438 Bignum tmp = key->p;
439 key->p = key->q;
440 key->q = tmp;
441
442 freebn(key->iqmp);
443 key->iqmp = modinv(key->q, key->p);
444 }
445
446 /*
447 * Ensure iqmp * q is congruent to 1, modulo p.
448 */
449 n = modmul(key->iqmp, key->q, key->p);
450 cmp = bignum_cmp(n, One);
451 sfree(n);
452 if (cmp != 0)
453 return 0;
454
455 return 1;
456 }
457
458 /* Public key blob as used by Pageant: exponent before modulus. */
459 unsigned char *rsa_public_blob(struct RSAKey *key, int *len)
460 {
461 int length, pos;
462 unsigned char *ret;
463
464 length = (ssh1_bignum_length(key->modulus) +
465 ssh1_bignum_length(key->exponent) + 4);
466 ret = snewn(length, unsigned char);
467
468 PUT_32BIT(ret, bignum_bitcount(key->modulus));
469 pos = 4;
470 pos += ssh1_write_bignum(ret + pos, key->exponent);
471 pos += ssh1_write_bignum(ret + pos, key->modulus);
472
473 *len = length;
474 return ret;
475 }
476
477 /* Given a public blob, determine its length. */
478 int rsa_public_blob_len(void *data, int maxlen)
479 {
480 unsigned char *p = (unsigned char *)data;
481 int n;
482
483 if (maxlen < 4)
484 return -1;
485 p += 4; /* length word */
486 maxlen -= 4;
487
488 n = ssh1_read_bignum(p, maxlen, NULL); /* exponent */
489 if (n < 0)
490 return -1;
491 p += n;
492
493 n = ssh1_read_bignum(p, maxlen, NULL); /* modulus */
494 if (n < 0)
495 return -1;
496 p += n;
497
498 return p - (unsigned char *)data;
499 }
500
501 void freersakey(struct RSAKey *key)
502 {
503 if (key->modulus)
504 freebn(key->modulus);
505 if (key->exponent)
506 freebn(key->exponent);
507 if (key->private_exponent)
508 freebn(key->private_exponent);
509 if (key->p)
510 freebn(key->p);
511 if (key->q)
512 freebn(key->q);
513 if (key->iqmp)
514 freebn(key->iqmp);
515 if (key->comment)
516 sfree(key->comment);
517 }
518
519 /* ----------------------------------------------------------------------
520 * Implementation of the ssh-rsa signing key type.
521 */
522
523 static void getstring(char **data, int *datalen, char **p, int *length)
524 {
525 *p = NULL;
526 if (*datalen < 4)
527 return;
528 *length = GET_32BIT(*data);
529 if (*length < 0)
530 return;
531 *datalen -= 4;
532 *data += 4;
533 if (*datalen < *length)
534 return;
535 *p = *data;
536 *data += *length;
537 *datalen -= *length;
538 }
539 static Bignum getmp(char **data, int *datalen)
540 {
541 char *p;
542 int length;
543 Bignum b;
544
545 getstring(data, datalen, &p, &length);
546 if (!p)
547 return NULL;
548 b = bignum_from_bytes((unsigned char *)p, length);
549 return b;
550 }
551
552 static void *rsa2_newkey(char *data, int len)
553 {
554 char *p;
555 int slen;
556 struct RSAKey *rsa;
557
558 rsa = snew(struct RSAKey);
559 if (!rsa)
560 return NULL;
561 getstring(&data, &len, &p, &slen);
562
563 if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
564 sfree(rsa);
565 return NULL;
566 }
567 rsa->exponent = getmp(&data, &len);
568 rsa->modulus = getmp(&data, &len);
569 rsa->private_exponent = NULL;
570 rsa->p = rsa->q = rsa->iqmp = NULL;
571 rsa->comment = NULL;
572
573 return rsa;
574 }
575
576 static void rsa2_freekey(void *key)
577 {
578 struct RSAKey *rsa = (struct RSAKey *) key;
579 freersakey(rsa);
580 sfree(rsa);
581 }
582
583 static char *rsa2_fmtkey(void *key)
584 {
585 struct RSAKey *rsa = (struct RSAKey *) key;
586 char *p;
587 int len;
588
589 len = rsastr_len(rsa);
590 p = snewn(len, char);
591 rsastr_fmt(p, rsa);
592 return p;
593 }
594
595 static unsigned char *rsa2_public_blob(void *key, int *len)
596 {
597 struct RSAKey *rsa = (struct RSAKey *) key;
598 int elen, mlen, bloblen;
599 int i;
600 unsigned char *blob, *p;
601
602 elen = (bignum_bitcount(rsa->exponent) + 8) / 8;
603 mlen = (bignum_bitcount(rsa->modulus) + 8) / 8;
604
605 /*
606 * string "ssh-rsa", mpint exp, mpint mod. Total 19+elen+mlen.
607 * (three length fields, 12+7=19).
608 */
609 bloblen = 19 + elen + mlen;
610 blob = snewn(bloblen, unsigned char);
611 p = blob;
612 PUT_32BIT(p, 7);
613 p += 4;
614 memcpy(p, "ssh-rsa", 7);
615 p += 7;
616 PUT_32BIT(p, elen);
617 p += 4;
618 for (i = elen; i--;)
619 *p++ = bignum_byte(rsa->exponent, i);
620 PUT_32BIT(p, mlen);
621 p += 4;
622 for (i = mlen; i--;)
623 *p++ = bignum_byte(rsa->modulus, i);
624 assert(p == blob + bloblen);
625 *len = bloblen;
626 return blob;
627 }
628
629 static unsigned char *rsa2_private_blob(void *key, int *len)
630 {
631 struct RSAKey *rsa = (struct RSAKey *) key;
632 int dlen, plen, qlen, ulen, bloblen;
633 int i;
634 unsigned char *blob, *p;
635
636 dlen = (bignum_bitcount(rsa->private_exponent) + 8) / 8;
637 plen = (bignum_bitcount(rsa->p) + 8) / 8;
638 qlen = (bignum_bitcount(rsa->q) + 8) / 8;
639 ulen = (bignum_bitcount(rsa->iqmp) + 8) / 8;
640
641 /*
642 * mpint private_exp, mpint p, mpint q, mpint iqmp. Total 16 +
643 * sum of lengths.
644 */
645 bloblen = 16 + dlen + plen + qlen + ulen;
646 blob = snewn(bloblen, unsigned char);
647 p = blob;
648 PUT_32BIT(p, dlen);
649 p += 4;
650 for (i = dlen; i--;)
651 *p++ = bignum_byte(rsa->private_exponent, i);
652 PUT_32BIT(p, plen);
653 p += 4;
654 for (i = plen; i--;)
655 *p++ = bignum_byte(rsa->p, i);
656 PUT_32BIT(p, qlen);
657 p += 4;
658 for (i = qlen; i--;)
659 *p++ = bignum_byte(rsa->q, i);
660 PUT_32BIT(p, ulen);
661 p += 4;
662 for (i = ulen; i--;)
663 *p++ = bignum_byte(rsa->iqmp, i);
664 assert(p == blob + bloblen);
665 *len = bloblen;
666 return blob;
667 }
668
669 static void *rsa2_createkey(unsigned char *pub_blob, int pub_len,
670 unsigned char *priv_blob, int priv_len)
671 {
672 struct RSAKey *rsa;
673 char *pb = (char *) priv_blob;
674
675 rsa = rsa2_newkey((char *) pub_blob, pub_len);
676 rsa->private_exponent = getmp(&pb, &priv_len);
677 rsa->p = getmp(&pb, &priv_len);
678 rsa->q = getmp(&pb, &priv_len);
679 rsa->iqmp = getmp(&pb, &priv_len);
680
681 if (!rsa_verify(rsa)) {
682 rsa2_freekey(rsa);
683 return NULL;
684 }
685
686 return rsa;
687 }
688
689 static void *rsa2_openssh_createkey(unsigned char **blob, int *len)
690 {
691 char **b = (char **) blob;
692 struct RSAKey *rsa;
693
694 rsa = snew(struct RSAKey);
695 if (!rsa)
696 return NULL;
697 rsa->comment = NULL;
698
699 rsa->modulus = getmp(b, len);
700 rsa->exponent = getmp(b, len);
701 rsa->private_exponent = getmp(b, len);
702 rsa->iqmp = getmp(b, len);
703 rsa->p = getmp(b, len);
704 rsa->q = getmp(b, len);
705
706 if (!rsa->modulus || !rsa->exponent || !rsa->private_exponent ||
707 !rsa->iqmp || !rsa->p || !rsa->q) {
708 sfree(rsa->modulus);
709 sfree(rsa->exponent);
710 sfree(rsa->private_exponent);
711 sfree(rsa->iqmp);
712 sfree(rsa->p);
713 sfree(rsa->q);
714 sfree(rsa);
715 return NULL;
716 }
717
718 return rsa;
719 }
720
721 static int rsa2_openssh_fmtkey(void *key, unsigned char *blob, int len)
722 {
723 struct RSAKey *rsa = (struct RSAKey *) key;
724 int bloblen, i;
725
726 bloblen =
727 ssh2_bignum_length(rsa->modulus) +
728 ssh2_bignum_length(rsa->exponent) +
729 ssh2_bignum_length(rsa->private_exponent) +
730 ssh2_bignum_length(rsa->iqmp) +
731 ssh2_bignum_length(rsa->p) + ssh2_bignum_length(rsa->q);
732
733 if (bloblen > len)
734 return bloblen;
735
736 bloblen = 0;
737 #define ENC(x) \
738 PUT_32BIT(blob+bloblen, ssh2_bignum_length((x))-4); bloblen += 4; \
739 for (i = ssh2_bignum_length((x))-4; i-- ;) blob[bloblen++]=bignum_byte((x),i);
740 ENC(rsa->modulus);
741 ENC(rsa->exponent);
742 ENC(rsa->private_exponent);
743 ENC(rsa->iqmp);
744 ENC(rsa->p);
745 ENC(rsa->q);
746
747 return bloblen;
748 }
749
750 static int rsa2_pubkey_bits(void *blob, int len)
751 {
752 struct RSAKey *rsa;
753 int ret;
754
755 rsa = rsa2_newkey((char *) blob, len);
756 ret = bignum_bitcount(rsa->modulus);
757 rsa2_freekey(rsa);
758
759 return ret;
760 }
761
762 static char *rsa2_fingerprint(void *key)
763 {
764 struct RSAKey *rsa = (struct RSAKey *) key;
765 struct MD5Context md5c;
766 unsigned char digest[16], lenbuf[4];
767 char buffer[16 * 3 + 40];
768 char *ret;
769 int numlen, i;
770
771 MD5Init(&md5c);
772 MD5Update(&md5c, (unsigned char *)"\0\0\0\7ssh-rsa", 11);
773
774 #define ADD_BIGNUM(bignum) \
775 numlen = (bignum_bitcount(bignum)+8)/8; \
776 PUT_32BIT(lenbuf, numlen); MD5Update(&md5c, lenbuf, 4); \
777 for (i = numlen; i-- ;) { \
778 unsigned char c = bignum_byte(bignum, i); \
779 MD5Update(&md5c, &c, 1); \
780 }
781 ADD_BIGNUM(rsa->exponent);
782 ADD_BIGNUM(rsa->modulus);
783 #undef ADD_BIGNUM
784
785 MD5Final(digest, &md5c);
786
787 sprintf(buffer, "ssh-rsa %d ", bignum_bitcount(rsa->modulus));
788 for (i = 0; i < 16; i++)
789 sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
790 digest[i]);
791 ret = snewn(strlen(buffer) + 1, char);
792 if (ret)
793 strcpy(ret, buffer);
794 return ret;
795 }
796
797 /*
798 * This is the magic ASN.1/DER prefix that goes in the decoded
799 * signature, between the string of FFs and the actual SHA hash
800 * value. The meaning of it is:
801 *
802 * 00 -- this marks the end of the FFs; not part of the ASN.1 bit itself
803 *
804 * 30 21 -- a constructed SEQUENCE of length 0x21
805 * 30 09 -- a constructed sub-SEQUENCE of length 9
806 * 06 05 -- an object identifier, length 5
807 * 2B 0E 03 02 1A -- object id { 1 3 14 3 2 26 }
808 * (the 1,3 comes from 0x2B = 43 = 40*1+3)
809 * 05 00 -- NULL
810 * 04 14 -- a primitive OCTET STRING of length 0x14
811 * [0x14 bytes of hash data follows]
812 *
813 * The object id in the middle there is listed as `id-sha1' in
814 * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1d2.asn (the
815 * ASN module for PKCS #1) and its expanded form is as follows:
816 *
817 * id-sha1 OBJECT IDENTIFIER ::= {
818 * iso(1) identified-organization(3) oiw(14) secsig(3)
819 * algorithms(2) 26 }
820 */
821 static const unsigned char asn1_weird_stuff[] = {
822 0x00, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
823 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
824 };
825
826 #define ASN1_LEN ( (int) sizeof(asn1_weird_stuff) )
827
828 static int rsa2_verifysig(void *key, char *sig, int siglen,
829 char *data, int datalen)
830 {
831 struct RSAKey *rsa = (struct RSAKey *) key;
832 Bignum in, out;
833 char *p;
834 int slen;
835 int bytes, i, j, ret;
836 unsigned char hash[20];
837
838 getstring(&sig, &siglen, &p, &slen);
839 if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
840 return 0;
841 }
842 in = getmp(&sig, &siglen);
843 out = modpow(in, rsa->exponent, rsa->modulus);
844 freebn(in);
845
846 ret = 1;
847
848 bytes = (bignum_bitcount(rsa->modulus)+7) / 8;
849 /* Top (partial) byte should be zero. */
850 if (bignum_byte(out, bytes - 1) != 0)
851 ret = 0;
852 /* First whole byte should be 1. */
853 if (bignum_byte(out, bytes - 2) != 1)
854 ret = 0;
855 /* Most of the rest should be FF. */
856 for (i = bytes - 3; i >= 20 + ASN1_LEN; i--) {
857 if (bignum_byte(out, i) != 0xFF)
858 ret = 0;
859 }
860 /* Then we expect to see the asn1_weird_stuff. */
861 for (i = 20 + ASN1_LEN - 1, j = 0; i >= 20; i--, j++) {
862 if (bignum_byte(out, i) != asn1_weird_stuff[j])
863 ret = 0;
864 }
865 /* Finally, we expect to see the SHA-1 hash of the signed data. */
866 SHA_Simple(data, datalen, hash);
867 for (i = 19, j = 0; i >= 0; i--, j++) {
868 if (bignum_byte(out, i) != hash[j])
869 ret = 0;
870 }
871 freebn(out);
872
873 return ret;
874 }
875
876 static unsigned char *rsa2_sign(void *key, char *data, int datalen,
877 int *siglen)
878 {
879 struct RSAKey *rsa = (struct RSAKey *) key;
880 unsigned char *bytes;
881 int nbytes;
882 unsigned char hash[20];
883 Bignum in, out;
884 int i, j;
885
886 SHA_Simple(data, datalen, hash);
887
888 nbytes = (bignum_bitcount(rsa->modulus) - 1) / 8;
889 assert(1 <= nbytes - 20 - ASN1_LEN);
890 bytes = snewn(nbytes, unsigned char);
891
892 bytes[0] = 1;
893 for (i = 1; i < nbytes - 20 - ASN1_LEN; i++)
894 bytes[i] = 0xFF;
895 for (i = nbytes - 20 - ASN1_LEN, j = 0; i < nbytes - 20; i++, j++)
896 bytes[i] = asn1_weird_stuff[j];
897 for (i = nbytes - 20, j = 0; i < nbytes; i++, j++)
898 bytes[i] = hash[j];
899
900 in = bignum_from_bytes(bytes, nbytes);
901 sfree(bytes);
902
903 out = rsa_privkey_op(in, rsa);
904 freebn(in);
905
906 nbytes = (bignum_bitcount(out) + 7) / 8;
907 bytes = snewn(4 + 7 + 4 + nbytes, unsigned char);
908 PUT_32BIT(bytes, 7);
909 memcpy(bytes + 4, "ssh-rsa", 7);
910 PUT_32BIT(bytes + 4 + 7, nbytes);
911 for (i = 0; i < nbytes; i++)
912 bytes[4 + 7 + 4 + i] = bignum_byte(out, nbytes - 1 - i);
913 freebn(out);
914
915 *siglen = 4 + 7 + 4 + nbytes;
916 return bytes;
917 }
918
919 const struct ssh_signkey ssh_rsa = {
920 rsa2_newkey,
921 rsa2_freekey,
922 rsa2_fmtkey,
923 rsa2_public_blob,
924 rsa2_private_blob,
925 rsa2_createkey,
926 rsa2_openssh_createkey,
927 rsa2_openssh_fmtkey,
928 rsa2_pubkey_bits,
929 rsa2_fingerprint,
930 rsa2_verifysig,
931 rsa2_sign,
932 "ssh-rsa",
933 "rsa2"
934 };
935
936 void *ssh_rsakex_newkey(char *data, int len)
937 {
938 return rsa2_newkey(data, len);
939 }
940
941 void ssh_rsakex_freekey(void *key)
942 {
943 rsa2_freekey(key);
944 }
945
946 int ssh_rsakex_klen(void *key)
947 {
948 struct RSAKey *rsa = (struct RSAKey *) key;
949
950 return bignum_bitcount(rsa->modulus);
951 }
952
953 static void oaep_mask(const struct ssh_hash *h, void *seed, int seedlen,
954 void *vdata, int datalen)
955 {
956 unsigned char *data = (unsigned char *)vdata;
957 unsigned count = 0;
958
959 while (datalen > 0) {
960 int i, max = (datalen > h->hlen ? h->hlen : datalen);
961 void *s;
962 unsigned char counter[4], hash[SSH2_KEX_MAX_HASH_LEN];
963
964 assert(h->hlen <= SSH2_KEX_MAX_HASH_LEN);
965 PUT_32BIT(counter, count);
966 s = h->init();
967 h->bytes(s, seed, seedlen);
968 h->bytes(s, counter, 4);
969 h->final(s, hash);
970 count++;
971
972 for (i = 0; i < max; i++)
973 data[i] ^= hash[i];
974
975 data += max;
976 datalen -= max;
977 }
978 }
979
980 void ssh_rsakex_encrypt(const struct ssh_hash *h, unsigned char *in, int inlen,
981 unsigned char *out, int outlen,
982 void *key)
983 {
984 Bignum b1, b2;
985 struct RSAKey *rsa = (struct RSAKey *) key;
986 int k, i;
987 char *p;
988 const int HLEN = h->hlen;
989
990 /*
991 * Here we encrypt using RSAES-OAEP. Essentially this means:
992 *
993 * - we have a SHA-based `mask generation function' which
994 * creates a pseudo-random stream of mask data
995 * deterministically from an input chunk of data.
996 *
997 * - we have a random chunk of data called a seed.
998 *
999 * - we use the seed to generate a mask which we XOR with our
1000 * plaintext.
1001 *
1002 * - then we use _the masked plaintext_ to generate a mask
1003 * which we XOR with the seed.
1004 *
1005 * - then we concatenate the masked seed and the masked
1006 * plaintext, and RSA-encrypt that lot.
1007 *
1008 * The result is that the data input to the encryption function
1009 * is random-looking and (hopefully) contains no exploitable
1010 * structure such as PKCS1-v1_5 does.
1011 *
1012 * For a precise specification, see RFC 3447, section 7.1.1.
1013 * Some of the variable names below are derived from that, so
1014 * it'd probably help to read it anyway.
1015 */
1016
1017 /* k denotes the length in octets of the RSA modulus. */
1018 k = (7 + bignum_bitcount(rsa->modulus)) / 8;
1019
1020 /* The length of the input data must be at most k - 2hLen - 2. */
1021 assert(inlen > 0 && inlen <= k - 2*HLEN - 2);
1022
1023 /* The length of the output data wants to be precisely k. */
1024 assert(outlen == k);
1025
1026 /*
1027 * Now perform EME-OAEP encoding. First set up all the unmasked
1028 * output data.
1029 */
1030 /* Leading byte zero. */
1031 out[0] = 0;
1032 /* At position 1, the seed: HLEN bytes of random data. */
1033 for (i = 0; i < HLEN; i++)
1034 out[i + 1] = random_byte();
1035 /* At position 1+HLEN, the data block DB, consisting of: */
1036 /* The hash of the label (we only support an empty label here) */
1037 h->final(h->init(), out + HLEN + 1);
1038 /* A bunch of zero octets */
1039 memset(out + 2*HLEN + 1, 0, outlen - (2*HLEN + 1));
1040 /* A single 1 octet, followed by the input message data. */
1041 out[outlen - inlen - 1] = 1;
1042 memcpy(out + outlen - inlen, in, inlen);
1043
1044 /*
1045 * Now use the seed data to mask the block DB.
1046 */
1047 oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
1048
1049 /*
1050 * And now use the masked DB to mask the seed itself.
1051 */
1052 oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
1053
1054 /*
1055 * Now `out' contains precisely the data we want to
1056 * RSA-encrypt.
1057 */
1058 b1 = bignum_from_bytes(out, outlen);
1059 b2 = modpow(b1, rsa->exponent, rsa->modulus);
1060 p = (char *)out;
1061 for (i = outlen; i--;) {
1062 *p++ = bignum_byte(b2, i);
1063 }
1064 freebn(b1);
1065 freebn(b2);
1066
1067 /*
1068 * And we're done.
1069 */
1070 }
1071
1072 static const struct ssh_kex ssh_rsa_kex_sha1 = {
1073 "rsa1024-sha1", NULL, KEXTYPE_RSA, NULL, NULL, 0, 0, &ssh_sha1
1074 };
1075
1076 static const struct ssh_kex ssh_rsa_kex_sha256 = {
1077 "rsa2048-sha256", NULL, KEXTYPE_RSA, NULL, NULL, 0, 0, &ssh_sha256
1078 };
1079
1080 static const struct ssh_kex *const rsa_kex_list[] = {
1081 &ssh_rsa_kex_sha256,
1082 &ssh_rsa_kex_sha1
1083 };
1084
1085 const struct ssh_kexes ssh_rsa_kex = {
1086 sizeof(rsa_kex_list) / sizeof(*rsa_kex_list),
1087 rsa_kex_list
1088 };