sshrsa.c 25 KB

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