sshrsa.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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. bool 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 false; /* 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 true;
  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. bool rsa_ssh1_decrypt_pkcs1(Bignum input, struct RSAKey *key, strbuf *outbuf)
  254. {
  255. strbuf *data = strbuf_new();
  256. bool success = false;
  257. BinarySource src[1];
  258. {
  259. Bignum *b = rsa_ssh1_decrypt(input, key);
  260. int i;
  261. for (i = (bignum_bitcount(key->modulus) + 7) / 8; i-- > 0 ;) {
  262. put_byte(data, bignum_byte(b, i));
  263. }
  264. freebn(b);
  265. }
  266. BinarySource_BARE_INIT(src, data->u, data->len);
  267. /* Check PKCS#1 formatting prefix */
  268. if (get_byte(src) != 0) goto out;
  269. if (get_byte(src) != 2) goto out;
  270. while (1) {
  271. unsigned char byte = get_byte(src);
  272. if (get_err(src)) goto out;
  273. if (byte == 0)
  274. break;
  275. }
  276. /* Everything else is the payload */
  277. success = true;
  278. put_data(outbuf, get_ptr(src), get_avail(src));
  279. out:
  280. strbuf_free(data);
  281. return success;
  282. }
  283. int rsastr_len(struct RSAKey *key)
  284. {
  285. Bignum md, ex;
  286. int mdlen, exlen;
  287. md = key->modulus;
  288. ex = key->exponent;
  289. mdlen = (bignum_bitcount(md) + 15) / 16;
  290. exlen = (bignum_bitcount(ex) + 15) / 16;
  291. return 4 * (mdlen + exlen) + 20;
  292. }
  293. void rsastr_fmt(char *str, struct RSAKey *key)
  294. {
  295. Bignum md, ex;
  296. int len = 0, i, nibbles;
  297. static const char hex[] = "0123456789abcdef";
  298. md = key->modulus;
  299. ex = key->exponent;
  300. len += sprintf(str + len, "0x");
  301. nibbles = (3 + bignum_bitcount(ex)) / 4;
  302. if (nibbles < 1)
  303. nibbles = 1;
  304. for (i = nibbles; i--;)
  305. str[len++] = hex[(bignum_byte(ex, i / 2) >> (4 * (i % 2))) & 0xF];
  306. len += sprintf(str + len, ",0x");
  307. nibbles = (3 + bignum_bitcount(md)) / 4;
  308. if (nibbles < 1)
  309. nibbles = 1;
  310. for (i = nibbles; i--;)
  311. str[len++] = hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF];
  312. str[len] = '\0';
  313. }
  314. /*
  315. * Generate a fingerprint string for the key. Compatible with the
  316. * OpenSSH fingerprint code.
  317. */
  318. char *rsa_ssh1_fingerprint(struct RSAKey *key)
  319. {
  320. struct MD5Context md5c;
  321. unsigned char digest[16];
  322. strbuf *out;
  323. int i;
  324. MD5Init(&md5c);
  325. put_mp_ssh1(&md5c, key->modulus);
  326. put_mp_ssh1(&md5c, key->exponent);
  327. MD5Final(digest, &md5c);
  328. out = strbuf_new();
  329. strbuf_catf(out, "%d ", bignum_bitcount(key->modulus));
  330. for (i = 0; i < 16; i++)
  331. strbuf_catf(out, "%s%02x", i ? ":" : "", digest[i]);
  332. if (key->comment)
  333. strbuf_catf(out, " %s", key->comment);
  334. return strbuf_to_str(out);
  335. }
  336. /*
  337. * Verify that the public data in an RSA key matches the private
  338. * data. We also check the private data itself: we ensure that p >
  339. * q and that iqmp really is the inverse of q mod p.
  340. */
  341. bool rsa_verify(struct RSAKey *key)
  342. {
  343. Bignum n, ed, pm1, qm1;
  344. int cmp;
  345. /* n must equal pq. */
  346. n = bigmul(key->p, key->q);
  347. cmp = bignum_cmp(n, key->modulus);
  348. freebn(n);
  349. if (cmp != 0)
  350. return false;
  351. /* e * d must be congruent to 1, modulo (p-1) and modulo (q-1). */
  352. pm1 = copybn(key->p);
  353. decbn(pm1);
  354. ed = modmul(key->exponent, key->private_exponent, pm1);
  355. freebn(pm1);
  356. cmp = bignum_cmp(ed, One);
  357. freebn(ed);
  358. if (cmp != 0)
  359. return false;
  360. qm1 = copybn(key->q);
  361. decbn(qm1);
  362. ed = modmul(key->exponent, key->private_exponent, qm1);
  363. freebn(qm1);
  364. cmp = bignum_cmp(ed, One);
  365. freebn(ed);
  366. if (cmp != 0)
  367. return false;
  368. /*
  369. * Ensure p > q.
  370. *
  371. * I have seen key blobs in the wild which were generated with
  372. * p < q, so instead of rejecting the key in this case we
  373. * should instead flip them round into the canonical order of
  374. * p > q. This also involves regenerating iqmp.
  375. */
  376. if (bignum_cmp(key->p, key->q) <= 0) {
  377. Bignum tmp = key->p;
  378. key->p = key->q;
  379. key->q = tmp;
  380. freebn(key->iqmp);
  381. key->iqmp = modinv(key->q, key->p);
  382. if (!key->iqmp)
  383. return false;
  384. }
  385. /*
  386. * Ensure iqmp * q is congruent to 1, modulo p.
  387. */
  388. n = modmul(key->iqmp, key->q, key->p);
  389. cmp = bignum_cmp(n, One);
  390. freebn(n);
  391. if (cmp != 0)
  392. return false;
  393. return true;
  394. }
  395. void rsa_ssh1_public_blob(BinarySink *bs, struct RSAKey *key,
  396. RsaSsh1Order order)
  397. {
  398. put_uint32(bs, bignum_bitcount(key->modulus));
  399. if (order == RSA_SSH1_EXPONENT_FIRST) {
  400. put_mp_ssh1(bs, key->exponent);
  401. put_mp_ssh1(bs, key->modulus);
  402. } else {
  403. put_mp_ssh1(bs, key->modulus);
  404. put_mp_ssh1(bs, key->exponent);
  405. }
  406. }
  407. /* Given an SSH-1 public key blob, determine its length. */
  408. int rsa_ssh1_public_blob_len(void *data, int maxlen)
  409. {
  410. BinarySource src[1];
  411. BinarySource_BARE_INIT(src, data, maxlen);
  412. /* Expect a length word, then exponent and modulus. (It doesn't
  413. * even matter which order.) */
  414. get_uint32(src);
  415. freebn(get_mp_ssh1(src));
  416. freebn(get_mp_ssh1(src));
  417. if (get_err(src))
  418. return -1;
  419. /* Return the number of bytes consumed. */
  420. return src->pos;
  421. }
  422. void freersakey(struct RSAKey *key)
  423. {
  424. if (key->modulus)
  425. freebn(key->modulus);
  426. if (key->exponent)
  427. freebn(key->exponent);
  428. if (key->private_exponent)
  429. freebn(key->private_exponent);
  430. if (key->p)
  431. freebn(key->p);
  432. if (key->q)
  433. freebn(key->q);
  434. if (key->iqmp)
  435. freebn(key->iqmp);
  436. if (key->comment)
  437. sfree(key->comment);
  438. }
  439. /* ----------------------------------------------------------------------
  440. * Implementation of the ssh-rsa signing key type.
  441. */
  442. static void rsa2_freekey(ssh_key *key); /* forward reference */
  443. static ssh_key *rsa2_new_pub(const ssh_keyalg *self, ptrlen data)
  444. {
  445. BinarySource src[1];
  446. struct RSAKey *rsa;
  447. BinarySource_BARE_INIT(src, data.ptr, data.len);
  448. if (!ptrlen_eq_string(get_string(src), "ssh-rsa"))
  449. return NULL;
  450. rsa = snew(struct RSAKey);
  451. rsa->sshk.vt = &ssh_rsa;
  452. rsa->exponent = get_mp_ssh2(src);
  453. rsa->modulus = get_mp_ssh2(src);
  454. rsa->private_exponent = NULL;
  455. rsa->p = rsa->q = rsa->iqmp = NULL;
  456. rsa->comment = NULL;
  457. if (get_err(src)) {
  458. rsa2_freekey(&rsa->sshk);
  459. return NULL;
  460. }
  461. return &rsa->sshk;
  462. }
  463. static void rsa2_freekey(ssh_key *key)
  464. {
  465. struct RSAKey *rsa = container_of(key, struct RSAKey, sshk);
  466. freersakey(rsa);
  467. sfree(rsa);
  468. }
  469. static char *rsa2_cache_str(ssh_key *key)
  470. {
  471. struct RSAKey *rsa = container_of(key, struct RSAKey, sshk);
  472. char *p;
  473. int len;
  474. len = rsastr_len(rsa);
  475. p = snewn(len, char);
  476. rsastr_fmt(p, rsa);
  477. return p;
  478. }
  479. static void rsa2_public_blob(ssh_key *key, BinarySink *bs)
  480. {
  481. struct RSAKey *rsa = container_of(key, struct RSAKey, sshk);
  482. put_stringz(bs, "ssh-rsa");
  483. put_mp_ssh2(bs, rsa->exponent);
  484. put_mp_ssh2(bs, rsa->modulus);
  485. }
  486. static void rsa2_private_blob(ssh_key *key, BinarySink *bs)
  487. {
  488. struct RSAKey *rsa = container_of(key, struct RSAKey, sshk);
  489. put_mp_ssh2(bs, rsa->private_exponent);
  490. put_mp_ssh2(bs, rsa->p);
  491. put_mp_ssh2(bs, rsa->q);
  492. put_mp_ssh2(bs, rsa->iqmp);
  493. }
  494. static ssh_key *rsa2_new_priv(const ssh_keyalg *self,
  495. ptrlen pub, ptrlen priv)
  496. {
  497. BinarySource src[1];
  498. ssh_key *sshk;
  499. struct RSAKey *rsa;
  500. sshk = rsa2_new_pub(self, pub);
  501. if (!sshk)
  502. return NULL;
  503. rsa = container_of(sshk, struct RSAKey, sshk);
  504. BinarySource_BARE_INIT(src, priv.ptr, priv.len);
  505. rsa->private_exponent = get_mp_ssh2(src);
  506. rsa->p = get_mp_ssh2(src);
  507. rsa->q = get_mp_ssh2(src);
  508. rsa->iqmp = get_mp_ssh2(src);
  509. if (get_err(src) || !rsa_verify(rsa)) {
  510. rsa2_freekey(&rsa->sshk);
  511. return NULL;
  512. }
  513. return &rsa->sshk;
  514. }
  515. static ssh_key *rsa2_new_priv_openssh(const ssh_keyalg *self,
  516. BinarySource *src)
  517. {
  518. struct RSAKey *rsa;
  519. rsa = snew(struct RSAKey);
  520. rsa->sshk.vt = &ssh_rsa;
  521. rsa->comment = NULL;
  522. rsa->modulus = get_mp_ssh2(src);
  523. rsa->exponent = get_mp_ssh2(src);
  524. rsa->private_exponent = get_mp_ssh2(src);
  525. rsa->iqmp = get_mp_ssh2(src);
  526. rsa->p = get_mp_ssh2(src);
  527. rsa->q = get_mp_ssh2(src);
  528. if (get_err(src) || !rsa_verify(rsa)) {
  529. rsa2_freekey(&rsa->sshk);
  530. return NULL;
  531. }
  532. return &rsa->sshk;
  533. }
  534. static void rsa2_openssh_blob(ssh_key *key, BinarySink *bs)
  535. {
  536. struct RSAKey *rsa = container_of(key, struct RSAKey, sshk);
  537. put_mp_ssh2(bs, rsa->modulus);
  538. put_mp_ssh2(bs, rsa->exponent);
  539. put_mp_ssh2(bs, rsa->private_exponent);
  540. put_mp_ssh2(bs, rsa->iqmp);
  541. put_mp_ssh2(bs, rsa->p);
  542. put_mp_ssh2(bs, rsa->q);
  543. }
  544. static int rsa2_pubkey_bits(const ssh_keyalg *self, ptrlen pub)
  545. {
  546. ssh_key *sshk;
  547. struct RSAKey *rsa;
  548. int ret;
  549. sshk = rsa2_new_pub(self, pub);
  550. if (!sshk)
  551. return -1;
  552. rsa = container_of(sshk, struct RSAKey, sshk);
  553. ret = bignum_bitcount(rsa->modulus);
  554. rsa2_freekey(&rsa->sshk);
  555. return ret;
  556. }
  557. /*
  558. * This is the magic ASN.1/DER prefix that goes in the decoded
  559. * signature, between the string of FFs and the actual SHA hash
  560. * value. The meaning of it is:
  561. *
  562. * 00 -- this marks the end of the FFs; not part of the ASN.1 bit itself
  563. *
  564. * 30 21 -- a constructed SEQUENCE of length 0x21
  565. * 30 09 -- a constructed sub-SEQUENCE of length 9
  566. * 06 05 -- an object identifier, length 5
  567. * 2B 0E 03 02 1A -- object id { 1 3 14 3 2 26 }
  568. * (the 1,3 comes from 0x2B = 43 = 40*1+3)
  569. * 05 00 -- NULL
  570. * 04 14 -- a primitive OCTET STRING of length 0x14
  571. * [0x14 bytes of hash data follows]
  572. *
  573. * The object id in the middle there is listed as `id-sha1' in
  574. * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1d2.asn (the
  575. * ASN module for PKCS #1) and its expanded form is as follows:
  576. *
  577. * id-sha1 OBJECT IDENTIFIER ::= {
  578. * iso(1) identified-organization(3) oiw(14) secsig(3)
  579. * algorithms(2) 26 }
  580. */
  581. static const unsigned char sha1_asn1_prefix[] = {
  582. 0x00, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
  583. 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
  584. };
  585. /*
  586. * Two more similar pieces of ASN.1 used for signatures using SHA-256
  587. * and SHA-512, in the same format but differing only in various
  588. * length fields and OID.
  589. */
  590. static const unsigned char sha256_asn1_prefix[] = {
  591. 0x00, 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60,
  592. 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
  593. 0x05, 0x00, 0x04, 0x20,
  594. };
  595. static const unsigned char sha512_asn1_prefix[] = {
  596. 0x00, 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60,
  597. 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
  598. 0x05, 0x00, 0x04, 0x40,
  599. };
  600. #define SHA1_ASN1_PREFIX_LEN sizeof(sha1_asn1_prefix)
  601. static bool rsa2_verify(ssh_key *key, ptrlen sig, ptrlen data)
  602. {
  603. struct RSAKey *rsa = container_of(key, struct RSAKey, sshk);
  604. BinarySource src[1];
  605. ptrlen type, in_pl;
  606. Bignum in, out;
  607. int bytes, i, j;
  608. bool toret;
  609. unsigned char hash[20];
  610. BinarySource_BARE_INIT(src, sig.ptr, sig.len);
  611. type = get_string(src);
  612. /*
  613. * RFC 4253 section 6.6: the signature integer in an ssh-rsa
  614. * signature is 'without lengths or padding'. That is, we _don't_
  615. * expect the usual leading zero byte if the topmost bit of the
  616. * first byte is set. (However, because of the possibility of
  617. * BUG_SSH2_RSA_PADDING at the other end, we tolerate it if it's
  618. * there.) So we can't use get_mp_ssh2, which enforces that
  619. * leading-byte scheme; instead we use get_string and
  620. * bignum_from_bytes, which will tolerate anything.
  621. */
  622. in_pl = get_string(src);
  623. if (get_err(src) || !ptrlen_eq_string(type, "ssh-rsa"))
  624. return false;
  625. in = bignum_from_bytes(in_pl.ptr, in_pl.len);
  626. out = modpow(in, rsa->exponent, rsa->modulus);
  627. freebn(in);
  628. toret = true;
  629. bytes = (bignum_bitcount(rsa->modulus)+7) / 8;
  630. /* Top (partial) byte should be zero. */
  631. if (bignum_byte(out, bytes - 1) != 0)
  632. toret = false;
  633. /* First whole byte should be 1. */
  634. if (bignum_byte(out, bytes - 2) != 1)
  635. toret = false;
  636. /* Most of the rest should be FF. */
  637. for (i = bytes - 3; i >= 20 + SHA1_ASN1_PREFIX_LEN; i--) {
  638. if (bignum_byte(out, i) != 0xFF)
  639. toret = false;
  640. }
  641. /* Then we expect to see the sha1_asn1_prefix. */
  642. for (i = 20 + SHA1_ASN1_PREFIX_LEN - 1, j = 0; i >= 20; i--, j++) {
  643. if (bignum_byte(out, i) != sha1_asn1_prefix[j])
  644. toret = false;
  645. }
  646. /* Finally, we expect to see the SHA-1 hash of the signed data. */
  647. SHA_Simple(data.ptr, data.len, hash);
  648. for (i = 19, j = 0; i >= 0; i--, j++) {
  649. if (bignum_byte(out, i) != hash[j])
  650. toret = false;
  651. }
  652. freebn(out);
  653. return toret;
  654. }
  655. static void rsa2_sign(ssh_key *key, const void *data, int datalen,
  656. unsigned flags, BinarySink *bs)
  657. {
  658. struct RSAKey *rsa = container_of(key, struct RSAKey, sshk);
  659. unsigned char *bytes;
  660. int nbytes;
  661. unsigned char hash[64];
  662. Bignum in, out;
  663. int i, j;
  664. const struct ssh_hashalg *halg;
  665. ssh_hash *h;
  666. const unsigned char *asn1_prefix;
  667. unsigned asn1_prefix_size;
  668. const char *sign_alg_name;
  669. if (flags & SSH_AGENT_RSA_SHA2_256) {
  670. halg = &ssh_sha256;
  671. asn1_prefix = sha256_asn1_prefix;
  672. asn1_prefix_size = sizeof(sha256_asn1_prefix);
  673. sign_alg_name = "rsa-sha2-256";
  674. } else if (flags & SSH_AGENT_RSA_SHA2_512) {
  675. halg = &ssh_sha512;
  676. asn1_prefix = sha512_asn1_prefix;
  677. asn1_prefix_size = sizeof(sha512_asn1_prefix);
  678. sign_alg_name = "rsa-sha2-512";
  679. } else {
  680. halg = &ssh_sha1;
  681. asn1_prefix = sha1_asn1_prefix;
  682. asn1_prefix_size = sizeof(sha1_asn1_prefix);
  683. sign_alg_name = "ssh-rsa";
  684. }
  685. h = ssh_hash_new(halg);
  686. put_data(h, data, datalen);
  687. ssh_hash_final(h, hash);
  688. nbytes = (bignum_bitcount(rsa->modulus) - 1) / 8;
  689. assert(1 <= nbytes - halg->hlen - asn1_prefix_size);
  690. bytes = snewn(nbytes, unsigned char);
  691. bytes[0] = 1;
  692. for (i = 1; i < nbytes - halg->hlen - asn1_prefix_size; i++)
  693. bytes[i] = 0xFF;
  694. for (i = nbytes - halg->hlen - asn1_prefix_size, j = 0;
  695. i < nbytes - halg->hlen; i++, j++)
  696. bytes[i] = asn1_prefix[j];
  697. for (i = nbytes - halg->hlen, j = 0; i < nbytes; i++, j++)
  698. bytes[i] = hash[j];
  699. in = bignum_from_bytes(bytes, nbytes);
  700. sfree(bytes);
  701. out = rsa_privkey_op(in, rsa);
  702. freebn(in);
  703. put_stringz(bs, sign_alg_name);
  704. nbytes = (bignum_bitcount(out) + 7) / 8;
  705. put_uint32(bs, nbytes);
  706. for (i = 0; i < nbytes; i++)
  707. put_byte(bs, bignum_byte(out, nbytes - 1 - i));
  708. freebn(out);
  709. }
  710. const ssh_keyalg ssh_rsa = {
  711. rsa2_new_pub,
  712. rsa2_new_priv,
  713. rsa2_new_priv_openssh,
  714. rsa2_freekey,
  715. rsa2_sign,
  716. rsa2_verify,
  717. rsa2_public_blob,
  718. rsa2_private_blob,
  719. rsa2_openssh_blob,
  720. rsa2_cache_str,
  721. rsa2_pubkey_bits,
  722. "ssh-rsa",
  723. "rsa2",
  724. NULL,
  725. SSH_AGENT_RSA_SHA2_256 | SSH_AGENT_RSA_SHA2_512,
  726. };
  727. struct RSAKey *ssh_rsakex_newkey(const void *data, int len)
  728. {
  729. ssh_key *sshk = rsa2_new_pub(&ssh_rsa, make_ptrlen(data, len));
  730. if (!sshk)
  731. return NULL;
  732. return container_of(sshk, struct RSAKey, sshk);
  733. }
  734. void ssh_rsakex_freekey(struct RSAKey *key)
  735. {
  736. rsa2_freekey(&key->sshk);
  737. }
  738. int ssh_rsakex_klen(struct RSAKey *rsa)
  739. {
  740. return bignum_bitcount(rsa->modulus);
  741. }
  742. static void oaep_mask(const struct ssh_hashalg *h, void *seed, int seedlen,
  743. void *vdata, int datalen)
  744. {
  745. unsigned char *data = (unsigned char *)vdata;
  746. unsigned count = 0;
  747. while (datalen > 0) {
  748. int i, max = (datalen > h->hlen ? h->hlen : datalen);
  749. ssh_hash *s;
  750. unsigned char hash[SSH2_KEX_MAX_HASH_LEN];
  751. assert(h->hlen <= SSH2_KEX_MAX_HASH_LEN);
  752. s = ssh_hash_new(h);
  753. put_data(s, seed, seedlen);
  754. put_uint32(s, count);
  755. ssh_hash_final(s, hash);
  756. count++;
  757. for (i = 0; i < max; i++)
  758. data[i] ^= hash[i];
  759. data += max;
  760. datalen -= max;
  761. }
  762. }
  763. void ssh_rsakex_encrypt(const struct ssh_hashalg *h,
  764. unsigned char *in, int inlen,
  765. unsigned char *out, int outlen, struct RSAKey *rsa)
  766. {
  767. Bignum b1, b2;
  768. int k, i;
  769. char *p;
  770. const int HLEN = h->hlen;
  771. /*
  772. * Here we encrypt using RSAES-OAEP. Essentially this means:
  773. *
  774. * - we have a SHA-based `mask generation function' which
  775. * creates a pseudo-random stream of mask data
  776. * deterministically from an input chunk of data.
  777. *
  778. * - we have a random chunk of data called a seed.
  779. *
  780. * - we use the seed to generate a mask which we XOR with our
  781. * plaintext.
  782. *
  783. * - then we use _the masked plaintext_ to generate a mask
  784. * which we XOR with the seed.
  785. *
  786. * - then we concatenate the masked seed and the masked
  787. * plaintext, and RSA-encrypt that lot.
  788. *
  789. * The result is that the data input to the encryption function
  790. * is random-looking and (hopefully) contains no exploitable
  791. * structure such as PKCS1-v1_5 does.
  792. *
  793. * For a precise specification, see RFC 3447, section 7.1.1.
  794. * Some of the variable names below are derived from that, so
  795. * it'd probably help to read it anyway.
  796. */
  797. /* k denotes the length in octets of the RSA modulus. */
  798. k = (7 + bignum_bitcount(rsa->modulus)) / 8;
  799. /* The length of the input data must be at most k - 2hLen - 2. */
  800. assert(inlen > 0 && inlen <= k - 2*HLEN - 2);
  801. /* The length of the output data wants to be precisely k. */
  802. assert(outlen == k);
  803. /*
  804. * Now perform EME-OAEP encoding. First set up all the unmasked
  805. * output data.
  806. */
  807. /* Leading byte zero. */
  808. out[0] = 0;
  809. /* At position 1, the seed: HLEN bytes of random data. */
  810. for (i = 0; i < HLEN; i++)
  811. out[i + 1] = random_byte();
  812. /* At position 1+HLEN, the data block DB, consisting of: */
  813. /* The hash of the label (we only support an empty label here) */
  814. {
  815. ssh_hash *s = ssh_hash_new(h);
  816. ssh_hash_final(s, out + HLEN + 1);
  817. }
  818. /* A bunch of zero octets */
  819. memset(out + 2*HLEN + 1, 0, outlen - (2*HLEN + 1));
  820. /* A single 1 octet, followed by the input message data. */
  821. out[outlen - inlen - 1] = 1;
  822. memcpy(out + outlen - inlen, in, inlen);
  823. /*
  824. * Now use the seed data to mask the block DB.
  825. */
  826. oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
  827. /*
  828. * And now use the masked DB to mask the seed itself.
  829. */
  830. oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
  831. /*
  832. * Now `out' contains precisely the data we want to
  833. * RSA-encrypt.
  834. */
  835. b1 = bignum_from_bytes(out, outlen);
  836. b2 = modpow(b1, rsa->exponent, rsa->modulus);
  837. p = (char *)out;
  838. for (i = outlen; i--;) {
  839. *p++ = bignum_byte(b2, i);
  840. }
  841. freebn(b1);
  842. freebn(b2);
  843. /*
  844. * And we're done.
  845. */
  846. }
  847. Bignum ssh_rsakex_decrypt(const struct ssh_hashalg *h, ptrlen ciphertext,
  848. struct RSAKey *rsa)
  849. {
  850. Bignum b1, b2;
  851. int outlen, i;
  852. unsigned char *out;
  853. unsigned char labelhash[64];
  854. ssh_hash *hash;
  855. BinarySource src[1];
  856. const int HLEN = h->hlen;
  857. /*
  858. * Decryption side of the RSA key exchange operation.
  859. */
  860. /* The length of the encrypted data should be exactly the length
  861. * in octets of the RSA modulus.. */
  862. outlen = (7 + bignum_bitcount(rsa->modulus)) / 8;
  863. if (ciphertext.len != outlen)
  864. return NULL;
  865. /* Do the RSA decryption, and extract the result into a byte array. */
  866. b1 = bignum_from_bytes(ciphertext.ptr, ciphertext.len);
  867. b2 = rsa_privkey_op(b1, rsa);
  868. out = snewn(outlen, unsigned char);
  869. for (i = 0; i < outlen; i++)
  870. out[i] = bignum_byte(b2, outlen-1-i);
  871. freebn(b1);
  872. freebn(b2);
  873. /* Do the OAEP masking operations, in the reverse order from encryption */
  874. oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
  875. oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
  876. /* Check the leading byte is zero. */
  877. if (out[0] != 0) {
  878. sfree(out);
  879. return NULL;
  880. }
  881. /* Check the label hash at position 1+HLEN */
  882. assert(HLEN <= lenof(labelhash));
  883. hash = ssh_hash_new(h);
  884. ssh_hash_final(hash, labelhash);
  885. if (memcmp(out + HLEN + 1, labelhash, HLEN)) {
  886. sfree(out);
  887. return NULL;
  888. }
  889. /* Expect zero bytes followed by a 1 byte */
  890. for (i = 1 + 2 * HLEN; i < outlen; i++) {
  891. if (out[i] == 1) {
  892. i++; /* skip over the 1 byte */
  893. break;
  894. } else if (out[i] != 1) {
  895. sfree(out);
  896. return NULL;
  897. }
  898. }
  899. /* And what's left is the input message data, which should be
  900. * encoded as an ordinary SSH-2 mpint. */
  901. BinarySource_BARE_INIT(src, out + i, outlen - i);
  902. b1 = get_mp_ssh2(src);
  903. sfree(out);
  904. if (get_err(src) || get_avail(src) != 0) {
  905. freebn(b1);
  906. return NULL;
  907. }
  908. /* Success! */
  909. return b1;
  910. }
  911. static const struct ssh_rsa_kex_extra ssh_rsa_kex_extra_sha1 = { 1024 };
  912. static const struct ssh_rsa_kex_extra ssh_rsa_kex_extra_sha256 = { 2048 };
  913. static const struct ssh_kex ssh_rsa_kex_sha1 = {
  914. "rsa1024-sha1", NULL, KEXTYPE_RSA,
  915. &ssh_sha1, &ssh_rsa_kex_extra_sha1,
  916. };
  917. static const struct ssh_kex ssh_rsa_kex_sha256 = {
  918. "rsa2048-sha256", NULL, KEXTYPE_RSA,
  919. &ssh_sha256, &ssh_rsa_kex_extra_sha256,
  920. };
  921. static const struct ssh_kex *const rsa_kex_list[] = {
  922. &ssh_rsa_kex_sha256,
  923. &ssh_rsa_kex_sha1
  924. };
  925. const struct ssh_kexes ssh_rsa_kex = {
  926. sizeof(rsa_kex_list) / sizeof(*rsa_kex_list),
  927. rsa_kex_list
  928. };