sshrsa.c 25 KB

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