]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshrsa.c
Fix a couple of signedness compiler warnings, presumably due to me
[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     if (bignum_cmp(key->p, key->q) <= 0)
357         return 0;
358
359     /*
360      * Ensure iqmp * q is congruent to 1, modulo p.
361      */
362     n = modmul(key->iqmp, key->q, key->p);
363     cmp = bignum_cmp(n, One);
364     sfree(n);
365     if (cmp != 0)
366         return 0;
367
368     return 1;
369 }
370
371 /* Public key blob as used by Pageant: exponent before modulus. */
372 unsigned char *rsa_public_blob(struct RSAKey *key, int *len)
373 {
374     int length, pos;
375     unsigned char *ret;
376
377     length = (ssh1_bignum_length(key->modulus) +
378               ssh1_bignum_length(key->exponent) + 4);
379     ret = snewn(length, unsigned char);
380
381     PUT_32BIT(ret, bignum_bitcount(key->modulus));
382     pos = 4;
383     pos += ssh1_write_bignum(ret + pos, key->exponent);
384     pos += ssh1_write_bignum(ret + pos, key->modulus);
385
386     *len = length;
387     return ret;
388 }
389
390 /* Given a public blob, determine its length. */
391 int rsa_public_blob_len(void *data, int maxlen)
392 {
393     unsigned char *p = (unsigned char *)data;
394     int n;
395
396     if (maxlen < 4)
397         return -1;
398     p += 4;                            /* length word */
399     maxlen -= 4;
400
401     n = ssh1_read_bignum(p, maxlen, NULL);    /* exponent */
402     if (n < 0)
403         return -1;
404     p += n;
405
406     n = ssh1_read_bignum(p, maxlen, NULL);    /* modulus */
407     if (n < 0)
408         return -1;
409     p += n;
410
411     return p - (unsigned char *)data;
412 }
413
414 void freersakey(struct RSAKey *key)
415 {
416     if (key->modulus)
417         freebn(key->modulus);
418     if (key->exponent)
419         freebn(key->exponent);
420     if (key->private_exponent)
421         freebn(key->private_exponent);
422     if (key->comment)
423         sfree(key->comment);
424 }
425
426 /* ----------------------------------------------------------------------
427  * Implementation of the ssh-rsa signing key type. 
428  */
429
430 static void getstring(char **data, int *datalen, char **p, int *length)
431 {
432     *p = NULL;
433     if (*datalen < 4)
434         return;
435     *length = GET_32BIT(*data);
436     *datalen -= 4;
437     *data += 4;
438     if (*datalen < *length)
439         return;
440     *p = *data;
441     *data += *length;
442     *datalen -= *length;
443 }
444 static Bignum getmp(char **data, int *datalen)
445 {
446     char *p;
447     int length;
448     Bignum b;
449
450     getstring(data, datalen, &p, &length);
451     if (!p)
452         return NULL;
453     b = bignum_from_bytes((unsigned char *)p, length);
454     return b;
455 }
456
457 static void *rsa2_newkey(char *data, int len)
458 {
459     char *p;
460     int slen;
461     struct RSAKey *rsa;
462
463     rsa = snew(struct RSAKey);
464     if (!rsa)
465         return NULL;
466     getstring(&data, &len, &p, &slen);
467
468     if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
469         sfree(rsa);
470         return NULL;
471     }
472     rsa->exponent = getmp(&data, &len);
473     rsa->modulus = getmp(&data, &len);
474     rsa->private_exponent = NULL;
475     rsa->comment = NULL;
476
477     return rsa;
478 }
479
480 static void rsa2_freekey(void *key)
481 {
482     struct RSAKey *rsa = (struct RSAKey *) key;
483     freersakey(rsa);
484     sfree(rsa);
485 }
486
487 static char *rsa2_fmtkey(void *key)
488 {
489     struct RSAKey *rsa = (struct RSAKey *) key;
490     char *p;
491     int len;
492
493     len = rsastr_len(rsa);
494     p = snewn(len, char);
495     rsastr_fmt(p, rsa);
496     return p;
497 }
498
499 static unsigned char *rsa2_public_blob(void *key, int *len)
500 {
501     struct RSAKey *rsa = (struct RSAKey *) key;
502     int elen, mlen, bloblen;
503     int i;
504     unsigned char *blob, *p;
505
506     elen = (bignum_bitcount(rsa->exponent) + 8) / 8;
507     mlen = (bignum_bitcount(rsa->modulus) + 8) / 8;
508
509     /*
510      * string "ssh-rsa", mpint exp, mpint mod. Total 19+elen+mlen.
511      * (three length fields, 12+7=19).
512      */
513     bloblen = 19 + elen + mlen;
514     blob = snewn(bloblen, unsigned char);
515     p = blob;
516     PUT_32BIT(p, 7);
517     p += 4;
518     memcpy(p, "ssh-rsa", 7);
519     p += 7;
520     PUT_32BIT(p, elen);
521     p += 4;
522     for (i = elen; i--;)
523         *p++ = bignum_byte(rsa->exponent, i);
524     PUT_32BIT(p, mlen);
525     p += 4;
526     for (i = mlen; i--;)
527         *p++ = bignum_byte(rsa->modulus, i);
528     assert(p == blob + bloblen);
529     *len = bloblen;
530     return blob;
531 }
532
533 static unsigned char *rsa2_private_blob(void *key, int *len)
534 {
535     struct RSAKey *rsa = (struct RSAKey *) key;
536     int dlen, plen, qlen, ulen, bloblen;
537     int i;
538     unsigned char *blob, *p;
539
540     dlen = (bignum_bitcount(rsa->private_exponent) + 8) / 8;
541     plen = (bignum_bitcount(rsa->p) + 8) / 8;
542     qlen = (bignum_bitcount(rsa->q) + 8) / 8;
543     ulen = (bignum_bitcount(rsa->iqmp) + 8) / 8;
544
545     /*
546      * mpint private_exp, mpint p, mpint q, mpint iqmp. Total 16 +
547      * sum of lengths.
548      */
549     bloblen = 16 + dlen + plen + qlen + ulen;
550     blob = snewn(bloblen, unsigned char);
551     p = blob;
552     PUT_32BIT(p, dlen);
553     p += 4;
554     for (i = dlen; i--;)
555         *p++ = bignum_byte(rsa->private_exponent, i);
556     PUT_32BIT(p, plen);
557     p += 4;
558     for (i = plen; i--;)
559         *p++ = bignum_byte(rsa->p, i);
560     PUT_32BIT(p, qlen);
561     p += 4;
562     for (i = qlen; i--;)
563         *p++ = bignum_byte(rsa->q, i);
564     PUT_32BIT(p, ulen);
565     p += 4;
566     for (i = ulen; i--;)
567         *p++ = bignum_byte(rsa->iqmp, i);
568     assert(p == blob + bloblen);
569     *len = bloblen;
570     return blob;
571 }
572
573 static void *rsa2_createkey(unsigned char *pub_blob, int pub_len,
574                             unsigned char *priv_blob, int priv_len)
575 {
576     struct RSAKey *rsa;
577     char *pb = (char *) priv_blob;
578
579     rsa = rsa2_newkey((char *) pub_blob, pub_len);
580     rsa->private_exponent = getmp(&pb, &priv_len);
581     rsa->p = getmp(&pb, &priv_len);
582     rsa->q = getmp(&pb, &priv_len);
583     rsa->iqmp = getmp(&pb, &priv_len);
584
585     if (!rsa_verify(rsa)) {
586         rsa2_freekey(rsa);
587         return NULL;
588     }
589
590     return rsa;
591 }
592
593 static void *rsa2_openssh_createkey(unsigned char **blob, int *len)
594 {
595     char **b = (char **) blob;
596     struct RSAKey *rsa;
597
598     rsa = snew(struct RSAKey);
599     if (!rsa)
600         return NULL;
601     rsa->comment = NULL;
602
603     rsa->modulus = getmp(b, len);
604     rsa->exponent = getmp(b, len);
605     rsa->private_exponent = getmp(b, len);
606     rsa->iqmp = getmp(b, len);
607     rsa->p = getmp(b, len);
608     rsa->q = getmp(b, len);
609
610     if (!rsa->modulus || !rsa->exponent || !rsa->private_exponent ||
611         !rsa->iqmp || !rsa->p || !rsa->q) {
612         sfree(rsa->modulus);
613         sfree(rsa->exponent);
614         sfree(rsa->private_exponent);
615         sfree(rsa->iqmp);
616         sfree(rsa->p);
617         sfree(rsa->q);
618         sfree(rsa);
619         return NULL;
620     }
621
622     return rsa;
623 }
624
625 static int rsa2_openssh_fmtkey(void *key, unsigned char *blob, int len)
626 {
627     struct RSAKey *rsa = (struct RSAKey *) key;
628     int bloblen, i;
629
630     bloblen =
631         ssh2_bignum_length(rsa->modulus) +
632         ssh2_bignum_length(rsa->exponent) +
633         ssh2_bignum_length(rsa->private_exponent) +
634         ssh2_bignum_length(rsa->iqmp) +
635         ssh2_bignum_length(rsa->p) + ssh2_bignum_length(rsa->q);
636
637     if (bloblen > len)
638         return bloblen;
639
640     bloblen = 0;
641 #define ENC(x) \
642     PUT_32BIT(blob+bloblen, ssh2_bignum_length((x))-4); bloblen += 4; \
643     for (i = ssh2_bignum_length((x))-4; i-- ;) blob[bloblen++]=bignum_byte((x),i);
644     ENC(rsa->modulus);
645     ENC(rsa->exponent);
646     ENC(rsa->private_exponent);
647     ENC(rsa->iqmp);
648     ENC(rsa->p);
649     ENC(rsa->q);
650
651     return bloblen;
652 }
653
654 static int rsa2_pubkey_bits(void *blob, int len)
655 {
656     struct RSAKey *rsa;
657     int ret;
658
659     rsa = rsa2_newkey((char *) blob, len);
660     ret = bignum_bitcount(rsa->modulus);
661     rsa2_freekey(rsa);
662
663     return ret;
664 }
665
666 static char *rsa2_fingerprint(void *key)
667 {
668     struct RSAKey *rsa = (struct RSAKey *) key;
669     struct MD5Context md5c;
670     unsigned char digest[16], lenbuf[4];
671     char buffer[16 * 3 + 40];
672     char *ret;
673     int numlen, i;
674
675     MD5Init(&md5c);
676     MD5Update(&md5c, (unsigned char *)"\0\0\0\7ssh-rsa", 11);
677
678 #define ADD_BIGNUM(bignum) \
679     numlen = (bignum_bitcount(bignum)+8)/8; \
680     PUT_32BIT(lenbuf, numlen); MD5Update(&md5c, lenbuf, 4); \
681     for (i = numlen; i-- ;) { \
682         unsigned char c = bignum_byte(bignum, i); \
683         MD5Update(&md5c, &c, 1); \
684     }
685     ADD_BIGNUM(rsa->exponent);
686     ADD_BIGNUM(rsa->modulus);
687 #undef ADD_BIGNUM
688
689     MD5Final(digest, &md5c);
690
691     sprintf(buffer, "ssh-rsa %d ", bignum_bitcount(rsa->modulus));
692     for (i = 0; i < 16; i++)
693         sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
694                 digest[i]);
695     ret = snewn(strlen(buffer) + 1, char);
696     if (ret)
697         strcpy(ret, buffer);
698     return ret;
699 }
700
701 /*
702  * This is the magic ASN.1/DER prefix that goes in the decoded
703  * signature, between the string of FFs and the actual SHA hash
704  * value. The meaning of it is:
705  * 
706  * 00 -- this marks the end of the FFs; not part of the ASN.1 bit itself
707  * 
708  * 30 21 -- a constructed SEQUENCE of length 0x21
709  *    30 09 -- a constructed sub-SEQUENCE of length 9
710  *       06 05 -- an object identifier, length 5
711  *          2B 0E 03 02 1A -- object id { 1 3 14 3 2 26 }
712  *                            (the 1,3 comes from 0x2B = 43 = 40*1+3)
713  *       05 00 -- NULL
714  *    04 14 -- a primitive OCTET STRING of length 0x14
715  *       [0x14 bytes of hash data follows]
716  * 
717  * The object id in the middle there is listed as `id-sha1' in
718  * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1d2.asn (the
719  * ASN module for PKCS #1) and its expanded form is as follows:
720  * 
721  * id-sha1                OBJECT IDENTIFIER ::= {
722  *    iso(1) identified-organization(3) oiw(14) secsig(3)
723  *    algorithms(2) 26 }
724  */
725 static const unsigned char asn1_weird_stuff[] = {
726     0x00, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
727     0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
728 };
729
730 #define ASN1_LEN ( (int) sizeof(asn1_weird_stuff) )
731
732 static int rsa2_verifysig(void *key, char *sig, int siglen,
733                           char *data, int datalen)
734 {
735     struct RSAKey *rsa = (struct RSAKey *) key;
736     Bignum in, out;
737     char *p;
738     int slen;
739     int bytes, i, j, ret;
740     unsigned char hash[20];
741
742     getstring(&sig, &siglen, &p, &slen);
743     if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
744         return 0;
745     }
746     in = getmp(&sig, &siglen);
747     out = modpow(in, rsa->exponent, rsa->modulus);
748     freebn(in);
749
750     ret = 1;
751
752     bytes = (bignum_bitcount(rsa->modulus)+7) / 8;
753     /* Top (partial) byte should be zero. */
754     if (bignum_byte(out, bytes - 1) != 0)
755         ret = 0;
756     /* First whole byte should be 1. */
757     if (bignum_byte(out, bytes - 2) != 1)
758         ret = 0;
759     /* Most of the rest should be FF. */
760     for (i = bytes - 3; i >= 20 + ASN1_LEN; i--) {
761         if (bignum_byte(out, i) != 0xFF)
762             ret = 0;
763     }
764     /* Then we expect to see the asn1_weird_stuff. */
765     for (i = 20 + ASN1_LEN - 1, j = 0; i >= 20; i--, j++) {
766         if (bignum_byte(out, i) != asn1_weird_stuff[j])
767             ret = 0;
768     }
769     /* Finally, we expect to see the SHA-1 hash of the signed data. */
770     SHA_Simple(data, datalen, hash);
771     for (i = 19, j = 0; i >= 0; i--, j++) {
772         if (bignum_byte(out, i) != hash[j])
773             ret = 0;
774     }
775     freebn(out);
776
777     return ret;
778 }
779
780 static unsigned char *rsa2_sign(void *key, char *data, int datalen,
781                                 int *siglen)
782 {
783     struct RSAKey *rsa = (struct RSAKey *) key;
784     unsigned char *bytes;
785     int nbytes;
786     unsigned char hash[20];
787     Bignum in, out;
788     int i, j;
789
790     SHA_Simple(data, datalen, hash);
791
792     nbytes = (bignum_bitcount(rsa->modulus) - 1) / 8;
793     assert(1 <= nbytes - 20 - ASN1_LEN);
794     bytes = snewn(nbytes, unsigned char);
795
796     bytes[0] = 1;
797     for (i = 1; i < nbytes - 20 - ASN1_LEN; i++)
798         bytes[i] = 0xFF;
799     for (i = nbytes - 20 - ASN1_LEN, j = 0; i < nbytes - 20; i++, j++)
800         bytes[i] = asn1_weird_stuff[j];
801     for (i = nbytes - 20, j = 0; i < nbytes; i++, j++)
802         bytes[i] = hash[j];
803
804     in = bignum_from_bytes(bytes, nbytes);
805     sfree(bytes);
806
807     out = rsa_privkey_op(in, rsa);
808     freebn(in);
809
810     nbytes = (bignum_bitcount(out) + 7) / 8;
811     bytes = snewn(4 + 7 + 4 + nbytes, unsigned char);
812     PUT_32BIT(bytes, 7);
813     memcpy(bytes + 4, "ssh-rsa", 7);
814     PUT_32BIT(bytes + 4 + 7, nbytes);
815     for (i = 0; i < nbytes; i++)
816         bytes[4 + 7 + 4 + i] = bignum_byte(out, nbytes - 1 - i);
817     freebn(out);
818
819     *siglen = 4 + 7 + 4 + nbytes;
820     return bytes;
821 }
822
823 const struct ssh_signkey ssh_rsa = {
824     rsa2_newkey,
825     rsa2_freekey,
826     rsa2_fmtkey,
827     rsa2_public_blob,
828     rsa2_private_blob,
829     rsa2_createkey,
830     rsa2_openssh_createkey,
831     rsa2_openssh_fmtkey,
832     rsa2_pubkey_bits,
833     rsa2_fingerprint,
834     rsa2_verifysig,
835     rsa2_sign,
836     "ssh-rsa",
837     "rsa2"
838 };
839
840 void *ssh_rsakex_newkey(char *data, int len)
841 {
842     return rsa2_newkey(data, len);
843 }
844
845 void ssh_rsakex_freekey(void *key)
846 {
847     rsa2_freekey(key);
848 }
849
850 int ssh_rsakex_klen(void *key)
851 {
852     struct RSAKey *rsa = (struct RSAKey *) key;
853
854     return bignum_bitcount(rsa->modulus);
855 }
856
857 static void oaep_mask(const struct ssh_hash *h, void *seed, int seedlen,
858                       void *vdata, int datalen)
859 {
860     unsigned char *data = (unsigned char *)vdata;
861     unsigned count = 0;
862
863     while (datalen > 0) {
864         int i, max = (datalen > h->hlen ? h->hlen : datalen);
865         void *s;
866         unsigned char counter[4], hash[SSH2_KEX_MAX_HASH_LEN];
867
868         assert(h->hlen <= SSH2_KEX_MAX_HASH_LEN);
869         PUT_32BIT(counter, count);
870         s = h->init();
871         h->bytes(s, seed, seedlen);
872         h->bytes(s, counter, 4);
873         h->final(s, hash);
874         count++;
875
876         for (i = 0; i < max; i++)
877             data[i] ^= hash[i];
878
879         data += max;
880         datalen -= max;
881     }
882 }
883
884 void ssh_rsakex_encrypt(const struct ssh_hash *h, unsigned char *in, int inlen,
885                         unsigned char *out, int outlen,
886                         void *key)
887 {
888     Bignum b1, b2;
889     struct RSAKey *rsa = (struct RSAKey *) key;
890     int k, i;
891     char *p;
892     const int HLEN = h->hlen;
893
894     /*
895      * Here we encrypt using RSAES-OAEP. Essentially this means:
896      * 
897      *  - we have a SHA-based `mask generation function' which
898      *    creates a pseudo-random stream of mask data
899      *    deterministically from an input chunk of data.
900      * 
901      *  - we have a random chunk of data called a seed.
902      * 
903      *  - we use the seed to generate a mask which we XOR with our
904      *    plaintext.
905      * 
906      *  - then we use _the masked plaintext_ to generate a mask
907      *    which we XOR with the seed.
908      * 
909      *  - then we concatenate the masked seed and the masked
910      *    plaintext, and RSA-encrypt that lot.
911      * 
912      * The result is that the data input to the encryption function
913      * is random-looking and (hopefully) contains no exploitable
914      * structure such as PKCS1-v1_5 does.
915      * 
916      * For a precise specification, see RFC 3447, section 7.1.1.
917      * Some of the variable names below are derived from that, so
918      * it'd probably help to read it anyway.
919      */
920
921     /* k denotes the length in octets of the RSA modulus. */
922     k = (7 + bignum_bitcount(rsa->modulus)) / 8;
923
924     /* The length of the input data must be at most k - 2hLen - 2. */
925     assert(inlen > 0 && inlen <= k - 2*HLEN - 2);
926
927     /* The length of the output data wants to be precisely k. */
928     assert(outlen == k);
929
930     /*
931      * Now perform EME-OAEP encoding. First set up all the unmasked
932      * output data.
933      */
934     /* Leading byte zero. */
935     out[0] = 0;
936     /* At position 1, the seed: HLEN bytes of random data. */
937     for (i = 0; i < HLEN; i++)
938         out[i + 1] = random_byte();
939     /* At position 1+HLEN, the data block DB, consisting of: */
940     /* The hash of the label (we only support an empty label here) */
941     h->final(h->init(), out + HLEN + 1);
942     /* A bunch of zero octets */
943     memset(out + 2*HLEN + 1, 0, outlen - (2*HLEN + 1));
944     /* A single 1 octet, followed by the input message data. */
945     out[outlen - inlen - 1] = 1;
946     memcpy(out + outlen - inlen, in, inlen);
947
948     /*
949      * Now use the seed data to mask the block DB.
950      */
951     oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
952
953     /*
954      * And now use the masked DB to mask the seed itself.
955      */
956     oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
957
958     /*
959      * Now `out' contains precisely the data we want to
960      * RSA-encrypt.
961      */
962     b1 = bignum_from_bytes(out, outlen);
963     b2 = modpow(b1, rsa->exponent, rsa->modulus);
964     p = (char *)out;
965     for (i = outlen; i--;) {
966         *p++ = bignum_byte(b2, i);
967     }
968     freebn(b1);
969     freebn(b2);
970
971     /*
972      * And we're done.
973      */
974 }
975
976 static const struct ssh_kex ssh_rsa_kex_sha1 = {
977     "rsa1024-sha1", NULL, KEXTYPE_RSA, NULL, NULL, 0, 0, &ssh_sha1
978 };
979
980 static const struct ssh_kex ssh_rsa_kex_sha256 = {
981     "rsa2048-sha256", NULL, KEXTYPE_RSA, NULL, NULL, 0, 0, &ssh_sha256
982 };
983
984 static const struct ssh_kex *const rsa_kex_list[] = {
985     &ssh_rsa_kex_sha256,
986     &ssh_rsa_kex_sha1
987 };
988
989 const struct ssh_kexes ssh_rsa_kex = {
990     sizeof(rsa_kex_list) / sizeof(*rsa_kex_list),
991     rsa_kex_list
992 };