sshrsa.c 27 KB

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