sshrsa.c 31 KB

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