sshrsa.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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 "mpint.h"
  10. #include "misc.h"
  11. void BinarySource_get_rsa_ssh1_pub(
  12. BinarySource *src, RSAKey *rsa, RsaSsh1Order order)
  13. {
  14. unsigned bits;
  15. mp_int *e, *m;
  16. bits = get_uint32(src);
  17. if (order == RSA_SSH1_EXPONENT_FIRST) {
  18. e = get_mp_ssh1(src);
  19. m = get_mp_ssh1(src);
  20. } else {
  21. m = get_mp_ssh1(src);
  22. e = get_mp_ssh1(src);
  23. }
  24. if (rsa) {
  25. rsa->bits = bits;
  26. rsa->exponent = e;
  27. rsa->modulus = m;
  28. rsa->bytes = (mp_get_nbits(m) + 7) / 8;
  29. } else {
  30. mp_free(e);
  31. mp_free(m);
  32. }
  33. }
  34. void BinarySource_get_rsa_ssh1_priv(
  35. BinarySource *src, RSAKey *rsa)
  36. {
  37. rsa->private_exponent = get_mp_ssh1(src);
  38. }
  39. bool rsa_ssh1_encrypt(unsigned char *data, int length, RSAKey *key)
  40. {
  41. mp_int *b1, *b2;
  42. int i;
  43. unsigned char *p;
  44. if (key->bytes < length + 4)
  45. return false; /* RSA key too short! */
  46. memmove(data + key->bytes - length, data, length);
  47. data[0] = 0;
  48. data[1] = 2;
  49. size_t npad = key->bytes - length - 3;
  50. /*
  51. * Generate a sequence of nonzero padding bytes. We do this in a
  52. * reasonably uniform way and without having to loop round
  53. * retrying the random number generation, by first generating an
  54. * integer in [0,2^n) for an appropriately large n; then we
  55. * repeatedly multiply by 255 to give an integer in [0,255*2^n),
  56. * extract the top 8 bits to give an integer in [0,255), and mask
  57. * those bits off before multiplying up again for the next digit.
  58. * This gives us a sequence of numbers in [0,255), and of course
  59. * adding 1 to each of them gives numbers in [1,256) as we wanted.
  60. *
  61. * (You could imagine this being a sort of fixed-point operation:
  62. * given a uniformly random binary _fraction_, multiplying it by k
  63. * and subtracting off the integer part will yield you a sequence
  64. * of integers each in [0,k). I'm just doing that scaled up by a
  65. * power of 2 to avoid the fractions.)
  66. */
  67. size_t random_bits = (npad + 16) * 8;
  68. mp_int *randval = mp_new(random_bits + 8);
  69. mp_int *tmp = mp_random_bits(random_bits);
  70. mp_copy_into(randval, tmp);
  71. mp_free(tmp);
  72. for (i = 2; i < key->bytes - length - 1; i++) {
  73. mp_mul_integer_into(randval, randval, 255);
  74. uint8_t byte = mp_get_byte(randval, random_bits / 8);
  75. assert(byte != 255);
  76. data[i] = byte + 1;
  77. mp_reduce_mod_2to(randval, random_bits);
  78. }
  79. mp_free(randval);
  80. data[key->bytes - length - 1] = 0;
  81. b1 = mp_from_bytes_be(make_ptrlen(data, key->bytes));
  82. b2 = mp_modpow(b1, key->exponent, key->modulus);
  83. p = data;
  84. for (i = key->bytes; i--;) {
  85. *p++ = mp_get_byte(b2, i);
  86. }
  87. mp_free(b1);
  88. mp_free(b2);
  89. return true;
  90. }
  91. /*
  92. * Compute (base ^ exp) % mod, provided mod == p * q, with p,q
  93. * distinct primes, and iqmp is the multiplicative inverse of q mod p.
  94. * Uses Chinese Remainder Theorem to speed computation up over the
  95. * obvious implementation of a single big modpow.
  96. */
  97. mp_int *crt_modpow(mp_int *base, mp_int *exp, mp_int *mod,
  98. mp_int *p, mp_int *q, mp_int *iqmp)
  99. {
  100. mp_int *pm1, *qm1, *pexp, *qexp, *presult, *qresult;
  101. mp_int *diff, *multiplier, *ret0, *ret;
  102. /*
  103. * Reduce the exponent mod phi(p) and phi(q), to save time when
  104. * exponentiating mod p and mod q respectively. Of course, since p
  105. * and q are prime, phi(p) == p-1 and similarly for q.
  106. */
  107. pm1 = mp_copy(p);
  108. mp_sub_integer_into(pm1, pm1, 1);
  109. qm1 = mp_copy(q);
  110. mp_sub_integer_into(qm1, qm1, 1);
  111. pexp = mp_mod(exp, pm1);
  112. qexp = mp_mod(exp, qm1);
  113. /*
  114. * Do the two modpows.
  115. */
  116. mp_int *base_mod_p = mp_mod(base, p);
  117. presult = mp_modpow(base_mod_p, pexp, p);
  118. mp_free(base_mod_p);
  119. mp_int *base_mod_q = mp_mod(base, q);
  120. qresult = mp_modpow(base_mod_q, qexp, q);
  121. mp_free(base_mod_q);
  122. /*
  123. * Recombine the results. We want a value which is congruent to
  124. * qresult mod q, and to presult mod p.
  125. *
  126. * We know that iqmp * q is congruent to 1 * mod p (by definition
  127. * of iqmp) and to 0 mod q (obviously). So we start with qresult
  128. * (which is congruent to qresult mod both primes), and add on
  129. * (presult-qresult) * (iqmp * q) which adjusts it to be congruent
  130. * to presult mod p without affecting its value mod q.
  131. *
  132. * (If presult-qresult < 0, we add p to it to keep it positive.)
  133. */
  134. unsigned presult_too_small = mp_cmp_hs(qresult, presult);
  135. mp_cond_add_into(presult, presult, p, presult_too_small);
  136. diff = mp_sub(presult, qresult);
  137. multiplier = mp_mul(iqmp, q);
  138. ret0 = mp_mul(multiplier, diff);
  139. mp_add_into(ret0, ret0, qresult);
  140. /*
  141. * Finally, reduce the result mod n.
  142. */
  143. ret = mp_mod(ret0, mod);
  144. /*
  145. * Free all the intermediate results before returning.
  146. */
  147. mp_free(pm1);
  148. mp_free(qm1);
  149. mp_free(pexp);
  150. mp_free(qexp);
  151. mp_free(presult);
  152. mp_free(qresult);
  153. mp_free(diff);
  154. mp_free(multiplier);
  155. mp_free(ret0);
  156. return ret;
  157. }
  158. /*
  159. * Wrapper on crt_modpow that looks up all the right values from an
  160. * RSAKey.
  161. */
  162. static mp_int *rsa_privkey_op(mp_int *input, RSAKey *key)
  163. {
  164. return crt_modpow(input, key->private_exponent,
  165. key->modulus, key->p, key->q, key->iqmp);
  166. }
  167. mp_int *rsa_ssh1_decrypt(mp_int *input, RSAKey *key)
  168. {
  169. return rsa_privkey_op(input, key);
  170. }
  171. bool rsa_ssh1_decrypt_pkcs1(mp_int *input, RSAKey *key,
  172. strbuf *outbuf)
  173. {
  174. strbuf *data = strbuf_new_nm();
  175. bool success = false;
  176. BinarySource src[1];
  177. {
  178. mp_int *b = rsa_ssh1_decrypt(input, key);
  179. for (size_t i = (mp_get_nbits(key->modulus) + 7) / 8; i-- > 0 ;) {
  180. put_byte(data, mp_get_byte(b, i));
  181. }
  182. mp_free(b);
  183. }
  184. BinarySource_BARE_INIT(src, data->u, data->len);
  185. /* Check PKCS#1 formatting prefix */
  186. if (get_byte(src) != 0) goto out;
  187. if (get_byte(src) != 2) goto out;
  188. while (1) {
  189. unsigned char byte = get_byte(src);
  190. if (get_err(src)) goto out;
  191. if (byte == 0)
  192. break;
  193. }
  194. /* Everything else is the payload */
  195. success = true;
  196. put_data(outbuf, get_ptr(src), get_avail(src));
  197. out:
  198. strbuf_free(data);
  199. return success;
  200. }
  201. static void append_hex_to_strbuf(strbuf *sb, mp_int *x)
  202. {
  203. if (sb->len > 0)
  204. put_byte(sb, ',');
  205. put_data(sb, "0x", 2);
  206. char *hex = mp_get_hex(x);
  207. size_t hexlen = strlen(hex);
  208. put_data(sb, hex, hexlen);
  209. smemclr(hex, hexlen);
  210. sfree(hex);
  211. }
  212. char *rsastr_fmt(RSAKey *key)
  213. {
  214. strbuf *sb = strbuf_new();
  215. append_hex_to_strbuf(sb, key->exponent);
  216. append_hex_to_strbuf(sb, key->modulus);
  217. return strbuf_to_str(sb);
  218. }
  219. /*
  220. * Generate a fingerprint string for the key. Compatible with the
  221. * OpenSSH fingerprint code.
  222. */
  223. char *rsa_ssh1_fingerprint(RSAKey *key)
  224. {
  225. unsigned char digest[16];
  226. strbuf *out;
  227. int i;
  228. /*
  229. * The hash preimage for SSH-1 key fingerprinting consists of the
  230. * modulus and exponent _without_ any preceding length field -
  231. * just the minimum number of bytes to represent each integer,
  232. * stored big-endian, concatenated with no marker at the division
  233. * between them.
  234. */
  235. ssh_hash *hash = ssh_hash_new(&ssh_md5);
  236. for (size_t i = (mp_get_nbits(key->modulus) + 7) / 8; i-- > 0 ;)
  237. put_byte(hash, mp_get_byte(key->modulus, i));
  238. for (size_t i = (mp_get_nbits(key->exponent) + 7) / 8; i-- > 0 ;)
  239. put_byte(hash, mp_get_byte(key->exponent, i));
  240. ssh_hash_final(hash, digest);
  241. out = strbuf_new();
  242. strbuf_catf(out, "%d ", mp_get_nbits(key->modulus));
  243. for (i = 0; i < 16; i++)
  244. strbuf_catf(out, "%s%02x", i ? ":" : "", digest[i]);
  245. if (key->comment)
  246. strbuf_catf(out, " %s", key->comment);
  247. return strbuf_to_str(out);
  248. }
  249. /*
  250. * Verify that the public data in an RSA key matches the private
  251. * data. We also check the private data itself: we ensure that p >
  252. * q and that iqmp really is the inverse of q mod p.
  253. */
  254. bool rsa_verify(RSAKey *key)
  255. {
  256. mp_int *n, *ed, *pm1, *qm1;
  257. unsigned ok = 1;
  258. /* Preliminary checks: p,q must actually be nonzero. */
  259. if (mp_eq_integer(key->p, 0) | mp_eq_integer(key->q, 0))
  260. return false;
  261. /* n must equal pq. */
  262. n = mp_mul(key->p, key->q);
  263. ok &= mp_cmp_eq(n, key->modulus);
  264. mp_free(n);
  265. /* e * d must be congruent to 1, modulo (p-1) and modulo (q-1). */
  266. pm1 = mp_copy(key->p);
  267. mp_sub_integer_into(pm1, pm1, 1);
  268. ed = mp_modmul(key->exponent, key->private_exponent, pm1);
  269. mp_free(pm1);
  270. ok &= mp_eq_integer(ed, 1);
  271. mp_free(ed);
  272. qm1 = mp_copy(key->q);
  273. mp_sub_integer_into(qm1, qm1, 1);
  274. ed = mp_modmul(key->exponent, key->private_exponent, qm1);
  275. mp_free(qm1);
  276. ok &= mp_eq_integer(ed, 1);
  277. mp_free(ed);
  278. /*
  279. * Ensure p > q.
  280. *
  281. * I have seen key blobs in the wild which were generated with
  282. * p < q, so instead of rejecting the key in this case we
  283. * should instead flip them round into the canonical order of
  284. * p > q. This also involves regenerating iqmp.
  285. */
  286. mp_int *p_new = mp_max(key->p, key->q);
  287. mp_int *q_new = mp_min(key->p, key->q);
  288. mp_free(key->p);
  289. mp_free(key->q);
  290. mp_free(key->iqmp);
  291. key->p = p_new;
  292. key->q = q_new;
  293. key->iqmp = mp_invert(key->q, key->p);
  294. return ok;
  295. }
  296. void rsa_ssh1_public_blob(BinarySink *bs, RSAKey *key,
  297. RsaSsh1Order order)
  298. {
  299. put_uint32(bs, mp_get_nbits(key->modulus));
  300. if (order == RSA_SSH1_EXPONENT_FIRST) {
  301. put_mp_ssh1(bs, key->exponent);
  302. put_mp_ssh1(bs, key->modulus);
  303. } else {
  304. put_mp_ssh1(bs, key->modulus);
  305. put_mp_ssh1(bs, key->exponent);
  306. }
  307. }
  308. /* Given an SSH-1 public key blob, determine its length. */
  309. int rsa_ssh1_public_blob_len(ptrlen data)
  310. {
  311. BinarySource src[1];
  312. BinarySource_BARE_INIT_PL(src, data);
  313. /* Expect a length word, then exponent and modulus. (It doesn't
  314. * even matter which order.) */
  315. get_uint32(src);
  316. mp_free(get_mp_ssh1(src));
  317. mp_free(get_mp_ssh1(src));
  318. if (get_err(src))
  319. return -1;
  320. /* Return the number of bytes consumed. */
  321. return src->pos;
  322. }
  323. void freersapriv(RSAKey *key)
  324. {
  325. if (key->private_exponent) {
  326. mp_free(key->private_exponent);
  327. key->private_exponent = NULL;
  328. }
  329. if (key->p) {
  330. mp_free(key->p);
  331. key->p = NULL;
  332. }
  333. if (key->q) {
  334. mp_free(key->q);
  335. key->q = NULL;
  336. }
  337. if (key->iqmp) {
  338. mp_free(key->iqmp);
  339. key->iqmp = NULL;
  340. }
  341. }
  342. void freersakey(RSAKey *key)
  343. {
  344. freersapriv(key);
  345. if (key->modulus) {
  346. mp_free(key->modulus);
  347. key->modulus = NULL;
  348. }
  349. if (key->exponent) {
  350. mp_free(key->exponent);
  351. key->exponent = NULL;
  352. }
  353. if (key->comment) {
  354. sfree(key->comment);
  355. key->comment = NULL;
  356. }
  357. }
  358. /* ----------------------------------------------------------------------
  359. * Implementation of the ssh-rsa signing key type.
  360. */
  361. static void rsa2_freekey(ssh_key *key); /* forward reference */
  362. static ssh_key *rsa2_new_pub(const ssh_keyalg *self, ptrlen data)
  363. {
  364. BinarySource src[1];
  365. RSAKey *rsa;
  366. BinarySource_BARE_INIT_PL(src, data);
  367. if (!ptrlen_eq_string(get_string(src), "ssh-rsa"))
  368. return NULL;
  369. rsa = snew(RSAKey);
  370. rsa->sshk.vt = &ssh_rsa;
  371. rsa->exponent = get_mp_ssh2(src);
  372. rsa->modulus = get_mp_ssh2(src);
  373. rsa->private_exponent = NULL;
  374. rsa->p = rsa->q = rsa->iqmp = NULL;
  375. rsa->comment = NULL;
  376. if (get_err(src)) {
  377. rsa2_freekey(&rsa->sshk);
  378. return NULL;
  379. }
  380. return &rsa->sshk;
  381. }
  382. static void rsa2_freekey(ssh_key *key)
  383. {
  384. RSAKey *rsa = container_of(key, RSAKey, sshk);
  385. freersakey(rsa);
  386. sfree(rsa);
  387. }
  388. static char *rsa2_cache_str(ssh_key *key)
  389. {
  390. RSAKey *rsa = container_of(key, RSAKey, sshk);
  391. return rsastr_fmt(rsa);
  392. }
  393. static void rsa2_public_blob(ssh_key *key, BinarySink *bs)
  394. {
  395. RSAKey *rsa = container_of(key, RSAKey, sshk);
  396. put_stringz(bs, "ssh-rsa");
  397. put_mp_ssh2(bs, rsa->exponent);
  398. put_mp_ssh2(bs, rsa->modulus);
  399. }
  400. static void rsa2_private_blob(ssh_key *key, BinarySink *bs)
  401. {
  402. RSAKey *rsa = container_of(key, RSAKey, sshk);
  403. put_mp_ssh2(bs, rsa->private_exponent);
  404. put_mp_ssh2(bs, rsa->p);
  405. put_mp_ssh2(bs, rsa->q);
  406. put_mp_ssh2(bs, rsa->iqmp);
  407. }
  408. static ssh_key *rsa2_new_priv(const ssh_keyalg *self,
  409. ptrlen pub, ptrlen priv)
  410. {
  411. BinarySource src[1];
  412. ssh_key *sshk;
  413. RSAKey *rsa;
  414. sshk = rsa2_new_pub(self, pub);
  415. if (!sshk)
  416. return NULL;
  417. rsa = container_of(sshk, RSAKey, sshk);
  418. BinarySource_BARE_INIT_PL(src, priv);
  419. rsa->private_exponent = get_mp_ssh2(src);
  420. rsa->p = get_mp_ssh2(src);
  421. rsa->q = get_mp_ssh2(src);
  422. rsa->iqmp = get_mp_ssh2(src);
  423. if (get_err(src) || !rsa_verify(rsa)) {
  424. rsa2_freekey(&rsa->sshk);
  425. return NULL;
  426. }
  427. return &rsa->sshk;
  428. }
  429. static ssh_key *rsa2_new_priv_openssh(const ssh_keyalg *self,
  430. BinarySource *src)
  431. {
  432. RSAKey *rsa;
  433. rsa = snew(RSAKey);
  434. rsa->sshk.vt = &ssh_rsa;
  435. rsa->comment = NULL;
  436. rsa->modulus = get_mp_ssh2(src);
  437. rsa->exponent = get_mp_ssh2(src);
  438. rsa->private_exponent = get_mp_ssh2(src);
  439. rsa->iqmp = get_mp_ssh2(src);
  440. rsa->p = get_mp_ssh2(src);
  441. rsa->q = get_mp_ssh2(src);
  442. if (get_err(src) || !rsa_verify(rsa)) {
  443. rsa2_freekey(&rsa->sshk);
  444. return NULL;
  445. }
  446. return &rsa->sshk;
  447. }
  448. static void rsa2_openssh_blob(ssh_key *key, BinarySink *bs)
  449. {
  450. RSAKey *rsa = container_of(key, RSAKey, sshk);
  451. put_mp_ssh2(bs, rsa->modulus);
  452. put_mp_ssh2(bs, rsa->exponent);
  453. put_mp_ssh2(bs, rsa->private_exponent);
  454. put_mp_ssh2(bs, rsa->iqmp);
  455. put_mp_ssh2(bs, rsa->p);
  456. put_mp_ssh2(bs, rsa->q);
  457. }
  458. static int rsa2_pubkey_bits(const ssh_keyalg *self, ptrlen pub)
  459. {
  460. ssh_key *sshk;
  461. RSAKey *rsa;
  462. int ret;
  463. sshk = rsa2_new_pub(self, pub);
  464. if (!sshk)
  465. return -1;
  466. rsa = container_of(sshk, RSAKey, sshk);
  467. ret = mp_get_nbits(rsa->modulus);
  468. rsa2_freekey(&rsa->sshk);
  469. return ret;
  470. }
  471. static inline const ssh_hashalg *rsa2_hash_alg_for_flags(
  472. unsigned flags, const char **protocol_id_out)
  473. {
  474. const ssh_hashalg *halg;
  475. const char *protocol_id;
  476. if (flags & SSH_AGENT_RSA_SHA2_256) {
  477. halg = &ssh_sha256;
  478. protocol_id = "rsa-sha2-256";
  479. } else if (flags & SSH_AGENT_RSA_SHA2_512) {
  480. halg = &ssh_sha512;
  481. protocol_id = "rsa-sha2-512";
  482. } else {
  483. halg = &ssh_sha1;
  484. protocol_id = "ssh-rsa";
  485. }
  486. if (protocol_id_out)
  487. *protocol_id_out = protocol_id;
  488. return halg;
  489. }
  490. static inline ptrlen rsa_pkcs1_prefix_for_hash(const ssh_hashalg *halg)
  491. {
  492. if (halg == &ssh_sha1) {
  493. /*
  494. * This is the magic ASN.1/DER prefix that goes in the decoded
  495. * signature, between the string of FFs and the actual SHA-1
  496. * hash value. The meaning of it is:
  497. *
  498. * 00 -- this marks the end of the FFs; not part of the ASN.1
  499. * bit itself
  500. *
  501. * 30 21 -- a constructed SEQUENCE of length 0x21
  502. * 30 09 -- a constructed sub-SEQUENCE of length 9
  503. * 06 05 -- an object identifier, length 5
  504. * 2B 0E 03 02 1A -- object id { 1 3 14 3 2 26 }
  505. * (the 1,3 comes from 0x2B = 43 = 40*1+3)
  506. * 05 00 -- NULL
  507. * 04 14 -- a primitive OCTET STRING of length 0x14
  508. * [0x14 bytes of hash data follows]
  509. *
  510. * The object id in the middle there is listed as `id-sha1' in
  511. * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1d2.asn
  512. * (the ASN module for PKCS #1) and its expanded form is as
  513. * follows:
  514. *
  515. * id-sha1 OBJECT IDENTIFIER ::= {
  516. * iso(1) identified-organization(3) oiw(14) secsig(3)
  517. * algorithms(2) 26 }
  518. */
  519. static const unsigned char sha1_asn1_prefix[] = {
  520. 0x00, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
  521. 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
  522. };
  523. return PTRLEN_FROM_CONST_BYTES(sha1_asn1_prefix);
  524. }
  525. if (halg == &ssh_sha256) {
  526. /*
  527. * A similar piece of ASN.1 used for signatures using SHA-256,
  528. * in the same format but differing only in various length
  529. * fields and OID.
  530. */
  531. static const unsigned char sha256_asn1_prefix[] = {
  532. 0x00, 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60,
  533. 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
  534. 0x05, 0x00, 0x04, 0x20,
  535. };
  536. return PTRLEN_FROM_CONST_BYTES(sha256_asn1_prefix);
  537. }
  538. if (halg == &ssh_sha512) {
  539. /*
  540. * And one more for SHA-512.
  541. */
  542. static const unsigned char sha512_asn1_prefix[] = {
  543. 0x00, 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60,
  544. 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
  545. 0x05, 0x00, 0x04, 0x40,
  546. };
  547. return PTRLEN_FROM_CONST_BYTES(sha512_asn1_prefix);
  548. }
  549. unreachable("bad hash algorithm for RSA PKCS#1");
  550. }
  551. static inline size_t rsa_pkcs1_length_of_fixed_parts(const ssh_hashalg *halg)
  552. {
  553. ptrlen asn1_prefix = rsa_pkcs1_prefix_for_hash(halg);
  554. return halg->hlen + asn1_prefix.len + 2;
  555. }
  556. static unsigned char *rsa_pkcs1_signature_string(
  557. size_t nbytes, const ssh_hashalg *halg, ptrlen data)
  558. {
  559. size_t fixed_parts = rsa_pkcs1_length_of_fixed_parts(halg);
  560. assert(nbytes >= fixed_parts);
  561. size_t padding = nbytes - fixed_parts;
  562. ptrlen asn1_prefix = rsa_pkcs1_prefix_for_hash(halg);
  563. unsigned char *bytes = snewn(nbytes, unsigned char);
  564. bytes[0] = 0;
  565. bytes[1] = 1;
  566. memset(bytes + 2, 0xFF, padding);
  567. memcpy(bytes + 2 + padding, asn1_prefix.ptr, asn1_prefix.len);
  568. ssh_hash *h = ssh_hash_new(halg);
  569. put_datapl(h, data);
  570. ssh_hash_final(h, bytes + 2 + padding + asn1_prefix.len);
  571. return bytes;
  572. }
  573. static bool rsa2_verify(ssh_key *key, ptrlen sig, ptrlen data)
  574. {
  575. RSAKey *rsa = container_of(key, RSAKey, sshk);
  576. BinarySource src[1];
  577. ptrlen type, in_pl;
  578. mp_int *in, *out;
  579. /* If we need to support variable flags on verify, this is where they go */
  580. const ssh_hashalg *halg = rsa2_hash_alg_for_flags(0, NULL);
  581. /* Start by making sure the key is even long enough to encode a
  582. * signature. If not, everything fails to verify. */
  583. size_t nbytes = (mp_get_nbits(rsa->modulus) + 7) / 8;
  584. if (nbytes < rsa_pkcs1_length_of_fixed_parts(halg))
  585. return false;
  586. BinarySource_BARE_INIT_PL(src, sig);
  587. type = get_string(src);
  588. /*
  589. * RFC 4253 section 6.6: the signature integer in an ssh-rsa
  590. * signature is 'without lengths or padding'. That is, we _don't_
  591. * expect the usual leading zero byte if the topmost bit of the
  592. * first byte is set. (However, because of the possibility of
  593. * BUG_SSH2_RSA_PADDING at the other end, we tolerate it if it's
  594. * there.) So we can't use get_mp_ssh2, which enforces that
  595. * leading-byte scheme; instead we use get_string and
  596. * mp_from_bytes_be, which will tolerate anything.
  597. */
  598. in_pl = get_string(src);
  599. if (get_err(src) || !ptrlen_eq_string(type, "ssh-rsa"))
  600. return false;
  601. in = mp_from_bytes_be(in_pl);
  602. out = mp_modpow(in, rsa->exponent, rsa->modulus);
  603. mp_free(in);
  604. unsigned diff = 0;
  605. unsigned char *bytes = rsa_pkcs1_signature_string(nbytes, halg, data);
  606. for (size_t i = 0; i < nbytes; i++)
  607. diff |= bytes[nbytes-1 - i] ^ mp_get_byte(out, i);
  608. smemclr(bytes, nbytes);
  609. sfree(bytes);
  610. mp_free(out);
  611. return diff == 0;
  612. }
  613. static void rsa2_sign(ssh_key *key, ptrlen data,
  614. unsigned flags, BinarySink *bs)
  615. {
  616. RSAKey *rsa = container_of(key, RSAKey, sshk);
  617. unsigned char *bytes;
  618. size_t nbytes;
  619. mp_int *in, *out;
  620. const ssh_hashalg *halg;
  621. const char *sign_alg_name;
  622. halg = rsa2_hash_alg_for_flags(flags, &sign_alg_name);
  623. nbytes = (mp_get_nbits(rsa->modulus) + 7) / 8;
  624. bytes = rsa_pkcs1_signature_string(nbytes, halg, data);
  625. in = mp_from_bytes_be(make_ptrlen(bytes, nbytes));
  626. smemclr(bytes, nbytes);
  627. sfree(bytes);
  628. out = rsa_privkey_op(in, rsa);
  629. mp_free(in);
  630. put_stringz(bs, sign_alg_name);
  631. nbytes = (mp_get_nbits(out) + 7) / 8;
  632. put_uint32(bs, nbytes);
  633. for (size_t i = 0; i < nbytes; i++)
  634. put_byte(bs, mp_get_byte(out, nbytes - 1 - i));
  635. mp_free(out);
  636. }
  637. char *rsa2_invalid(ssh_key *key, unsigned flags)
  638. {
  639. RSAKey *rsa = container_of(key, RSAKey, sshk);
  640. size_t bits = mp_get_nbits(rsa->modulus), nbytes = (bits + 7) / 8;
  641. const char *sign_alg_name;
  642. const ssh_hashalg *halg = rsa2_hash_alg_for_flags(flags, &sign_alg_name);
  643. if (nbytes < rsa_pkcs1_length_of_fixed_parts(halg)) {
  644. return dupprintf(
  645. "%zu-bit RSA key is too short to generate %s signatures",
  646. bits, sign_alg_name);
  647. }
  648. return NULL;
  649. }
  650. const ssh_keyalg ssh_rsa = {
  651. rsa2_new_pub,
  652. rsa2_new_priv,
  653. rsa2_new_priv_openssh,
  654. rsa2_freekey,
  655. rsa2_invalid,
  656. rsa2_sign,
  657. rsa2_verify,
  658. rsa2_public_blob,
  659. rsa2_private_blob,
  660. rsa2_openssh_blob,
  661. rsa2_cache_str,
  662. rsa2_pubkey_bits,
  663. "ssh-rsa",
  664. "rsa2",
  665. NULL,
  666. SSH_AGENT_RSA_SHA2_256 | SSH_AGENT_RSA_SHA2_512,
  667. };
  668. RSAKey *ssh_rsakex_newkey(ptrlen data)
  669. {
  670. ssh_key *sshk = rsa2_new_pub(&ssh_rsa, data);
  671. if (!sshk)
  672. return NULL;
  673. return container_of(sshk, RSAKey, sshk);
  674. }
  675. void ssh_rsakex_freekey(RSAKey *key)
  676. {
  677. rsa2_freekey(&key->sshk);
  678. }
  679. int ssh_rsakex_klen(RSAKey *rsa)
  680. {
  681. return mp_get_nbits(rsa->modulus);
  682. }
  683. static void oaep_mask(const ssh_hashalg *h, void *seed, int seedlen,
  684. void *vdata, int datalen)
  685. {
  686. unsigned char *data = (unsigned char *)vdata;
  687. unsigned count = 0;
  688. while (datalen > 0) {
  689. int i, max = (datalen > h->hlen ? h->hlen : datalen);
  690. ssh_hash *s;
  691. unsigned char hash[MAX_HASH_LEN];
  692. assert(h->hlen <= MAX_HASH_LEN);
  693. s = ssh_hash_new(h);
  694. put_data(s, seed, seedlen);
  695. put_uint32(s, count);
  696. ssh_hash_final(s, hash);
  697. count++;
  698. for (i = 0; i < max; i++)
  699. data[i] ^= hash[i];
  700. data += max;
  701. datalen -= max;
  702. }
  703. }
  704. strbuf *ssh_rsakex_encrypt(RSAKey *rsa, const ssh_hashalg *h, ptrlen in)
  705. {
  706. mp_int *b1, *b2;
  707. int k, i;
  708. char *p;
  709. const int HLEN = h->hlen;
  710. /*
  711. * Here we encrypt using RSAES-OAEP. Essentially this means:
  712. *
  713. * - we have a SHA-based `mask generation function' which
  714. * creates a pseudo-random stream of mask data
  715. * deterministically from an input chunk of data.
  716. *
  717. * - we have a random chunk of data called a seed.
  718. *
  719. * - we use the seed to generate a mask which we XOR with our
  720. * plaintext.
  721. *
  722. * - then we use _the masked plaintext_ to generate a mask
  723. * which we XOR with the seed.
  724. *
  725. * - then we concatenate the masked seed and the masked
  726. * plaintext, and RSA-encrypt that lot.
  727. *
  728. * The result is that the data input to the encryption function
  729. * is random-looking and (hopefully) contains no exploitable
  730. * structure such as PKCS1-v1_5 does.
  731. *
  732. * For a precise specification, see RFC 3447, section 7.1.1.
  733. * Some of the variable names below are derived from that, so
  734. * it'd probably help to read it anyway.
  735. */
  736. /* k denotes the length in octets of the RSA modulus. */
  737. k = (7 + mp_get_nbits(rsa->modulus)) / 8;
  738. /* The length of the input data must be at most k - 2hLen - 2. */
  739. assert(in.len > 0 && in.len <= k - 2*HLEN - 2);
  740. /* The length of the output data wants to be precisely k. */
  741. strbuf *toret = strbuf_new_nm();
  742. int outlen = k;
  743. unsigned char *out = strbuf_append(toret, outlen);
  744. /*
  745. * Now perform EME-OAEP encoding. First set up all the unmasked
  746. * output data.
  747. */
  748. /* Leading byte zero. */
  749. out[0] = 0;
  750. /* At position 1, the seed: HLEN bytes of random data. */
  751. random_read(out + 1, HLEN);
  752. /* At position 1+HLEN, the data block DB, consisting of: */
  753. /* The hash of the label (we only support an empty label here) */
  754. {
  755. ssh_hash *s = ssh_hash_new(h);
  756. ssh_hash_final(s, out + HLEN + 1);
  757. }
  758. /* A bunch of zero octets */
  759. memset(out + 2*HLEN + 1, 0, outlen - (2*HLEN + 1));
  760. /* A single 1 octet, followed by the input message data. */
  761. out[outlen - in.len - 1] = 1;
  762. memcpy(out + outlen - in.len, in.ptr, in.len);
  763. /*
  764. * Now use the seed data to mask the block DB.
  765. */
  766. oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
  767. /*
  768. * And now use the masked DB to mask the seed itself.
  769. */
  770. oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
  771. /*
  772. * Now `out' contains precisely the data we want to
  773. * RSA-encrypt.
  774. */
  775. b1 = mp_from_bytes_be(make_ptrlen(out, outlen));
  776. b2 = mp_modpow(b1, rsa->exponent, rsa->modulus);
  777. p = (char *)out;
  778. for (i = outlen; i--;) {
  779. *p++ = mp_get_byte(b2, i);
  780. }
  781. mp_free(b1);
  782. mp_free(b2);
  783. /*
  784. * And we're done.
  785. */
  786. return toret;
  787. }
  788. mp_int *ssh_rsakex_decrypt(
  789. RSAKey *rsa, const ssh_hashalg *h, ptrlen ciphertext)
  790. {
  791. mp_int *b1, *b2;
  792. int outlen, i;
  793. unsigned char *out;
  794. unsigned char labelhash[64];
  795. ssh_hash *hash;
  796. BinarySource src[1];
  797. const int HLEN = h->hlen;
  798. /*
  799. * Decryption side of the RSA key exchange operation.
  800. */
  801. /* The length of the encrypted data should be exactly the length
  802. * in octets of the RSA modulus.. */
  803. outlen = (7 + mp_get_nbits(rsa->modulus)) / 8;
  804. if (ciphertext.len != outlen)
  805. return NULL;
  806. /* Do the RSA decryption, and extract the result into a byte array. */
  807. b1 = mp_from_bytes_be(ciphertext);
  808. b2 = rsa_privkey_op(b1, rsa);
  809. out = snewn(outlen, unsigned char);
  810. for (i = 0; i < outlen; i++)
  811. out[i] = mp_get_byte(b2, outlen-1-i);
  812. mp_free(b1);
  813. mp_free(b2);
  814. /* Do the OAEP masking operations, in the reverse order from encryption */
  815. oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
  816. oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
  817. /* Check the leading byte is zero. */
  818. if (out[0] != 0) {
  819. sfree(out);
  820. return NULL;
  821. }
  822. /* Check the label hash at position 1+HLEN */
  823. assert(HLEN <= lenof(labelhash));
  824. hash = ssh_hash_new(h);
  825. ssh_hash_final(hash, labelhash);
  826. if (memcmp(out + HLEN + 1, labelhash, HLEN)) {
  827. sfree(out);
  828. return NULL;
  829. }
  830. /* Expect zero bytes followed by a 1 byte */
  831. for (i = 1 + 2 * HLEN; i < outlen; i++) {
  832. if (out[i] == 1) {
  833. i++; /* skip over the 1 byte */
  834. break;
  835. } else if (out[i] != 1) {
  836. sfree(out);
  837. return NULL;
  838. }
  839. }
  840. /* And what's left is the input message data, which should be
  841. * encoded as an ordinary SSH-2 mpint. */
  842. BinarySource_BARE_INIT(src, out + i, outlen - i);
  843. b1 = get_mp_ssh2(src);
  844. sfree(out);
  845. if (get_err(src) || get_avail(src) != 0) {
  846. mp_free(b1);
  847. return NULL;
  848. }
  849. /* Success! */
  850. return b1;
  851. }
  852. static const struct ssh_rsa_kex_extra ssh_rsa_kex_extra_sha1 = { 1024 };
  853. static const struct ssh_rsa_kex_extra ssh_rsa_kex_extra_sha256 = { 2048 };
  854. static const ssh_kex ssh_rsa_kex_sha1 = {
  855. "rsa1024-sha1", NULL, KEXTYPE_RSA,
  856. &ssh_sha1, &ssh_rsa_kex_extra_sha1,
  857. };
  858. static const ssh_kex ssh_rsa_kex_sha256 = {
  859. "rsa2048-sha256", NULL, KEXTYPE_RSA,
  860. &ssh_sha256, &ssh_rsa_kex_extra_sha256,
  861. };
  862. static const ssh_kex *const rsa_kex_list[] = {
  863. &ssh_rsa_kex_sha256,
  864. &ssh_rsa_kex_sha1
  865. };
  866. const ssh_kexes ssh_rsa_kex = { lenof(rsa_kex_list), rsa_kex_list };