rsa.c 34 KB

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