sshrsa.c 26 KB

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