sshrsa.c 26 KB

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