]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshrsa.c
Update version number for 0.66 release.
[PuTTY.git] / 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         bn_restore_invariant(random);
268
269         /*
270          * Now check that this number is strictly greater than
271          * zero, and strictly less than modulus.
272          */
273         if (bignum_cmp(random, Zero) <= 0 ||
274             bignum_cmp(random, key->modulus) >= 0) {
275             freebn(random);
276             continue;
277         }
278
279         /*
280          * Also, make sure it has an inverse mod modulus.
281          */
282         random_inverse = modinv(random, key->modulus);
283         if (!random_inverse) {
284             freebn(random);
285             continue;
286         }
287
288         break;
289     }
290
291     /*
292      * RSA blinding relies on the fact that (xy)^d mod n is equal
293      * to (x^d mod n) * (y^d mod n) mod n. We invent a random pair
294      * y and y^d; then we multiply x by y, raise to the power d mod
295      * n as usual, and divide by y^d to recover x^d. Thus an
296      * attacker can't correlate the timing of the modpow with the
297      * input, because they don't know anything about the number
298      * that was input to the actual modpow.
299      * 
300      * The clever bit is that we don't have to do a huge modpow to
301      * get y and y^d; we will use the number we just invented as
302      * _y^d_, and use the _public_ exponent to compute (y^d)^e = y
303      * from it, which is much faster to do.
304      */
305     random_encrypted = crt_modpow(random, key->exponent,
306                                   key->modulus, key->p, key->q, key->iqmp);
307     input_blinded = modmul(input, random_encrypted, key->modulus);
308     ret_blinded = crt_modpow(input_blinded, key->private_exponent,
309                              key->modulus, key->p, key->q, key->iqmp);
310     ret = modmul(ret_blinded, random_inverse, key->modulus);
311
312     freebn(ret_blinded);
313     freebn(input_blinded);
314     freebn(random_inverse);
315     freebn(random_encrypted);
316     freebn(random);
317
318     return ret;
319 }
320
321 Bignum rsadecrypt(Bignum input, struct RSAKey *key)
322 {
323     return rsa_privkey_op(input, key);
324 }
325
326 int rsastr_len(struct RSAKey *key)
327 {
328     Bignum md, ex;
329     int mdlen, exlen;
330
331     md = key->modulus;
332     ex = key->exponent;
333     mdlen = (bignum_bitcount(md) + 15) / 16;
334     exlen = (bignum_bitcount(ex) + 15) / 16;
335     return 4 * (mdlen + exlen) + 20;
336 }
337
338 void rsastr_fmt(char *str, struct RSAKey *key)
339 {
340     Bignum md, ex;
341     int len = 0, i, nibbles;
342     static const char hex[] = "0123456789abcdef";
343
344     md = key->modulus;
345     ex = key->exponent;
346
347     len += sprintf(str + len, "0x");
348
349     nibbles = (3 + bignum_bitcount(ex)) / 4;
350     if (nibbles < 1)
351         nibbles = 1;
352     for (i = nibbles; i--;)
353         str[len++] = hex[(bignum_byte(ex, i / 2) >> (4 * (i % 2))) & 0xF];
354
355     len += sprintf(str + len, ",0x");
356
357     nibbles = (3 + bignum_bitcount(md)) / 4;
358     if (nibbles < 1)
359         nibbles = 1;
360     for (i = nibbles; i--;)
361         str[len++] = hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF];
362
363     str[len] = '\0';
364 }
365
366 /*
367  * Generate a fingerprint string for the key. Compatible with the
368  * OpenSSH fingerprint code.
369  */
370 void rsa_fingerprint(char *str, int len, struct RSAKey *key)
371 {
372     struct MD5Context md5c;
373     unsigned char digest[16];
374     char buffer[16 * 3 + 40];
375     int numlen, slen, i;
376
377     MD5Init(&md5c);
378     numlen = ssh1_bignum_length(key->modulus) - 2;
379     for (i = numlen; i--;) {
380         unsigned char c = bignum_byte(key->modulus, i);
381         MD5Update(&md5c, &c, 1);
382     }
383     numlen = ssh1_bignum_length(key->exponent) - 2;
384     for (i = numlen; i--;) {
385         unsigned char c = bignum_byte(key->exponent, i);
386         MD5Update(&md5c, &c, 1);
387     }
388     MD5Final(digest, &md5c);
389
390     sprintf(buffer, "%d ", bignum_bitcount(key->modulus));
391     for (i = 0; i < 16; i++)
392         sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
393                 digest[i]);
394     strncpy(str, buffer, len);
395     str[len - 1] = '\0';
396     slen = strlen(str);
397     if (key->comment && slen < len - 1) {
398         str[slen] = ' ';
399         strncpy(str + slen + 1, key->comment, len - slen - 1);
400         str[len - 1] = '\0';
401     }
402 }
403
404 /*
405  * Verify that the public data in an RSA key matches the private
406  * data. We also check the private data itself: we ensure that p >
407  * q and that iqmp really is the inverse of q mod p.
408  */
409 int rsa_verify(struct RSAKey *key)
410 {
411     Bignum n, ed, pm1, qm1;
412     int cmp;
413
414     /* n must equal pq. */
415     n = bigmul(key->p, key->q);
416     cmp = bignum_cmp(n, key->modulus);
417     freebn(n);
418     if (cmp != 0)
419         return 0;
420
421     /* e * d must be congruent to 1, modulo (p-1) and modulo (q-1). */
422     pm1 = copybn(key->p);
423     decbn(pm1);
424     ed = modmul(key->exponent, key->private_exponent, pm1);
425     freebn(pm1);
426     cmp = bignum_cmp(ed, One);
427     freebn(ed);
428     if (cmp != 0)
429         return 0;
430
431     qm1 = copybn(key->q);
432     decbn(qm1);
433     ed = modmul(key->exponent, key->private_exponent, qm1);
434     freebn(qm1);
435     cmp = bignum_cmp(ed, One);
436     freebn(ed);
437     if (cmp != 0)
438         return 0;
439
440     /*
441      * Ensure p > q.
442      *
443      * I have seen key blobs in the wild which were generated with
444      * p < q, so instead of rejecting the key in this case we
445      * should instead flip them round into the canonical order of
446      * p > q. This also involves regenerating iqmp.
447      */
448     if (bignum_cmp(key->p, key->q) <= 0) {
449         Bignum tmp = key->p;
450         key->p = key->q;
451         key->q = tmp;
452
453         freebn(key->iqmp);
454         key->iqmp = modinv(key->q, key->p);
455         if (!key->iqmp)
456             return 0;
457     }
458
459     /*
460      * Ensure iqmp * q is congruent to 1, modulo p.
461      */
462     n = modmul(key->iqmp, key->q, key->p);
463     cmp = bignum_cmp(n, One);
464     freebn(n);
465     if (cmp != 0)
466         return 0;
467
468     return 1;
469 }
470
471 /* Public key blob as used by Pageant: exponent before modulus. */
472 unsigned char *rsa_public_blob(struct RSAKey *key, int *len)
473 {
474     int length, pos;
475     unsigned char *ret;
476
477     length = (ssh1_bignum_length(key->modulus) +
478               ssh1_bignum_length(key->exponent) + 4);
479     ret = snewn(length, unsigned char);
480
481     PUT_32BIT(ret, bignum_bitcount(key->modulus));
482     pos = 4;
483     pos += ssh1_write_bignum(ret + pos, key->exponent);
484     pos += ssh1_write_bignum(ret + pos, key->modulus);
485
486     *len = length;
487     return ret;
488 }
489
490 /* Given a public blob, determine its length. */
491 int rsa_public_blob_len(void *data, int maxlen)
492 {
493     unsigned char *p = (unsigned char *)data;
494     int n;
495
496     if (maxlen < 4)
497         return -1;
498     p += 4;                            /* length word */
499     maxlen -= 4;
500
501     n = ssh1_read_bignum(p, maxlen, NULL);    /* exponent */
502     if (n < 0)
503         return -1;
504     p += n;
505
506     n = ssh1_read_bignum(p, maxlen, NULL);    /* modulus */
507     if (n < 0)
508         return -1;
509     p += n;
510
511     return p - (unsigned char *)data;
512 }
513
514 void freersakey(struct RSAKey *key)
515 {
516     if (key->modulus)
517         freebn(key->modulus);
518     if (key->exponent)
519         freebn(key->exponent);
520     if (key->private_exponent)
521         freebn(key->private_exponent);
522     if (key->p)
523         freebn(key->p);
524     if (key->q)
525         freebn(key->q);
526     if (key->iqmp)
527         freebn(key->iqmp);
528     if (key->comment)
529         sfree(key->comment);
530 }
531
532 /* ----------------------------------------------------------------------
533  * Implementation of the ssh-rsa signing key type. 
534  */
535
536 static void getstring(char **data, int *datalen, char **p, int *length)
537 {
538     *p = NULL;
539     if (*datalen < 4)
540         return;
541     *length = toint(GET_32BIT(*data));
542     if (*length < 0)
543         return;
544     *datalen -= 4;
545     *data += 4;
546     if (*datalen < *length)
547         return;
548     *p = *data;
549     *data += *length;
550     *datalen -= *length;
551 }
552 static Bignum getmp(char **data, int *datalen)
553 {
554     char *p;
555     int length;
556     Bignum b;
557
558     getstring(data, datalen, &p, &length);
559     if (!p)
560         return NULL;
561     b = bignum_from_bytes((unsigned char *)p, length);
562     return b;
563 }
564
565 static void rsa2_freekey(void *key);   /* forward reference */
566
567 static void *rsa2_newkey(char *data, int len)
568 {
569     char *p;
570     int slen;
571     struct RSAKey *rsa;
572
573     rsa = snew(struct RSAKey);
574     getstring(&data, &len, &p, &slen);
575
576     if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
577         sfree(rsa);
578         return NULL;
579     }
580     rsa->exponent = getmp(&data, &len);
581     rsa->modulus = getmp(&data, &len);
582     rsa->private_exponent = NULL;
583     rsa->p = rsa->q = rsa->iqmp = NULL;
584     rsa->comment = NULL;
585
586     if (!rsa->exponent || !rsa->modulus) {
587         rsa2_freekey(rsa);
588         return NULL;
589     }
590
591     return rsa;
592 }
593
594 static void rsa2_freekey(void *key)
595 {
596     struct RSAKey *rsa = (struct RSAKey *) key;
597     freersakey(rsa);
598     sfree(rsa);
599 }
600
601 static char *rsa2_fmtkey(void *key)
602 {
603     struct RSAKey *rsa = (struct RSAKey *) key;
604     char *p;
605     int len;
606
607     len = rsastr_len(rsa);
608     p = snewn(len, char);
609     rsastr_fmt(p, rsa);
610     return p;
611 }
612
613 static unsigned char *rsa2_public_blob(void *key, int *len)
614 {
615     struct RSAKey *rsa = (struct RSAKey *) key;
616     int elen, mlen, bloblen;
617     int i;
618     unsigned char *blob, *p;
619
620     elen = (bignum_bitcount(rsa->exponent) + 8) / 8;
621     mlen = (bignum_bitcount(rsa->modulus) + 8) / 8;
622
623     /*
624      * string "ssh-rsa", mpint exp, mpint mod. Total 19+elen+mlen.
625      * (three length fields, 12+7=19).
626      */
627     bloblen = 19 + elen + mlen;
628     blob = snewn(bloblen, unsigned char);
629     p = blob;
630     PUT_32BIT(p, 7);
631     p += 4;
632     memcpy(p, "ssh-rsa", 7);
633     p += 7;
634     PUT_32BIT(p, elen);
635     p += 4;
636     for (i = elen; i--;)
637         *p++ = bignum_byte(rsa->exponent, i);
638     PUT_32BIT(p, mlen);
639     p += 4;
640     for (i = mlen; i--;)
641         *p++ = bignum_byte(rsa->modulus, i);
642     assert(p == blob + bloblen);
643     *len = bloblen;
644     return blob;
645 }
646
647 static unsigned char *rsa2_private_blob(void *key, int *len)
648 {
649     struct RSAKey *rsa = (struct RSAKey *) key;
650     int dlen, plen, qlen, ulen, bloblen;
651     int i;
652     unsigned char *blob, *p;
653
654     dlen = (bignum_bitcount(rsa->private_exponent) + 8) / 8;
655     plen = (bignum_bitcount(rsa->p) + 8) / 8;
656     qlen = (bignum_bitcount(rsa->q) + 8) / 8;
657     ulen = (bignum_bitcount(rsa->iqmp) + 8) / 8;
658
659     /*
660      * mpint private_exp, mpint p, mpint q, mpint iqmp. Total 16 +
661      * sum of lengths.
662      */
663     bloblen = 16 + dlen + plen + qlen + ulen;
664     blob = snewn(bloblen, unsigned char);
665     p = blob;
666     PUT_32BIT(p, dlen);
667     p += 4;
668     for (i = dlen; i--;)
669         *p++ = bignum_byte(rsa->private_exponent, i);
670     PUT_32BIT(p, plen);
671     p += 4;
672     for (i = plen; i--;)
673         *p++ = bignum_byte(rsa->p, i);
674     PUT_32BIT(p, qlen);
675     p += 4;
676     for (i = qlen; i--;)
677         *p++ = bignum_byte(rsa->q, i);
678     PUT_32BIT(p, ulen);
679     p += 4;
680     for (i = ulen; i--;)
681         *p++ = bignum_byte(rsa->iqmp, i);
682     assert(p == blob + bloblen);
683     *len = bloblen;
684     return blob;
685 }
686
687 static void *rsa2_createkey(unsigned char *pub_blob, int pub_len,
688                             unsigned char *priv_blob, int priv_len)
689 {
690     struct RSAKey *rsa;
691     char *pb = (char *) priv_blob;
692
693     rsa = rsa2_newkey((char *) pub_blob, pub_len);
694     rsa->private_exponent = getmp(&pb, &priv_len);
695     rsa->p = getmp(&pb, &priv_len);
696     rsa->q = getmp(&pb, &priv_len);
697     rsa->iqmp = getmp(&pb, &priv_len);
698
699     if (!rsa_verify(rsa)) {
700         rsa2_freekey(rsa);
701         return NULL;
702     }
703
704     return rsa;
705 }
706
707 static void *rsa2_openssh_createkey(unsigned char **blob, int *len)
708 {
709     char **b = (char **) blob;
710     struct RSAKey *rsa;
711
712     rsa = snew(struct RSAKey);
713     rsa->comment = NULL;
714
715     rsa->modulus = getmp(b, len);
716     rsa->exponent = getmp(b, len);
717     rsa->private_exponent = getmp(b, len);
718     rsa->iqmp = getmp(b, len);
719     rsa->p = getmp(b, len);
720     rsa->q = getmp(b, len);
721
722     if (!rsa->modulus || !rsa->exponent || !rsa->private_exponent ||
723         !rsa->iqmp || !rsa->p || !rsa->q) {
724         rsa2_freekey(rsa);
725         return NULL;
726     }
727
728     if (!rsa_verify(rsa)) {
729         rsa2_freekey(rsa);
730         return NULL;
731     }
732
733     return rsa;
734 }
735
736 static int rsa2_openssh_fmtkey(void *key, unsigned char *blob, int len)
737 {
738     struct RSAKey *rsa = (struct RSAKey *) key;
739     int bloblen, i;
740
741     bloblen =
742         ssh2_bignum_length(rsa->modulus) +
743         ssh2_bignum_length(rsa->exponent) +
744         ssh2_bignum_length(rsa->private_exponent) +
745         ssh2_bignum_length(rsa->iqmp) +
746         ssh2_bignum_length(rsa->p) + ssh2_bignum_length(rsa->q);
747
748     if (bloblen > len)
749         return bloblen;
750
751     bloblen = 0;
752 #define ENC(x) \
753     PUT_32BIT(blob+bloblen, ssh2_bignum_length((x))-4); bloblen += 4; \
754     for (i = ssh2_bignum_length((x))-4; i-- ;) blob[bloblen++]=bignum_byte((x),i);
755     ENC(rsa->modulus);
756     ENC(rsa->exponent);
757     ENC(rsa->private_exponent);
758     ENC(rsa->iqmp);
759     ENC(rsa->p);
760     ENC(rsa->q);
761
762     return bloblen;
763 }
764
765 static int rsa2_pubkey_bits(void *blob, int len)
766 {
767     struct RSAKey *rsa;
768     int ret;
769
770     rsa = rsa2_newkey((char *) blob, len);
771     if (!rsa)
772         return -1;
773     ret = bignum_bitcount(rsa->modulus);
774     rsa2_freekey(rsa);
775
776     return ret;
777 }
778
779 static char *rsa2_fingerprint(void *key)
780 {
781     struct RSAKey *rsa = (struct RSAKey *) key;
782     struct MD5Context md5c;
783     unsigned char digest[16], lenbuf[4];
784     char buffer[16 * 3 + 40];
785     char *ret;
786     int numlen, i;
787
788     MD5Init(&md5c);
789     MD5Update(&md5c, (unsigned char *)"\0\0\0\7ssh-rsa", 11);
790
791 #define ADD_BIGNUM(bignum) \
792     numlen = (bignum_bitcount(bignum)+8)/8; \
793     PUT_32BIT(lenbuf, numlen); MD5Update(&md5c, lenbuf, 4); \
794     for (i = numlen; i-- ;) { \
795         unsigned char c = bignum_byte(bignum, i); \
796         MD5Update(&md5c, &c, 1); \
797     }
798     ADD_BIGNUM(rsa->exponent);
799     ADD_BIGNUM(rsa->modulus);
800 #undef ADD_BIGNUM
801
802     MD5Final(digest, &md5c);
803
804     sprintf(buffer, "ssh-rsa %d ", bignum_bitcount(rsa->modulus));
805     for (i = 0; i < 16; i++)
806         sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
807                 digest[i]);
808     ret = snewn(strlen(buffer) + 1, char);
809     if (ret)
810         strcpy(ret, buffer);
811     return ret;
812 }
813
814 /*
815  * This is the magic ASN.1/DER prefix that goes in the decoded
816  * signature, between the string of FFs and the actual SHA hash
817  * value. The meaning of it is:
818  * 
819  * 00 -- this marks the end of the FFs; not part of the ASN.1 bit itself
820  * 
821  * 30 21 -- a constructed SEQUENCE of length 0x21
822  *    30 09 -- a constructed sub-SEQUENCE of length 9
823  *       06 05 -- an object identifier, length 5
824  *          2B 0E 03 02 1A -- object id { 1 3 14 3 2 26 }
825  *                            (the 1,3 comes from 0x2B = 43 = 40*1+3)
826  *       05 00 -- NULL
827  *    04 14 -- a primitive OCTET STRING of length 0x14
828  *       [0x14 bytes of hash data follows]
829  * 
830  * The object id in the middle there is listed as `id-sha1' in
831  * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1d2.asn (the
832  * ASN module for PKCS #1) and its expanded form is as follows:
833  * 
834  * id-sha1                OBJECT IDENTIFIER ::= {
835  *    iso(1) identified-organization(3) oiw(14) secsig(3)
836  *    algorithms(2) 26 }
837  */
838 static const unsigned char asn1_weird_stuff[] = {
839     0x00, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
840     0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
841 };
842
843 #define ASN1_LEN ( (int) sizeof(asn1_weird_stuff) )
844
845 static int rsa2_verifysig(void *key, char *sig, int siglen,
846                           char *data, int datalen)
847 {
848     struct RSAKey *rsa = (struct RSAKey *) key;
849     Bignum in, out;
850     char *p;
851     int slen;
852     int bytes, i, j, ret;
853     unsigned char hash[20];
854
855     getstring(&sig, &siglen, &p, &slen);
856     if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
857         return 0;
858     }
859     in = getmp(&sig, &siglen);
860     if (!in)
861         return 0;
862     out = modpow(in, rsa->exponent, rsa->modulus);
863     freebn(in);
864
865     ret = 1;
866
867     bytes = (bignum_bitcount(rsa->modulus)+7) / 8;
868     /* Top (partial) byte should be zero. */
869     if (bignum_byte(out, bytes - 1) != 0)
870         ret = 0;
871     /* First whole byte should be 1. */
872     if (bignum_byte(out, bytes - 2) != 1)
873         ret = 0;
874     /* Most of the rest should be FF. */
875     for (i = bytes - 3; i >= 20 + ASN1_LEN; i--) {
876         if (bignum_byte(out, i) != 0xFF)
877             ret = 0;
878     }
879     /* Then we expect to see the asn1_weird_stuff. */
880     for (i = 20 + ASN1_LEN - 1, j = 0; i >= 20; i--, j++) {
881         if (bignum_byte(out, i) != asn1_weird_stuff[j])
882             ret = 0;
883     }
884     /* Finally, we expect to see the SHA-1 hash of the signed data. */
885     SHA_Simple(data, datalen, hash);
886     for (i = 19, j = 0; i >= 0; i--, j++) {
887         if (bignum_byte(out, i) != hash[j])
888             ret = 0;
889     }
890     freebn(out);
891
892     return ret;
893 }
894
895 static unsigned char *rsa2_sign(void *key, char *data, int datalen,
896                                 int *siglen)
897 {
898     struct RSAKey *rsa = (struct RSAKey *) key;
899     unsigned char *bytes;
900     int nbytes;
901     unsigned char hash[20];
902     Bignum in, out;
903     int i, j;
904
905     SHA_Simple(data, datalen, hash);
906
907     nbytes = (bignum_bitcount(rsa->modulus) - 1) / 8;
908     assert(1 <= nbytes - 20 - ASN1_LEN);
909     bytes = snewn(nbytes, unsigned char);
910
911     bytes[0] = 1;
912     for (i = 1; i < nbytes - 20 - ASN1_LEN; i++)
913         bytes[i] = 0xFF;
914     for (i = nbytes - 20 - ASN1_LEN, j = 0; i < nbytes - 20; i++, j++)
915         bytes[i] = asn1_weird_stuff[j];
916     for (i = nbytes - 20, j = 0; i < nbytes; i++, j++)
917         bytes[i] = hash[j];
918
919     in = bignum_from_bytes(bytes, nbytes);
920     sfree(bytes);
921
922     out = rsa_privkey_op(in, rsa);
923     freebn(in);
924
925     nbytes = (bignum_bitcount(out) + 7) / 8;
926     bytes = snewn(4 + 7 + 4 + nbytes, unsigned char);
927     PUT_32BIT(bytes, 7);
928     memcpy(bytes + 4, "ssh-rsa", 7);
929     PUT_32BIT(bytes + 4 + 7, nbytes);
930     for (i = 0; i < nbytes; i++)
931         bytes[4 + 7 + 4 + i] = bignum_byte(out, nbytes - 1 - i);
932     freebn(out);
933
934     *siglen = 4 + 7 + 4 + nbytes;
935     return bytes;
936 }
937
938 const struct ssh_signkey ssh_rsa = {
939     rsa2_newkey,
940     rsa2_freekey,
941     rsa2_fmtkey,
942     rsa2_public_blob,
943     rsa2_private_blob,
944     rsa2_createkey,
945     rsa2_openssh_createkey,
946     rsa2_openssh_fmtkey,
947     rsa2_pubkey_bits,
948     rsa2_fingerprint,
949     rsa2_verifysig,
950     rsa2_sign,
951     "ssh-rsa",
952     "rsa2"
953 };
954
955 void *ssh_rsakex_newkey(char *data, int len)
956 {
957     return rsa2_newkey(data, len);
958 }
959
960 void ssh_rsakex_freekey(void *key)
961 {
962     rsa2_freekey(key);
963 }
964
965 int ssh_rsakex_klen(void *key)
966 {
967     struct RSAKey *rsa = (struct RSAKey *) key;
968
969     return bignum_bitcount(rsa->modulus);
970 }
971
972 static void oaep_mask(const struct ssh_hash *h, void *seed, int seedlen,
973                       void *vdata, int datalen)
974 {
975     unsigned char *data = (unsigned char *)vdata;
976     unsigned count = 0;
977
978     while (datalen > 0) {
979         int i, max = (datalen > h->hlen ? h->hlen : datalen);
980         void *s;
981         unsigned char counter[4], hash[SSH2_KEX_MAX_HASH_LEN];
982
983         assert(h->hlen <= SSH2_KEX_MAX_HASH_LEN);
984         PUT_32BIT(counter, count);
985         s = h->init();
986         h->bytes(s, seed, seedlen);
987         h->bytes(s, counter, 4);
988         h->final(s, hash);
989         count++;
990
991         for (i = 0; i < max; i++)
992             data[i] ^= hash[i];
993
994         data += max;
995         datalen -= max;
996     }
997 }
998
999 void ssh_rsakex_encrypt(const struct ssh_hash *h, unsigned char *in, int inlen,
1000                         unsigned char *out, int outlen,
1001                         void *key)
1002 {
1003     Bignum b1, b2;
1004     struct RSAKey *rsa = (struct RSAKey *) key;
1005     int k, i;
1006     char *p;
1007     const int HLEN = h->hlen;
1008
1009     /*
1010      * Here we encrypt using RSAES-OAEP. Essentially this means:
1011      * 
1012      *  - we have a SHA-based `mask generation function' which
1013      *    creates a pseudo-random stream of mask data
1014      *    deterministically from an input chunk of data.
1015      * 
1016      *  - we have a random chunk of data called a seed.
1017      * 
1018      *  - we use the seed to generate a mask which we XOR with our
1019      *    plaintext.
1020      * 
1021      *  - then we use _the masked plaintext_ to generate a mask
1022      *    which we XOR with the seed.
1023      * 
1024      *  - then we concatenate the masked seed and the masked
1025      *    plaintext, and RSA-encrypt that lot.
1026      * 
1027      * The result is that the data input to the encryption function
1028      * is random-looking and (hopefully) contains no exploitable
1029      * structure such as PKCS1-v1_5 does.
1030      * 
1031      * For a precise specification, see RFC 3447, section 7.1.1.
1032      * Some of the variable names below are derived from that, so
1033      * it'd probably help to read it anyway.
1034      */
1035
1036     /* k denotes the length in octets of the RSA modulus. */
1037     k = (7 + bignum_bitcount(rsa->modulus)) / 8;
1038
1039     /* The length of the input data must be at most k - 2hLen - 2. */
1040     assert(inlen > 0 && inlen <= k - 2*HLEN - 2);
1041
1042     /* The length of the output data wants to be precisely k. */
1043     assert(outlen == k);
1044
1045     /*
1046      * Now perform EME-OAEP encoding. First set up all the unmasked
1047      * output data.
1048      */
1049     /* Leading byte zero. */
1050     out[0] = 0;
1051     /* At position 1, the seed: HLEN bytes of random data. */
1052     for (i = 0; i < HLEN; i++)
1053         out[i + 1] = random_byte();
1054     /* At position 1+HLEN, the data block DB, consisting of: */
1055     /* The hash of the label (we only support an empty label here) */
1056     h->final(h->init(), out + HLEN + 1);
1057     /* A bunch of zero octets */
1058     memset(out + 2*HLEN + 1, 0, outlen - (2*HLEN + 1));
1059     /* A single 1 octet, followed by the input message data. */
1060     out[outlen - inlen - 1] = 1;
1061     memcpy(out + outlen - inlen, in, inlen);
1062
1063     /*
1064      * Now use the seed data to mask the block DB.
1065      */
1066     oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
1067
1068     /*
1069      * And now use the masked DB to mask the seed itself.
1070      */
1071     oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
1072
1073     /*
1074      * Now `out' contains precisely the data we want to
1075      * RSA-encrypt.
1076      */
1077     b1 = bignum_from_bytes(out, outlen);
1078     b2 = modpow(b1, rsa->exponent, rsa->modulus);
1079     p = (char *)out;
1080     for (i = outlen; i--;) {
1081         *p++ = bignum_byte(b2, i);
1082     }
1083     freebn(b1);
1084     freebn(b2);
1085
1086     /*
1087      * And we're done.
1088      */
1089 }
1090
1091 static const struct ssh_kex ssh_rsa_kex_sha1 = {
1092     "rsa1024-sha1", NULL, KEXTYPE_RSA, NULL, NULL, 0, 0, &ssh_sha1
1093 };
1094
1095 static const struct ssh_kex ssh_rsa_kex_sha256 = {
1096     "rsa2048-sha256", NULL, KEXTYPE_RSA, NULL, NULL, 0, 0, &ssh_sha256
1097 };
1098
1099 static const struct ssh_kex *const rsa_kex_list[] = {
1100     &ssh_rsa_kex_sha256,
1101     &ssh_rsa_kex_sha1
1102 };
1103
1104 const struct ssh_kexes ssh_rsa_kex = {
1105     sizeof(rsa_kex_list) / sizeof(*rsa_kex_list),
1106     rsa_kex_list
1107 };