sshrsa.c 29 KB

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