sshrsa.c 32 KB

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