sshrsa.c 29 KB

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