sshrsa.c 27 KB

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