]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshrsa.c
first pass
[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(const unsigned char *data, int len, struct RSAKey *result,
14             const unsigned char **keystr, int order)
15 {
16     const 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(const 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(const char **data, int *datalen,
537                       const char **p, int *length)
538 {
539     *p = NULL;
540     if (*datalen < 4)
541         return;
542     *length = toint(GET_32BIT(*data));
543     if (*length < 0)
544         return;
545     *datalen -= 4;
546     *data += 4;
547     if (*datalen < *length)
548         return;
549     *p = *data;
550     *data += *length;
551     *datalen -= *length;
552 }
553 static Bignum getmp(const char **data, int *datalen)
554 {
555     const char *p;
556     int length;
557     Bignum b;
558
559     getstring(data, datalen, &p, &length);
560     if (!p)
561         return NULL;
562     b = bignum_from_bytes((unsigned char *)p, length);
563     return b;
564 }
565
566 static void rsa2_freekey(void *key);   /* forward reference */
567
568 static void *rsa2_newkey(const struct ssh_signkey *self,
569                          const char *data, int len)
570 {
571     const char *p;
572     int slen;
573     struct RSAKey *rsa;
574
575     rsa = snew(struct RSAKey);
576     getstring(&data, &len, &p, &slen);
577
578     if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
579         sfree(rsa);
580         return NULL;
581     }
582     rsa->exponent = getmp(&data, &len);
583     rsa->modulus = getmp(&data, &len);
584     rsa->private_exponent = NULL;
585     rsa->p = rsa->q = rsa->iqmp = NULL;
586     rsa->comment = NULL;
587
588     if (!rsa->exponent || !rsa->modulus) {
589         rsa2_freekey(rsa);
590         return NULL;
591     }
592
593     return rsa;
594 }
595
596 static void rsa2_freekey(void *key)
597 {
598     struct RSAKey *rsa = (struct RSAKey *) key;
599     freersakey(rsa);
600     sfree(rsa);
601 }
602
603 static char *rsa2_fmtkey(void *key)
604 {
605     struct RSAKey *rsa = (struct RSAKey *) key;
606     char *p;
607     int len;
608
609     len = rsastr_len(rsa);
610     p = snewn(len, char);
611     rsastr_fmt(p, rsa);
612     return p;
613 }
614
615 static unsigned char *rsa2_public_blob(void *key, int *len)
616 {
617     struct RSAKey *rsa = (struct RSAKey *) key;
618     int elen, mlen, bloblen;
619     int i;
620     unsigned char *blob, *p;
621
622     elen = (bignum_bitcount(rsa->exponent) + 8) / 8;
623     mlen = (bignum_bitcount(rsa->modulus) + 8) / 8;
624
625     /*
626      * string "ssh-rsa", mpint exp, mpint mod. Total 19+elen+mlen.
627      * (three length fields, 12+7=19).
628      */
629     bloblen = 19 + elen + mlen;
630     blob = snewn(bloblen, unsigned char);
631     p = blob;
632     PUT_32BIT(p, 7);
633     p += 4;
634     memcpy(p, "ssh-rsa", 7);
635     p += 7;
636     PUT_32BIT(p, elen);
637     p += 4;
638     for (i = elen; i--;)
639         *p++ = bignum_byte(rsa->exponent, i);
640     PUT_32BIT(p, mlen);
641     p += 4;
642     for (i = mlen; i--;)
643         *p++ = bignum_byte(rsa->modulus, i);
644     assert(p == blob + bloblen);
645     *len = bloblen;
646     return blob;
647 }
648
649 static unsigned char *rsa2_private_blob(void *key, int *len)
650 {
651     struct RSAKey *rsa = (struct RSAKey *) key;
652     int dlen, plen, qlen, ulen, bloblen;
653     int i;
654     unsigned char *blob, *p;
655
656     dlen = (bignum_bitcount(rsa->private_exponent) + 8) / 8;
657     plen = (bignum_bitcount(rsa->p) + 8) / 8;
658     qlen = (bignum_bitcount(rsa->q) + 8) / 8;
659     ulen = (bignum_bitcount(rsa->iqmp) + 8) / 8;
660
661     /*
662      * mpint private_exp, mpint p, mpint q, mpint iqmp. Total 16 +
663      * sum of lengths.
664      */
665     bloblen = 16 + dlen + plen + qlen + ulen;
666     blob = snewn(bloblen, unsigned char);
667     p = blob;
668     PUT_32BIT(p, dlen);
669     p += 4;
670     for (i = dlen; i--;)
671         *p++ = bignum_byte(rsa->private_exponent, i);
672     PUT_32BIT(p, plen);
673     p += 4;
674     for (i = plen; i--;)
675         *p++ = bignum_byte(rsa->p, i);
676     PUT_32BIT(p, qlen);
677     p += 4;
678     for (i = qlen; i--;)
679         *p++ = bignum_byte(rsa->q, i);
680     PUT_32BIT(p, ulen);
681     p += 4;
682     for (i = ulen; i--;)
683         *p++ = bignum_byte(rsa->iqmp, i);
684     assert(p == blob + bloblen);
685     *len = bloblen;
686     return blob;
687 }
688
689 static void *rsa2_createkey(const struct ssh_signkey *self,
690                             const unsigned char *pub_blob, int pub_len,
691                             const unsigned char *priv_blob, int priv_len)
692 {
693     struct RSAKey *rsa;
694     const char *pb = (const char *) priv_blob;
695
696     rsa = rsa2_newkey(self, (char *) pub_blob, pub_len);
697     rsa->private_exponent = getmp(&pb, &priv_len);
698     rsa->p = getmp(&pb, &priv_len);
699     rsa->q = getmp(&pb, &priv_len);
700     rsa->iqmp = getmp(&pb, &priv_len);
701
702     if (!rsa_verify(rsa)) {
703         rsa2_freekey(rsa);
704         return NULL;
705     }
706
707     return rsa;
708 }
709
710 static void *rsa2_openssh_createkey(const struct ssh_signkey *self,
711                                     const unsigned char **blob, int *len)
712 {
713     const char **b = (const char **) blob;
714     struct RSAKey *rsa;
715
716     rsa = snew(struct RSAKey);
717     rsa->comment = NULL;
718
719     rsa->modulus = getmp(b, len);
720     rsa->exponent = getmp(b, len);
721     rsa->private_exponent = getmp(b, len);
722     rsa->iqmp = getmp(b, len);
723     rsa->p = getmp(b, len);
724     rsa->q = getmp(b, len);
725
726     if (!rsa->modulus || !rsa->exponent || !rsa->private_exponent ||
727         !rsa->iqmp || !rsa->p || !rsa->q) {
728         rsa2_freekey(rsa);
729         return NULL;
730     }
731
732     if (!rsa_verify(rsa)) {
733         rsa2_freekey(rsa);
734         return NULL;
735     }
736
737     return rsa;
738 }
739
740 static int rsa2_openssh_fmtkey(void *key, unsigned char *blob, int len)
741 {
742     struct RSAKey *rsa = (struct RSAKey *) key;
743     int bloblen, i;
744
745     bloblen =
746         ssh2_bignum_length(rsa->modulus) +
747         ssh2_bignum_length(rsa->exponent) +
748         ssh2_bignum_length(rsa->private_exponent) +
749         ssh2_bignum_length(rsa->iqmp) +
750         ssh2_bignum_length(rsa->p) + ssh2_bignum_length(rsa->q);
751
752     if (bloblen > len)
753         return bloblen;
754
755     bloblen = 0;
756 #define ENC(x) \
757     PUT_32BIT(blob+bloblen, ssh2_bignum_length((x))-4); bloblen += 4; \
758     for (i = ssh2_bignum_length((x))-4; i-- ;) blob[bloblen++]=bignum_byte((x),i);
759     ENC(rsa->modulus);
760     ENC(rsa->exponent);
761     ENC(rsa->private_exponent);
762     ENC(rsa->iqmp);
763     ENC(rsa->p);
764     ENC(rsa->q);
765
766     return bloblen;
767 }
768
769 static int rsa2_pubkey_bits(const struct ssh_signkey *self,
770                             const void *blob, int len)
771 {
772     struct RSAKey *rsa;
773     int ret;
774
775     rsa = rsa2_newkey(self, (const char *) blob, len);
776     if (!rsa)
777         return -1;
778     ret = bignum_bitcount(rsa->modulus);
779     rsa2_freekey(rsa);
780
781     return ret;
782 }
783
784 /*
785  * This is the magic ASN.1/DER prefix that goes in the decoded
786  * signature, between the string of FFs and the actual SHA hash
787  * value. The meaning of it is:
788  * 
789  * 00 -- this marks the end of the FFs; not part of the ASN.1 bit itself
790  * 
791  * 30 21 -- a constructed SEQUENCE of length 0x21
792  *    30 09 -- a constructed sub-SEQUENCE of length 9
793  *       06 05 -- an object identifier, length 5
794  *          2B 0E 03 02 1A -- object id { 1 3 14 3 2 26 }
795  *                            (the 1,3 comes from 0x2B = 43 = 40*1+3)
796  *       05 00 -- NULL
797  *    04 14 -- a primitive OCTET STRING of length 0x14
798  *       [0x14 bytes of hash data follows]
799  * 
800  * The object id in the middle there is listed as `id-sha1' in
801  * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1d2.asn (the
802  * ASN module for PKCS #1) and its expanded form is as follows:
803  * 
804  * id-sha1                OBJECT IDENTIFIER ::= {
805  *    iso(1) identified-organization(3) oiw(14) secsig(3)
806  *    algorithms(2) 26 }
807  */
808 static const unsigned char asn1_weird_stuff[] = {
809     0x00, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
810     0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
811 };
812
813 #define ASN1_LEN ( (int) sizeof(asn1_weird_stuff) )
814
815 static int rsa2_verifysig(void *key, const char *sig, int siglen,
816                           const char *data, int datalen)
817 {
818     struct RSAKey *rsa = (struct RSAKey *) key;
819     Bignum in, out;
820     const char *p;
821     int slen;
822     int bytes, i, j, ret;
823     unsigned char hash[20];
824
825     getstring(&sig, &siglen, &p, &slen);
826     if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
827         return 0;
828     }
829     in = getmp(&sig, &siglen);
830     if (!in)
831         return 0;
832     out = modpow(in, rsa->exponent, rsa->modulus);
833     freebn(in);
834
835     ret = 1;
836
837     bytes = (bignum_bitcount(rsa->modulus)+7) / 8;
838     /* Top (partial) byte should be zero. */
839     if (bignum_byte(out, bytes - 1) != 0)
840         ret = 0;
841     /* First whole byte should be 1. */
842     if (bignum_byte(out, bytes - 2) != 1)
843         ret = 0;
844     /* Most of the rest should be FF. */
845     for (i = bytes - 3; i >= 20 + ASN1_LEN; i--) {
846         if (bignum_byte(out, i) != 0xFF)
847             ret = 0;
848     }
849     /* Then we expect to see the asn1_weird_stuff. */
850     for (i = 20 + ASN1_LEN - 1, j = 0; i >= 20; i--, j++) {
851         if (bignum_byte(out, i) != asn1_weird_stuff[j])
852             ret = 0;
853     }
854     /* Finally, we expect to see the SHA-1 hash of the signed data. */
855     SHA_Simple(data, datalen, hash);
856     for (i = 19, j = 0; i >= 0; i--, j++) {
857         if (bignum_byte(out, i) != hash[j])
858             ret = 0;
859     }
860     freebn(out);
861
862     return ret;
863 }
864
865 static unsigned char *rsa2_sign(void *key, const char *data, int datalen,
866                                 int *siglen)
867 {
868     struct RSAKey *rsa = (struct RSAKey *) key;
869     unsigned char *bytes;
870     int nbytes;
871     unsigned char hash[20];
872     Bignum in, out;
873     int i, j;
874
875     SHA_Simple(data, datalen, hash);
876
877     nbytes = (bignum_bitcount(rsa->modulus) - 1) / 8;
878     assert(1 <= nbytes - 20 - ASN1_LEN);
879     bytes = snewn(nbytes, unsigned char);
880
881     bytes[0] = 1;
882     for (i = 1; i < nbytes - 20 - ASN1_LEN; i++)
883         bytes[i] = 0xFF;
884     for (i = nbytes - 20 - ASN1_LEN, j = 0; i < nbytes - 20; i++, j++)
885         bytes[i] = asn1_weird_stuff[j];
886     for (i = nbytes - 20, j = 0; i < nbytes; i++, j++)
887         bytes[i] = hash[j];
888
889     in = bignum_from_bytes(bytes, nbytes);
890     sfree(bytes);
891
892     out = rsa_privkey_op(in, rsa);
893     freebn(in);
894
895     nbytes = (bignum_bitcount(out) + 7) / 8;
896     bytes = snewn(4 + 7 + 4 + nbytes, unsigned char);
897     PUT_32BIT(bytes, 7);
898     memcpy(bytes + 4, "ssh-rsa", 7);
899     PUT_32BIT(bytes + 4 + 7, nbytes);
900     for (i = 0; i < nbytes; i++)
901         bytes[4 + 7 + 4 + i] = bignum_byte(out, nbytes - 1 - i);
902     freebn(out);
903
904     *siglen = 4 + 7 + 4 + nbytes;
905     return bytes;
906 }
907
908 const struct ssh_signkey ssh_rsa = {
909     rsa2_newkey,
910     rsa2_freekey,
911     rsa2_fmtkey,
912     rsa2_public_blob,
913     rsa2_private_blob,
914     rsa2_createkey,
915     rsa2_openssh_createkey,
916     rsa2_openssh_fmtkey,
917     6 /* n,e,d,iqmp,q,p */,
918     rsa2_pubkey_bits,
919     rsa2_verifysig,
920     rsa2_sign,
921     "ssh-rsa",
922     "rsa2",
923     NULL,
924 };
925
926 void *ssh_rsakex_newkey(char *data, int len)
927 {
928     return rsa2_newkey(&ssh_rsa, data, len);
929 }
930
931 void ssh_rsakex_freekey(void *key)
932 {
933     rsa2_freekey(key);
934 }
935
936 int ssh_rsakex_klen(void *key)
937 {
938     struct RSAKey *rsa = (struct RSAKey *) key;
939
940     return bignum_bitcount(rsa->modulus);
941 }
942
943 static void oaep_mask(const struct ssh_hash *h, void *seed, int seedlen,
944                       void *vdata, int datalen)
945 {
946     unsigned char *data = (unsigned char *)vdata;
947     unsigned count = 0;
948
949     while (datalen > 0) {
950         int i, max = (datalen > h->hlen ? h->hlen : datalen);
951         void *s;
952         unsigned char counter[4], hash[SSH2_KEX_MAX_HASH_LEN];
953
954         assert(h->hlen <= SSH2_KEX_MAX_HASH_LEN);
955         PUT_32BIT(counter, count);
956         s = h->init();
957         h->bytes(s, seed, seedlen);
958         h->bytes(s, counter, 4);
959         h->final(s, hash);
960         count++;
961
962         for (i = 0; i < max; i++)
963             data[i] ^= hash[i];
964
965         data += max;
966         datalen -= max;
967     }
968 }
969
970 void ssh_rsakex_encrypt(const struct ssh_hash *h, unsigned char *in, int inlen,
971                         unsigned char *out, int outlen,
972                         void *key)
973 {
974     Bignum b1, b2;
975     struct RSAKey *rsa = (struct RSAKey *) key;
976     int k, i;
977     char *p;
978     const int HLEN = h->hlen;
979
980     /*
981      * Here we encrypt using RSAES-OAEP. Essentially this means:
982      * 
983      *  - we have a SHA-based `mask generation function' which
984      *    creates a pseudo-random stream of mask data
985      *    deterministically from an input chunk of data.
986      * 
987      *  - we have a random chunk of data called a seed.
988      * 
989      *  - we use the seed to generate a mask which we XOR with our
990      *    plaintext.
991      * 
992      *  - then we use _the masked plaintext_ to generate a mask
993      *    which we XOR with the seed.
994      * 
995      *  - then we concatenate the masked seed and the masked
996      *    plaintext, and RSA-encrypt that lot.
997      * 
998      * The result is that the data input to the encryption function
999      * is random-looking and (hopefully) contains no exploitable
1000      * structure such as PKCS1-v1_5 does.
1001      * 
1002      * For a precise specification, see RFC 3447, section 7.1.1.
1003      * Some of the variable names below are derived from that, so
1004      * it'd probably help to read it anyway.
1005      */
1006
1007     /* k denotes the length in octets of the RSA modulus. */
1008     k = (7 + bignum_bitcount(rsa->modulus)) / 8;
1009
1010     /* The length of the input data must be at most k - 2hLen - 2. */
1011     assert(inlen > 0 && inlen <= k - 2*HLEN - 2);
1012
1013     /* The length of the output data wants to be precisely k. */
1014     assert(outlen == k);
1015
1016     /*
1017      * Now perform EME-OAEP encoding. First set up all the unmasked
1018      * output data.
1019      */
1020     /* Leading byte zero. */
1021     out[0] = 0;
1022     /* At position 1, the seed: HLEN bytes of random data. */
1023     for (i = 0; i < HLEN; i++)
1024         out[i + 1] = random_byte();
1025     /* At position 1+HLEN, the data block DB, consisting of: */
1026     /* The hash of the label (we only support an empty label here) */
1027     h->final(h->init(), out + HLEN + 1);
1028     /* A bunch of zero octets */
1029     memset(out + 2*HLEN + 1, 0, outlen - (2*HLEN + 1));
1030     /* A single 1 octet, followed by the input message data. */
1031     out[outlen - inlen - 1] = 1;
1032     memcpy(out + outlen - inlen, in, inlen);
1033
1034     /*
1035      * Now use the seed data to mask the block DB.
1036      */
1037     oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
1038
1039     /*
1040      * And now use the masked DB to mask the seed itself.
1041      */
1042     oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
1043
1044     /*
1045      * Now `out' contains precisely the data we want to
1046      * RSA-encrypt.
1047      */
1048     b1 = bignum_from_bytes(out, outlen);
1049     b2 = modpow(b1, rsa->exponent, rsa->modulus);
1050     p = (char *)out;
1051     for (i = outlen; i--;) {
1052         *p++ = bignum_byte(b2, i);
1053     }
1054     freebn(b1);
1055     freebn(b2);
1056
1057     /*
1058      * And we're done.
1059      */
1060 }
1061
1062 static const struct ssh_kex ssh_rsa_kex_sha1 = {
1063     "rsa1024-sha1", NULL, KEXTYPE_RSA, &ssh_sha1, NULL,
1064 };
1065
1066 static const struct ssh_kex ssh_rsa_kex_sha256 = {
1067     "rsa2048-sha256", NULL, KEXTYPE_RSA, &ssh_sha256, NULL,
1068 };
1069
1070 static const struct ssh_kex *const rsa_kex_list[] = {
1071     &ssh_rsa_kex_sha256,
1072     &ssh_rsa_kex_sha1
1073 };
1074
1075 const struct ssh_kexes ssh_rsa_kex = {
1076     sizeof(rsa_kex_list) / sizeof(*rsa_kex_list),
1077     rsa_kex_list
1078 };