sshrsa.c 26 KB

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