]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshrsa.c
Add a missing bn_restore_invariant in RSA blinding code.
[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     ret = bignum_bitcount(rsa->modulus);
772     rsa2_freekey(rsa);
773
774     return ret;
775 }
776
777 static char *rsa2_fingerprint(void *key)
778 {
779     struct RSAKey *rsa = (struct RSAKey *) key;
780     struct MD5Context md5c;
781     unsigned char digest[16], lenbuf[4];
782     char buffer[16 * 3 + 40];
783     char *ret;
784     int numlen, i;
785
786     MD5Init(&md5c);
787     MD5Update(&md5c, (unsigned char *)"\0\0\0\7ssh-rsa", 11);
788
789 #define ADD_BIGNUM(bignum) \
790     numlen = (bignum_bitcount(bignum)+8)/8; \
791     PUT_32BIT(lenbuf, numlen); MD5Update(&md5c, lenbuf, 4); \
792     for (i = numlen; i-- ;) { \
793         unsigned char c = bignum_byte(bignum, i); \
794         MD5Update(&md5c, &c, 1); \
795     }
796     ADD_BIGNUM(rsa->exponent);
797     ADD_BIGNUM(rsa->modulus);
798 #undef ADD_BIGNUM
799
800     MD5Final(digest, &md5c);
801
802     sprintf(buffer, "ssh-rsa %d ", bignum_bitcount(rsa->modulus));
803     for (i = 0; i < 16; i++)
804         sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
805                 digest[i]);
806     ret = snewn(strlen(buffer) + 1, char);
807     if (ret)
808         strcpy(ret, buffer);
809     return ret;
810 }
811
812 /*
813  * This is the magic ASN.1/DER prefix that goes in the decoded
814  * signature, between the string of FFs and the actual SHA hash
815  * value. The meaning of it is:
816  * 
817  * 00 -- this marks the end of the FFs; not part of the ASN.1 bit itself
818  * 
819  * 30 21 -- a constructed SEQUENCE of length 0x21
820  *    30 09 -- a constructed sub-SEQUENCE of length 9
821  *       06 05 -- an object identifier, length 5
822  *          2B 0E 03 02 1A -- object id { 1 3 14 3 2 26 }
823  *                            (the 1,3 comes from 0x2B = 43 = 40*1+3)
824  *       05 00 -- NULL
825  *    04 14 -- a primitive OCTET STRING of length 0x14
826  *       [0x14 bytes of hash data follows]
827  * 
828  * The object id in the middle there is listed as `id-sha1' in
829  * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1d2.asn (the
830  * ASN module for PKCS #1) and its expanded form is as follows:
831  * 
832  * id-sha1                OBJECT IDENTIFIER ::= {
833  *    iso(1) identified-organization(3) oiw(14) secsig(3)
834  *    algorithms(2) 26 }
835  */
836 static const unsigned char asn1_weird_stuff[] = {
837     0x00, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
838     0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
839 };
840
841 #define ASN1_LEN ( (int) sizeof(asn1_weird_stuff) )
842
843 static int rsa2_verifysig(void *key, char *sig, int siglen,
844                           char *data, int datalen)
845 {
846     struct RSAKey *rsa = (struct RSAKey *) key;
847     Bignum in, out;
848     char *p;
849     int slen;
850     int bytes, i, j, ret;
851     unsigned char hash[20];
852
853     getstring(&sig, &siglen, &p, &slen);
854     if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
855         return 0;
856     }
857     in = getmp(&sig, &siglen);
858     if (!in)
859         return 0;
860     out = modpow(in, rsa->exponent, rsa->modulus);
861     freebn(in);
862
863     ret = 1;
864
865     bytes = (bignum_bitcount(rsa->modulus)+7) / 8;
866     /* Top (partial) byte should be zero. */
867     if (bignum_byte(out, bytes - 1) != 0)
868         ret = 0;
869     /* First whole byte should be 1. */
870     if (bignum_byte(out, bytes - 2) != 1)
871         ret = 0;
872     /* Most of the rest should be FF. */
873     for (i = bytes - 3; i >= 20 + ASN1_LEN; i--) {
874         if (bignum_byte(out, i) != 0xFF)
875             ret = 0;
876     }
877     /* Then we expect to see the asn1_weird_stuff. */
878     for (i = 20 + ASN1_LEN - 1, j = 0; i >= 20; i--, j++) {
879         if (bignum_byte(out, i) != asn1_weird_stuff[j])
880             ret = 0;
881     }
882     /* Finally, we expect to see the SHA-1 hash of the signed data. */
883     SHA_Simple(data, datalen, hash);
884     for (i = 19, j = 0; i >= 0; i--, j++) {
885         if (bignum_byte(out, i) != hash[j])
886             ret = 0;
887     }
888     freebn(out);
889
890     return ret;
891 }
892
893 static unsigned char *rsa2_sign(void *key, char *data, int datalen,
894                                 int *siglen)
895 {
896     struct RSAKey *rsa = (struct RSAKey *) key;
897     unsigned char *bytes;
898     int nbytes;
899     unsigned char hash[20];
900     Bignum in, out;
901     int i, j;
902
903     SHA_Simple(data, datalen, hash);
904
905     nbytes = (bignum_bitcount(rsa->modulus) - 1) / 8;
906     assert(1 <= nbytes - 20 - ASN1_LEN);
907     bytes = snewn(nbytes, unsigned char);
908
909     bytes[0] = 1;
910     for (i = 1; i < nbytes - 20 - ASN1_LEN; i++)
911         bytes[i] = 0xFF;
912     for (i = nbytes - 20 - ASN1_LEN, j = 0; i < nbytes - 20; i++, j++)
913         bytes[i] = asn1_weird_stuff[j];
914     for (i = nbytes - 20, j = 0; i < nbytes; i++, j++)
915         bytes[i] = hash[j];
916
917     in = bignum_from_bytes(bytes, nbytes);
918     sfree(bytes);
919
920     out = rsa_privkey_op(in, rsa);
921     freebn(in);
922
923     nbytes = (bignum_bitcount(out) + 7) / 8;
924     bytes = snewn(4 + 7 + 4 + nbytes, unsigned char);
925     PUT_32BIT(bytes, 7);
926     memcpy(bytes + 4, "ssh-rsa", 7);
927     PUT_32BIT(bytes + 4 + 7, nbytes);
928     for (i = 0; i < nbytes; i++)
929         bytes[4 + 7 + 4 + i] = bignum_byte(out, nbytes - 1 - i);
930     freebn(out);
931
932     *siglen = 4 + 7 + 4 + nbytes;
933     return bytes;
934 }
935
936 const struct ssh_signkey ssh_rsa = {
937     rsa2_newkey,
938     rsa2_freekey,
939     rsa2_fmtkey,
940     rsa2_public_blob,
941     rsa2_private_blob,
942     rsa2_createkey,
943     rsa2_openssh_createkey,
944     rsa2_openssh_fmtkey,
945     rsa2_pubkey_bits,
946     rsa2_fingerprint,
947     rsa2_verifysig,
948     rsa2_sign,
949     "ssh-rsa",
950     "rsa2"
951 };
952
953 void *ssh_rsakex_newkey(char *data, int len)
954 {
955     return rsa2_newkey(data, len);
956 }
957
958 void ssh_rsakex_freekey(void *key)
959 {
960     rsa2_freekey(key);
961 }
962
963 int ssh_rsakex_klen(void *key)
964 {
965     struct RSAKey *rsa = (struct RSAKey *) key;
966
967     return bignum_bitcount(rsa->modulus);
968 }
969
970 static void oaep_mask(const struct ssh_hash *h, void *seed, int seedlen,
971                       void *vdata, int datalen)
972 {
973     unsigned char *data = (unsigned char *)vdata;
974     unsigned count = 0;
975
976     while (datalen > 0) {
977         int i, max = (datalen > h->hlen ? h->hlen : datalen);
978         void *s;
979         unsigned char counter[4], hash[SSH2_KEX_MAX_HASH_LEN];
980
981         assert(h->hlen <= SSH2_KEX_MAX_HASH_LEN);
982         PUT_32BIT(counter, count);
983         s = h->init();
984         h->bytes(s, seed, seedlen);
985         h->bytes(s, counter, 4);
986         h->final(s, hash);
987         count++;
988
989         for (i = 0; i < max; i++)
990             data[i] ^= hash[i];
991
992         data += max;
993         datalen -= max;
994     }
995 }
996
997 void ssh_rsakex_encrypt(const struct ssh_hash *h, unsigned char *in, int inlen,
998                         unsigned char *out, int outlen,
999                         void *key)
1000 {
1001     Bignum b1, b2;
1002     struct RSAKey *rsa = (struct RSAKey *) key;
1003     int k, i;
1004     char *p;
1005     const int HLEN = h->hlen;
1006
1007     /*
1008      * Here we encrypt using RSAES-OAEP. Essentially this means:
1009      * 
1010      *  - we have a SHA-based `mask generation function' which
1011      *    creates a pseudo-random stream of mask data
1012      *    deterministically from an input chunk of data.
1013      * 
1014      *  - we have a random chunk of data called a seed.
1015      * 
1016      *  - we use the seed to generate a mask which we XOR with our
1017      *    plaintext.
1018      * 
1019      *  - then we use _the masked plaintext_ to generate a mask
1020      *    which we XOR with the seed.
1021      * 
1022      *  - then we concatenate the masked seed and the masked
1023      *    plaintext, and RSA-encrypt that lot.
1024      * 
1025      * The result is that the data input to the encryption function
1026      * is random-looking and (hopefully) contains no exploitable
1027      * structure such as PKCS1-v1_5 does.
1028      * 
1029      * For a precise specification, see RFC 3447, section 7.1.1.
1030      * Some of the variable names below are derived from that, so
1031      * it'd probably help to read it anyway.
1032      */
1033
1034     /* k denotes the length in octets of the RSA modulus. */
1035     k = (7 + bignum_bitcount(rsa->modulus)) / 8;
1036
1037     /* The length of the input data must be at most k - 2hLen - 2. */
1038     assert(inlen > 0 && inlen <= k - 2*HLEN - 2);
1039
1040     /* The length of the output data wants to be precisely k. */
1041     assert(outlen == k);
1042
1043     /*
1044      * Now perform EME-OAEP encoding. First set up all the unmasked
1045      * output data.
1046      */
1047     /* Leading byte zero. */
1048     out[0] = 0;
1049     /* At position 1, the seed: HLEN bytes of random data. */
1050     for (i = 0; i < HLEN; i++)
1051         out[i + 1] = random_byte();
1052     /* At position 1+HLEN, the data block DB, consisting of: */
1053     /* The hash of the label (we only support an empty label here) */
1054     h->final(h->init(), out + HLEN + 1);
1055     /* A bunch of zero octets */
1056     memset(out + 2*HLEN + 1, 0, outlen - (2*HLEN + 1));
1057     /* A single 1 octet, followed by the input message data. */
1058     out[outlen - inlen - 1] = 1;
1059     memcpy(out + outlen - inlen, in, inlen);
1060
1061     /*
1062      * Now use the seed data to mask the block DB.
1063      */
1064     oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
1065
1066     /*
1067      * And now use the masked DB to mask the seed itself.
1068      */
1069     oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
1070
1071     /*
1072      * Now `out' contains precisely the data we want to
1073      * RSA-encrypt.
1074      */
1075     b1 = bignum_from_bytes(out, outlen);
1076     b2 = modpow(b1, rsa->exponent, rsa->modulus);
1077     p = (char *)out;
1078     for (i = outlen; i--;) {
1079         *p++ = bignum_byte(b2, i);
1080     }
1081     freebn(b1);
1082     freebn(b2);
1083
1084     /*
1085      * And we're done.
1086      */
1087 }
1088
1089 static const struct ssh_kex ssh_rsa_kex_sha1 = {
1090     "rsa1024-sha1", NULL, KEXTYPE_RSA, NULL, NULL, 0, 0, &ssh_sha1
1091 };
1092
1093 static const struct ssh_kex ssh_rsa_kex_sha256 = {
1094     "rsa2048-sha256", NULL, KEXTYPE_RSA, NULL, NULL, 0, 0, &ssh_sha256
1095 };
1096
1097 static const struct ssh_kex *const rsa_kex_list[] = {
1098     &ssh_rsa_kex_sha256,
1099     &ssh_rsa_kex_sha1
1100 };
1101
1102 const struct ssh_kexes ssh_rsa_kex = {
1103     sizeof(rsa_kex_list) / sizeof(*rsa_kex_list),
1104     rsa_kex_list
1105 };