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