sshrsa.c 26 KB

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