2 * RSA implementation for PuTTY.
13 #define GET_32BIT(cp) \
14 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
15 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
16 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
17 ((unsigned long)(unsigned char)(cp)[3]))
19 #define PUT_32BIT(cp, value) { \
20 (cp)[0] = (unsigned char)((value) >> 24); \
21 (cp)[1] = (unsigned char)((value) >> 16); \
22 (cp)[2] = (unsigned char)((value) >> 8); \
23 (cp)[3] = (unsigned char)(value); }
25 int makekey(unsigned char *data, struct RSAKey *result,
26 unsigned char **keystr, int order)
28 unsigned char *p = data;
33 for (i = 0; i < 4; i++)
34 result->bits = (result->bits << 8) + *p++;
39 * order=0 means exponent then modulus (the keys sent by the
40 * server). order=1 means modulus then exponent (the keys
41 * stored in a keyfile).
45 p += ssh1_read_bignum(p, result ? &result->exponent : NULL);
47 result->bytes = (((p[0] << 8) + p[1]) + 7) / 8;
50 p += ssh1_read_bignum(p, result ? &result->modulus : NULL);
52 p += ssh1_read_bignum(p, result ? &result->exponent : NULL);
57 int makeprivate(unsigned char *data, struct RSAKey *result)
59 return ssh1_read_bignum(data, &result->private_exponent);
62 void rsaencrypt(unsigned char *data, int length, struct RSAKey *key)
68 memmove(data + key->bytes - length, data, length);
72 for (i = 2; i < key->bytes - length - 1; i++) {
74 data[i] = random_byte();
75 } while (data[i] == 0);
77 data[key->bytes - length - 1] = 0;
79 b1 = bignum_from_bytes(data, key->bytes);
81 b2 = modpow(b1, key->exponent, key->modulus);
84 for (i = key->bytes; i--;) {
85 *p++ = bignum_byte(b2, i);
93 * This function is a wrapper on modpow(). It has the same effect
94 * as modpow(), but employs RSA blinding to protect against timing
97 static Bignum rsa_privkey_op(Bignum input, struct RSAKey *key)
99 Bignum random, random_encrypted, random_inverse;
100 Bignum input_blinded, ret_blinded;
104 * Start by inventing a random number chosen uniformly from the
105 * range 2..modulus-1. (We do this by preparing a random number
106 * of the right length and retrying if it's greater than the
107 * modulus, to prevent any potential Bleichenbacher-like
108 * attacks making use of the uneven distribution within the
109 * range that would arise from just reducing our number mod n.
110 * There are timing implications to the potential retries, of
111 * course, but all they tell you is the modulus, which you
115 int bits, byte, bitsleft, v;
116 random = copybn(key->modulus);
118 * Find the topmost set bit. (This function will return its
119 * index plus one.) Then we'll set all bits from that one
120 * downwards randomly.
122 bits = bignum_bitcount(random);
127 bitsleft = 8, byte = random_byte();
131 bignum_set_bit(random, bits, v);
135 * Now check that this number is strictly greater than
136 * zero, and strictly less than modulus.
138 if (bignum_cmp(random, Zero) <= 0 ||
139 bignum_cmp(random, key->modulus) >= 0) {
148 * RSA blinding relies on the fact that (xy)^d mod n is equal
149 * to (x^d mod n) * (y^d mod n) mod n. We invent a random pair
150 * y and y^d; then we multiply x by y, raise to the power d mod
151 * n as usual, and divide by y^d to recover x^d. Thus an
152 * attacker can't correlate the timing of the modpow with the
153 * input, because they don't know anything about the number
154 * that was input to the actual modpow.
156 * The clever bit is that we don't have to do a huge modpow to
157 * get y and y^d; we will use the number we just invented as
158 * _y^d_, and use the _public_ exponent to compute (y^d)^e = y
159 * from it, which is much faster to do.
161 random_encrypted = modpow(random, key->exponent, key->modulus);
162 random_inverse = modinv(random, key->modulus);
163 input_blinded = modmul(input, random_encrypted, key->modulus);
164 ret_blinded = modpow(input_blinded, key->private_exponent, key->modulus);
165 ret = modmul(ret_blinded, random_inverse, key->modulus);
168 freebn(input_blinded);
169 freebn(random_inverse);
170 freebn(random_encrypted);
176 Bignum rsadecrypt(Bignum input, struct RSAKey *key)
178 return rsa_privkey_op(input, key);
181 int rsastr_len(struct RSAKey *key)
188 mdlen = (bignum_bitcount(md) + 15) / 16;
189 exlen = (bignum_bitcount(ex) + 15) / 16;
190 return 4 * (mdlen + exlen) + 20;
193 void rsastr_fmt(char *str, struct RSAKey *key)
196 int len = 0, i, nibbles;
197 static const char hex[] = "0123456789abcdef";
202 len += sprintf(str + len, "0x");
204 nibbles = (3 + bignum_bitcount(ex)) / 4;
207 for (i = nibbles; i--;)
208 str[len++] = hex[(bignum_byte(ex, i / 2) >> (4 * (i % 2))) & 0xF];
210 len += sprintf(str + len, ",0x");
212 nibbles = (3 + bignum_bitcount(md)) / 4;
215 for (i = nibbles; i--;)
216 str[len++] = hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF];
222 * Generate a fingerprint string for the key. Compatible with the
223 * OpenSSH fingerprint code.
225 void rsa_fingerprint(char *str, int len, struct RSAKey *key)
227 struct MD5Context md5c;
228 unsigned char digest[16];
229 char buffer[16 * 3 + 40];
233 numlen = ssh1_bignum_length(key->modulus) - 2;
234 for (i = numlen; i--;) {
235 unsigned char c = bignum_byte(key->modulus, i);
236 MD5Update(&md5c, &c, 1);
238 numlen = ssh1_bignum_length(key->exponent) - 2;
239 for (i = numlen; i--;) {
240 unsigned char c = bignum_byte(key->exponent, i);
241 MD5Update(&md5c, &c, 1);
243 MD5Final(digest, &md5c);
245 sprintf(buffer, "%d ", bignum_bitcount(key->modulus));
246 for (i = 0; i < 16; i++)
247 sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
249 strncpy(str, buffer, len);
252 if (key->comment && slen < len - 1) {
254 strncpy(str + slen + 1, key->comment, len - slen - 1);
260 * Verify that the public data in an RSA key matches the private
261 * data. We also check the private data itself: we ensure that p >
262 * q and that iqmp really is the inverse of q mod p.
264 int rsa_verify(struct RSAKey *key)
266 Bignum n, ed, pm1, qm1;
269 /* n must equal pq. */
270 n = bigmul(key->p, key->q);
271 cmp = bignum_cmp(n, key->modulus);
276 /* e * d must be congruent to 1, modulo (p-1) and modulo (q-1). */
277 pm1 = copybn(key->p);
279 ed = modmul(key->exponent, key->private_exponent, pm1);
280 cmp = bignum_cmp(ed, One);
285 qm1 = copybn(key->q);
287 ed = modmul(key->exponent, key->private_exponent, qm1);
288 cmp = bignum_cmp(ed, One);
296 if (bignum_cmp(key->p, key->q) <= 0)
300 * Ensure iqmp * q is congruent to 1, modulo p.
302 n = modmul(key->iqmp, key->q, key->p);
303 cmp = bignum_cmp(n, One);
311 /* Public key blob as used by Pageant: exponent before modulus. */
312 unsigned char *rsa_public_blob(struct RSAKey *key, int *len)
317 length = (ssh1_bignum_length(key->modulus) +
318 ssh1_bignum_length(key->exponent) + 4);
319 ret = smalloc(length);
321 PUT_32BIT(ret, bignum_bitcount(key->modulus));
323 pos += ssh1_write_bignum(ret + pos, key->exponent);
324 pos += ssh1_write_bignum(ret + pos, key->modulus);
330 /* Given a public blob, determine its length. */
331 int rsa_public_blob_len(void *data)
333 unsigned char *p = (unsigned char *)data;
335 p += 4; /* length word */
336 p += ssh1_read_bignum(p, NULL); /* exponent */
337 p += ssh1_read_bignum(p, NULL); /* modulus */
339 return p - (unsigned char *)data;
342 void freersakey(struct RSAKey *key)
345 freebn(key->modulus);
347 freebn(key->exponent);
348 if (key->private_exponent)
349 freebn(key->private_exponent);
354 /* ----------------------------------------------------------------------
355 * Implementation of the ssh-rsa signing key type.
358 static void getstring(char **data, int *datalen, char **p, int *length)
363 *length = GET_32BIT(*data);
366 if (*datalen < *length)
372 static Bignum getmp(char **data, int *datalen)
378 getstring(data, datalen, &p, &length);
381 b = bignum_from_bytes((unsigned char *)p, length);
385 static void *rsa2_newkey(char *data, int len)
391 rsa = smalloc(sizeof(struct RSAKey));
394 getstring(&data, &len, &p, &slen);
396 if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
400 rsa->exponent = getmp(&data, &len);
401 rsa->modulus = getmp(&data, &len);
402 rsa->private_exponent = NULL;
408 static void rsa2_freekey(void *key)
410 struct RSAKey *rsa = (struct RSAKey *) key;
415 static char *rsa2_fmtkey(void *key)
417 struct RSAKey *rsa = (struct RSAKey *) key;
421 len = rsastr_len(rsa);
427 static unsigned char *rsa2_public_blob(void *key, int *len)
429 struct RSAKey *rsa = (struct RSAKey *) key;
430 int elen, mlen, bloblen;
432 unsigned char *blob, *p;
434 elen = (bignum_bitcount(rsa->exponent) + 8) / 8;
435 mlen = (bignum_bitcount(rsa->modulus) + 8) / 8;
438 * string "ssh-rsa", mpint exp, mpint mod. Total 19+elen+mlen.
439 * (three length fields, 12+7=19).
441 bloblen = 19 + elen + mlen;
442 blob = smalloc(bloblen);
446 memcpy(p, "ssh-rsa", 7);
451 *p++ = bignum_byte(rsa->exponent, i);
455 *p++ = bignum_byte(rsa->modulus, i);
456 assert(p == blob + bloblen);
461 static unsigned char *rsa2_private_blob(void *key, int *len)
463 struct RSAKey *rsa = (struct RSAKey *) key;
464 int dlen, plen, qlen, ulen, bloblen;
466 unsigned char *blob, *p;
468 dlen = (bignum_bitcount(rsa->private_exponent) + 8) / 8;
469 plen = (bignum_bitcount(rsa->p) + 8) / 8;
470 qlen = (bignum_bitcount(rsa->q) + 8) / 8;
471 ulen = (bignum_bitcount(rsa->iqmp) + 8) / 8;
474 * mpint private_exp, mpint p, mpint q, mpint iqmp. Total 16 +
477 bloblen = 16 + dlen + plen + qlen + ulen;
478 blob = smalloc(bloblen);
483 *p++ = bignum_byte(rsa->private_exponent, i);
487 *p++ = bignum_byte(rsa->p, i);
491 *p++ = bignum_byte(rsa->q, i);
495 *p++ = bignum_byte(rsa->iqmp, i);
496 assert(p == blob + bloblen);
501 static void *rsa2_createkey(unsigned char *pub_blob, int pub_len,
502 unsigned char *priv_blob, int priv_len)
505 char *pb = (char *) priv_blob;
507 rsa = rsa2_newkey((char *) pub_blob, pub_len);
508 rsa->private_exponent = getmp(&pb, &priv_len);
509 rsa->p = getmp(&pb, &priv_len);
510 rsa->q = getmp(&pb, &priv_len);
511 rsa->iqmp = getmp(&pb, &priv_len);
513 if (!rsa_verify(rsa)) {
521 static void *rsa2_openssh_createkey(unsigned char **blob, int *len)
523 char **b = (char **) blob;
526 rsa = smalloc(sizeof(struct RSAKey));
531 rsa->modulus = getmp(b, len);
532 rsa->exponent = getmp(b, len);
533 rsa->private_exponent = getmp(b, len);
534 rsa->iqmp = getmp(b, len);
535 rsa->p = getmp(b, len);
536 rsa->q = getmp(b, len);
538 if (!rsa->modulus || !rsa->exponent || !rsa->private_exponent ||
539 !rsa->iqmp || !rsa->p || !rsa->q) {
541 sfree(rsa->exponent);
542 sfree(rsa->private_exponent);
553 static int rsa2_openssh_fmtkey(void *key, unsigned char *blob, int len)
555 struct RSAKey *rsa = (struct RSAKey *) key;
559 ssh2_bignum_length(rsa->modulus) +
560 ssh2_bignum_length(rsa->exponent) +
561 ssh2_bignum_length(rsa->private_exponent) +
562 ssh2_bignum_length(rsa->iqmp) +
563 ssh2_bignum_length(rsa->p) + ssh2_bignum_length(rsa->q);
570 PUT_32BIT(blob+bloblen, ssh2_bignum_length((x))-4); bloblen += 4; \
571 for (i = ssh2_bignum_length((x))-4; i-- ;) blob[bloblen++]=bignum_byte((x),i);
574 ENC(rsa->private_exponent);
582 static char *rsa2_fingerprint(void *key)
584 struct RSAKey *rsa = (struct RSAKey *) key;
585 struct MD5Context md5c;
586 unsigned char digest[16], lenbuf[4];
587 char buffer[16 * 3 + 40];
592 MD5Update(&md5c, (unsigned char *)"\0\0\0\7ssh-rsa", 11);
594 #define ADD_BIGNUM(bignum) \
595 numlen = (bignum_bitcount(bignum)+8)/8; \
596 PUT_32BIT(lenbuf, numlen); MD5Update(&md5c, lenbuf, 4); \
597 for (i = numlen; i-- ;) { \
598 unsigned char c = bignum_byte(bignum, i); \
599 MD5Update(&md5c, &c, 1); \
601 ADD_BIGNUM(rsa->exponent);
602 ADD_BIGNUM(rsa->modulus);
605 MD5Final(digest, &md5c);
607 sprintf(buffer, "ssh-rsa %d ", bignum_bitcount(rsa->modulus));
608 for (i = 0; i < 16; i++)
609 sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
611 ret = smalloc(strlen(buffer) + 1);
618 * This is the magic ASN.1/DER prefix that goes in the decoded
619 * signature, between the string of FFs and the actual SHA hash
620 * value. The meaning of it is:
622 * 00 -- this marks the end of the FFs; not part of the ASN.1 bit itself
624 * 30 21 -- a constructed SEQUENCE of length 0x21
625 * 30 09 -- a constructed sub-SEQUENCE of length 9
626 * 06 05 -- an object identifier, length 5
627 * 2B 0E 03 02 1A -- object id { 1 3 14 3 2 26 }
628 * (the 1,3 comes from 0x2B = 43 = 40*1+3)
630 * 04 14 -- a primitive OCTET STRING of length 0x14
631 * [0x14 bytes of hash data follows]
633 * The object id in the middle there is listed as `id-sha1' in
634 * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1d2.asn (the
635 * ASN module for PKCS #1) and its expanded form is as follows:
637 * id-sha1 OBJECT IDENTIFIER ::= {
638 * iso(1) identified-organization(3) oiw(14) secsig(3)
641 static const unsigned char asn1_weird_stuff[] = {
642 0x00, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
643 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
646 #define ASN1_LEN ( (int) sizeof(asn1_weird_stuff) )
648 static int rsa2_verifysig(void *key, char *sig, int siglen,
649 char *data, int datalen)
651 struct RSAKey *rsa = (struct RSAKey *) key;
655 int bytes, i, j, ret;
656 unsigned char hash[20];
658 getstring(&sig, &siglen, &p, &slen);
659 if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
662 in = getmp(&sig, &siglen);
663 out = modpow(in, rsa->exponent, rsa->modulus);
668 bytes = bignum_bitcount(rsa->modulus) / 8;
669 /* Top (partial) byte should be zero. */
670 if (bignum_byte(out, bytes - 1) != 0)
672 /* First whole byte should be 1. */
673 if (bignum_byte(out, bytes - 2) != 1)
675 /* Most of the rest should be FF. */
676 for (i = bytes - 3; i >= 20 + ASN1_LEN; i--) {
677 if (bignum_byte(out, i) != 0xFF)
680 /* Then we expect to see the asn1_weird_stuff. */
681 for (i = 20 + ASN1_LEN - 1, j = 0; i >= 20; i--, j++) {
682 if (bignum_byte(out, i) != asn1_weird_stuff[j])
685 /* Finally, we expect to see the SHA-1 hash of the signed data. */
686 SHA_Simple(data, datalen, hash);
687 for (i = 19, j = 0; i >= 0; i--, j++) {
688 if (bignum_byte(out, i) != hash[j])
695 static unsigned char *rsa2_sign(void *key, char *data, int datalen,
698 struct RSAKey *rsa = (struct RSAKey *) key;
699 unsigned char *bytes;
701 unsigned char hash[20];
705 SHA_Simple(data, datalen, hash);
707 nbytes = (bignum_bitcount(rsa->modulus) - 1) / 8;
708 bytes = smalloc(nbytes);
711 for (i = 1; i < nbytes - 20 - ASN1_LEN; i++)
713 for (i = nbytes - 20 - ASN1_LEN, j = 0; i < nbytes - 20; i++, j++)
714 bytes[i] = asn1_weird_stuff[j];
715 for (i = nbytes - 20, j = 0; i < nbytes; i++, j++)
718 in = bignum_from_bytes(bytes, nbytes);
721 out = rsa_privkey_op(in, rsa);
724 nbytes = (bignum_bitcount(out) + 7) / 8;
725 bytes = smalloc(4 + 7 + 4 + nbytes);
727 memcpy(bytes + 4, "ssh-rsa", 7);
728 PUT_32BIT(bytes + 4 + 7, nbytes);
729 for (i = 0; i < nbytes; i++)
730 bytes[4 + 7 + 4 + i] = bignum_byte(out, nbytes - 1 - i);
733 *siglen = 4 + 7 + 4 + nbytes;
737 const struct ssh_signkey ssh_rsa = {
744 rsa2_openssh_createkey,