1
0

sshrsa.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  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. unsigned i; // WINSCP
  301. for (i = 0; i < SSH_N_FPTYPES; i++)
  302. ret[i] = NULL;
  303. ret[SSH_FPTYPE_MD5] = rsa_ssh1_fingerprint(key);
  304. return ret;
  305. }
  306. /*
  307. * Verify that the public data in an RSA key matches the private
  308. * data. We also check the private data itself: we ensure that p >
  309. * q and that iqmp really is the inverse of q mod p.
  310. */
  311. bool rsa_verify(RSAKey *key)
  312. {
  313. mp_int *n, *ed, *pm1, *qm1;
  314. unsigned ok = 1;
  315. /* Preliminary checks: p,q can't be 0 or 1. (Of course no other
  316. * very small value is any good either, but these are the values
  317. * we _must_ check for to avoid assertion failures further down
  318. * this function.) */
  319. if (!(mp_hs_integer(key->p, 2) & mp_hs_integer(key->q, 2)))
  320. return false;
  321. /* n must equal pq. */
  322. n = mp_mul(key->p, key->q);
  323. ok &= mp_cmp_eq(n, key->modulus);
  324. mp_free(n);
  325. /* e * d must be congruent to 1, modulo (p-1) and modulo (q-1). */
  326. pm1 = mp_copy(key->p);
  327. mp_sub_integer_into(pm1, pm1, 1);
  328. ed = mp_modmul(key->exponent, key->private_exponent, pm1);
  329. mp_free(pm1);
  330. ok &= mp_eq_integer(ed, 1);
  331. mp_free(ed);
  332. qm1 = mp_copy(key->q);
  333. mp_sub_integer_into(qm1, qm1, 1);
  334. ed = mp_modmul(key->exponent, key->private_exponent, qm1);
  335. mp_free(qm1);
  336. ok &= mp_eq_integer(ed, 1);
  337. mp_free(ed);
  338. /*
  339. * Ensure p > q.
  340. *
  341. * I have seen key blobs in the wild which were generated with
  342. * p < q, so instead of rejecting the key in this case we
  343. * should instead flip them round into the canonical order of
  344. * p > q. This also involves regenerating iqmp.
  345. */
  346. { // WINSCP
  347. mp_int *p_new = mp_max(key->p, key->q);
  348. mp_int *q_new = mp_min(key->p, key->q);
  349. mp_free(key->p);
  350. mp_free(key->q);
  351. mp_free(key->iqmp);
  352. key->p = p_new;
  353. key->q = q_new;
  354. key->iqmp = mp_invert(key->q, key->p);
  355. return ok;
  356. } // WINSCP
  357. }
  358. void rsa_ssh1_public_blob(BinarySink *bs, RSAKey *key,
  359. RsaSsh1Order order)
  360. {
  361. put_uint32(bs, mp_get_nbits(key->modulus));
  362. if (order == RSA_SSH1_EXPONENT_FIRST) {
  363. put_mp_ssh1(bs, key->exponent);
  364. put_mp_ssh1(bs, key->modulus);
  365. } else {
  366. put_mp_ssh1(bs, key->modulus);
  367. put_mp_ssh1(bs, key->exponent);
  368. }
  369. }
  370. void rsa_ssh1_private_blob_agent(BinarySink *bs, RSAKey *key)
  371. {
  372. rsa_ssh1_public_blob(bs, key, RSA_SSH1_MODULUS_FIRST);
  373. put_mp_ssh1(bs, key->private_exponent);
  374. put_mp_ssh1(bs, key->iqmp);
  375. put_mp_ssh1(bs, key->q);
  376. put_mp_ssh1(bs, key->p);
  377. }
  378. /* Given an SSH-1 public key blob, determine its length. */
  379. int rsa_ssh1_public_blob_len(ptrlen data)
  380. {
  381. BinarySource src[1];
  382. BinarySource_BARE_INIT_PL(src, data);
  383. /* Expect a length word, then exponent and modulus. (It doesn't
  384. * even matter which order.) */
  385. get_uint32(src);
  386. mp_free(get_mp_ssh1(src));
  387. mp_free(get_mp_ssh1(src));
  388. if (get_err(src))
  389. return -1;
  390. /* Return the number of bytes consumed. */
  391. return src->pos;
  392. }
  393. void freersapriv(RSAKey *key)
  394. {
  395. if (key->private_exponent) {
  396. mp_free(key->private_exponent);
  397. key->private_exponent = NULL;
  398. }
  399. if (key->p) {
  400. mp_free(key->p);
  401. key->p = NULL;
  402. }
  403. if (key->q) {
  404. mp_free(key->q);
  405. key->q = NULL;
  406. }
  407. if (key->iqmp) {
  408. mp_free(key->iqmp);
  409. key->iqmp = NULL;
  410. }
  411. }
  412. void freersakey(RSAKey *key)
  413. {
  414. freersapriv(key);
  415. if (key->modulus) {
  416. mp_free(key->modulus);
  417. key->modulus = NULL;
  418. }
  419. if (key->exponent) {
  420. mp_free(key->exponent);
  421. key->exponent = NULL;
  422. }
  423. if (key->comment) {
  424. sfree(key->comment);
  425. key->comment = NULL;
  426. }
  427. }
  428. /* ----------------------------------------------------------------------
  429. * Implementation of the ssh-rsa signing key type family.
  430. */
  431. struct ssh2_rsa_extra {
  432. unsigned signflags;
  433. };
  434. static void rsa2_freekey(ssh_key *key); /* forward reference */
  435. static ssh_key *rsa2_new_pub(const ssh_keyalg *self, ptrlen data)
  436. {
  437. BinarySource src[1];
  438. RSAKey *rsa;
  439. BinarySource_BARE_INIT_PL(src, data);
  440. if (!ptrlen_eq_string(get_string(src), "ssh-rsa"))
  441. return NULL;
  442. rsa = snew(RSAKey);
  443. rsa->sshk.vt = self;
  444. rsa->exponent = get_mp_ssh2(src);
  445. rsa->modulus = get_mp_ssh2(src);
  446. rsa->private_exponent = NULL;
  447. rsa->p = rsa->q = rsa->iqmp = NULL;
  448. rsa->comment = NULL;
  449. if (get_err(src)) {
  450. rsa2_freekey(&rsa->sshk);
  451. return NULL;
  452. }
  453. return &rsa->sshk;
  454. }
  455. static void rsa2_freekey(ssh_key *key)
  456. {
  457. RSAKey *rsa = container_of(key, RSAKey, sshk);
  458. freersakey(rsa);
  459. sfree(rsa);
  460. }
  461. static char *rsa2_cache_str(ssh_key *key)
  462. {
  463. RSAKey *rsa = container_of(key, RSAKey, sshk);
  464. return rsastr_fmt(rsa);
  465. }
  466. static key_components *rsa2_components(ssh_key *key)
  467. {
  468. RSAKey *rsa = container_of(key, RSAKey, sshk);
  469. return rsa_components(rsa);
  470. }
  471. static void rsa2_public_blob(ssh_key *key, BinarySink *bs)
  472. {
  473. RSAKey *rsa = container_of(key, RSAKey, sshk);
  474. put_stringz(bs, "ssh-rsa");
  475. put_mp_ssh2(bs, rsa->exponent);
  476. put_mp_ssh2(bs, rsa->modulus);
  477. }
  478. static void rsa2_private_blob(ssh_key *key, BinarySink *bs)
  479. {
  480. RSAKey *rsa = container_of(key, RSAKey, sshk);
  481. put_mp_ssh2(bs, rsa->private_exponent);
  482. put_mp_ssh2(bs, rsa->p);
  483. put_mp_ssh2(bs, rsa->q);
  484. put_mp_ssh2(bs, rsa->iqmp);
  485. }
  486. static ssh_key *rsa2_new_priv(const ssh_keyalg *self,
  487. ptrlen pub, ptrlen priv)
  488. {
  489. BinarySource src[1];
  490. ssh_key *sshk;
  491. RSAKey *rsa;
  492. sshk = rsa2_new_pub(self, pub);
  493. if (!sshk)
  494. return NULL;
  495. rsa = container_of(sshk, RSAKey, sshk);
  496. BinarySource_BARE_INIT_PL(src, priv);
  497. rsa->private_exponent = get_mp_ssh2(src);
  498. rsa->p = get_mp_ssh2(src);
  499. rsa->q = get_mp_ssh2(src);
  500. rsa->iqmp = get_mp_ssh2(src);
  501. if (get_err(src) || !rsa_verify(rsa)) {
  502. rsa2_freekey(&rsa->sshk);
  503. return NULL;
  504. }
  505. return &rsa->sshk;
  506. }
  507. static ssh_key *rsa2_new_priv_openssh(const ssh_keyalg *self,
  508. BinarySource *src)
  509. {
  510. RSAKey *rsa;
  511. rsa = snew(RSAKey);
  512. rsa->sshk.vt = &ssh_rsa;
  513. rsa->comment = NULL;
  514. rsa->modulus = get_mp_ssh2(src);
  515. rsa->exponent = get_mp_ssh2(src);
  516. rsa->private_exponent = get_mp_ssh2(src);
  517. rsa->iqmp = get_mp_ssh2(src);
  518. rsa->p = get_mp_ssh2(src);
  519. rsa->q = get_mp_ssh2(src);
  520. if (get_err(src) || !rsa_verify(rsa)) {
  521. rsa2_freekey(&rsa->sshk);
  522. return NULL;
  523. }
  524. return &rsa->sshk;
  525. }
  526. static void rsa2_openssh_blob(ssh_key *key, BinarySink *bs)
  527. {
  528. RSAKey *rsa = container_of(key, RSAKey, sshk);
  529. put_mp_ssh2(bs, rsa->modulus);
  530. put_mp_ssh2(bs, rsa->exponent);
  531. put_mp_ssh2(bs, rsa->private_exponent);
  532. put_mp_ssh2(bs, rsa->iqmp);
  533. put_mp_ssh2(bs, rsa->p);
  534. put_mp_ssh2(bs, rsa->q);
  535. }
  536. static int rsa2_pubkey_bits(const ssh_keyalg *self, ptrlen pub)
  537. {
  538. ssh_key *sshk;
  539. RSAKey *rsa;
  540. int ret;
  541. sshk = rsa2_new_pub(self, pub);
  542. if (!sshk)
  543. return -1;
  544. rsa = container_of(sshk, RSAKey, sshk);
  545. ret = mp_get_nbits(rsa->modulus);
  546. rsa2_freekey(&rsa->sshk);
  547. return ret;
  548. }
  549. static inline const ssh_hashalg *rsa2_hash_alg_for_flags(
  550. unsigned flags, const char **protocol_id_out)
  551. {
  552. const ssh_hashalg *halg;
  553. const char *protocol_id;
  554. if (flags & SSH_AGENT_RSA_SHA2_256) {
  555. halg = &ssh_sha256;
  556. protocol_id = "rsa-sha2-256";
  557. } else if (flags & SSH_AGENT_RSA_SHA2_512) {
  558. halg = &ssh_sha512;
  559. protocol_id = "rsa-sha2-512";
  560. } else {
  561. halg = &ssh_sha1;
  562. protocol_id = "ssh-rsa";
  563. }
  564. if (protocol_id_out)
  565. *protocol_id_out = protocol_id;
  566. return halg;
  567. }
  568. static inline ptrlen rsa_pkcs1_prefix_for_hash(const ssh_hashalg *halg)
  569. {
  570. if (halg == &ssh_sha1) {
  571. /*
  572. * This is the magic ASN.1/DER prefix that goes in the decoded
  573. * signature, between the string of FFs and the actual SHA-1
  574. * hash value. The meaning of it is:
  575. *
  576. * 00 -- this marks the end of the FFs; not part of the ASN.1
  577. * bit itself
  578. *
  579. * 30 21 -- a constructed SEQUENCE of length 0x21
  580. * 30 09 -- a constructed sub-SEQUENCE of length 9
  581. * 06 05 -- an object identifier, length 5
  582. * 2B 0E 03 02 1A -- object id { 1 3 14 3 2 26 }
  583. * (the 1,3 comes from 0x2B = 43 = 40*1+3)
  584. * 05 00 -- NULL
  585. * 04 14 -- a primitive OCTET STRING of length 0x14
  586. * [0x14 bytes of hash data follows]
  587. *
  588. * The object id in the middle there is listed as `id-sha1' in
  589. * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1d2.asn
  590. * (the ASN module for PKCS #1) and its expanded form is as
  591. * follows:
  592. *
  593. * id-sha1 OBJECT IDENTIFIER ::= {
  594. * iso(1) identified-organization(3) oiw(14) secsig(3)
  595. * algorithms(2) 26 }
  596. */
  597. static const unsigned char sha1_asn1_prefix[] = {
  598. 0x00, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
  599. 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
  600. };
  601. return PTRLEN_FROM_CONST_BYTES(sha1_asn1_prefix);
  602. }
  603. if (halg == &ssh_sha256) {
  604. /*
  605. * A similar piece of ASN.1 used for signatures using SHA-256,
  606. * in the same format but differing only in various length
  607. * fields and OID.
  608. */
  609. static const unsigned char sha256_asn1_prefix[] = {
  610. 0x00, 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60,
  611. 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
  612. 0x05, 0x00, 0x04, 0x20,
  613. };
  614. return PTRLEN_FROM_CONST_BYTES(sha256_asn1_prefix);
  615. }
  616. if (halg == &ssh_sha512) {
  617. /*
  618. * And one more for SHA-512.
  619. */
  620. static const unsigned char sha512_asn1_prefix[] = {
  621. 0x00, 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60,
  622. 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
  623. 0x05, 0x00, 0x04, 0x40,
  624. };
  625. return PTRLEN_FROM_CONST_BYTES(sha512_asn1_prefix);
  626. }
  627. unreachable("bad hash algorithm for RSA PKCS#1");
  628. }
  629. static inline size_t rsa_pkcs1_length_of_fixed_parts(const ssh_hashalg *halg)
  630. {
  631. ptrlen asn1_prefix = rsa_pkcs1_prefix_for_hash(halg);
  632. return halg->hlen + asn1_prefix.len + 2;
  633. }
  634. static unsigned char *rsa_pkcs1_signature_string(
  635. size_t nbytes, const ssh_hashalg *halg, ptrlen data)
  636. {
  637. size_t fixed_parts = rsa_pkcs1_length_of_fixed_parts(halg);
  638. pinitassert(nbytes >= fixed_parts);
  639. size_t padding = nbytes - fixed_parts;
  640. ptrlen asn1_prefix = rsa_pkcs1_prefix_for_hash(halg);
  641. unsigned char *bytes = snewn(nbytes, unsigned char);
  642. bytes[0] = 0;
  643. bytes[1] = 1;
  644. memset(bytes + 2, 0xFF, padding);
  645. memcpy(bytes + 2 + padding, asn1_prefix.ptr, asn1_prefix.len);
  646. { // WINSCP
  647. ssh_hash *h = ssh_hash_new(halg);
  648. put_datapl(h, data);
  649. ssh_hash_final(h, bytes + 2 + padding + asn1_prefix.len);
  650. } // WINSCP
  651. return bytes;
  652. }
  653. static bool rsa2_verify(ssh_key *key, ptrlen sig, ptrlen data)
  654. {
  655. RSAKey *rsa = container_of(key, RSAKey, sshk);
  656. BinarySource src[1];
  657. ptrlen type, in_pl;
  658. mp_int *in, *out;
  659. const struct ssh2_rsa_extra *extra =
  660. (const struct ssh2_rsa_extra *)key->vt->extra;
  661. const ssh_hashalg *halg = rsa2_hash_alg_for_flags(extra->signflags, NULL);
  662. /* Start by making sure the key is even long enough to encode a
  663. * signature. If not, everything fails to verify. */
  664. size_t nbytes = (mp_get_nbits(rsa->modulus) + 7) / 8;
  665. if (nbytes < rsa_pkcs1_length_of_fixed_parts(halg))
  666. return false;
  667. BinarySource_BARE_INIT_PL(src, sig);
  668. type = get_string(src);
  669. /*
  670. * RFC 4253 section 6.6: the signature integer in an ssh-rsa
  671. * signature is 'without lengths or padding'. That is, we _don't_
  672. * expect the usual leading zero byte if the topmost bit of the
  673. * first byte is set. (However, because of the possibility of
  674. * BUG_SSH2_RSA_PADDING at the other end, we tolerate it if it's
  675. * there.) So we can't use get_mp_ssh2, which enforces that
  676. * leading-byte scheme; instead we use get_string and
  677. * mp_from_bytes_be, which will tolerate anything.
  678. */
  679. in_pl = get_string(src);
  680. if (get_err(src) || !ptrlen_eq_string(type, key->vt->ssh_id))
  681. return false;
  682. in = mp_from_bytes_be(in_pl);
  683. out = mp_modpow(in, rsa->exponent, rsa->modulus);
  684. mp_free(in);
  685. { // WINSCP
  686. unsigned diff = 0;
  687. unsigned char *bytes = rsa_pkcs1_signature_string(nbytes, halg, data);
  688. size_t i; // WINSCP
  689. for (i = 0; i < nbytes; i++)
  690. diff |= bytes[nbytes-1 - i] ^ mp_get_byte(out, i);
  691. smemclr(bytes, nbytes);
  692. sfree(bytes);
  693. mp_free(out);
  694. return diff == 0;
  695. } // WINSCP
  696. }
  697. static void rsa2_sign(ssh_key *key, ptrlen data,
  698. unsigned flags, BinarySink *bs)
  699. {
  700. RSAKey *rsa = container_of(key, RSAKey, sshk);
  701. unsigned char *bytes;
  702. size_t nbytes;
  703. mp_int *in, *out;
  704. const ssh_hashalg *halg;
  705. const char *sign_alg_name;
  706. const struct ssh2_rsa_extra *extra =
  707. (const struct ssh2_rsa_extra *)key->vt->extra;
  708. flags |= extra->signflags;
  709. halg = rsa2_hash_alg_for_flags(flags, &sign_alg_name);
  710. nbytes = (mp_get_nbits(rsa->modulus) + 7) / 8;
  711. bytes = rsa_pkcs1_signature_string(nbytes, halg, data);
  712. in = mp_from_bytes_be(make_ptrlen(bytes, nbytes));
  713. smemclr(bytes, nbytes);
  714. sfree(bytes);
  715. out = rsa_privkey_op(in, rsa);
  716. mp_free(in);
  717. put_stringz(bs, sign_alg_name);
  718. nbytes = (mp_get_nbits(out) + 7) / 8;
  719. put_uint32(bs, nbytes);
  720. { // WINSCP
  721. size_t i; // WINSCP
  722. for (i = 0; i < nbytes; i++)
  723. put_byte(bs, mp_get_byte(out, nbytes - 1 - i));
  724. } // WINSCP
  725. mp_free(out);
  726. }
  727. static char *rsa2_invalid(ssh_key *key, unsigned flags)
  728. {
  729. RSAKey *rsa = container_of(key, RSAKey, sshk);
  730. size_t bits = mp_get_nbits(rsa->modulus), nbytes = (bits + 7) / 8;
  731. const char *sign_alg_name;
  732. const ssh_hashalg *halg = rsa2_hash_alg_for_flags(flags, &sign_alg_name);
  733. if (nbytes < rsa_pkcs1_length_of_fixed_parts(halg)) {
  734. return dupprintf(
  735. "%"SIZEu"-bit RSA key is too short to generate %s signatures",
  736. bits, sign_alg_name);
  737. }
  738. return NULL;
  739. }
  740. static const struct ssh2_rsa_extra
  741. rsa_extra = { 0 },
  742. rsa_sha256_extra = { SSH_AGENT_RSA_SHA2_256 },
  743. rsa_sha512_extra = { SSH_AGENT_RSA_SHA2_512 };
  744. // WINSCP
  745. #define COMMON_KEYALG_FIELDS \
  746. /*.new_pub =*/ rsa2_new_pub, \
  747. /*.new_priv =*/ rsa2_new_priv, \
  748. /*.new_priv_openssh =*/ rsa2_new_priv_openssh, \
  749. /*.freekey =*/ rsa2_freekey, \
  750. /*.invalid =*/ rsa2_invalid, \
  751. /*.sign =*/ rsa2_sign, \
  752. /*.verify =*/ rsa2_verify, \
  753. /*.public_blob =*/ rsa2_public_blob, \
  754. /*.private_blob =*/ rsa2_private_blob, \
  755. /*.openssh_blob =*/ rsa2_openssh_blob, \
  756. /*.cache_str =*/ rsa2_cache_str, \
  757. /*.components =*/ rsa2_components, \
  758. /*.pubkey_bits =*/ rsa2_pubkey_bits
  759. #define COMMON_KEYALG_FIELDS2 \
  760. /*.cache_id =*/ "rsa2"
  761. const ssh_keyalg ssh_rsa = {
  762. // WINSCP
  763. COMMON_KEYALG_FIELDS,
  764. /*.ssh_id =*/ "ssh-rsa",
  765. COMMON_KEYALG_FIELDS2,
  766. /*.extra =*/ &rsa_extra,
  767. /*.supported_flags =*/ SSH_AGENT_RSA_SHA2_256 | SSH_AGENT_RSA_SHA2_512,
  768. };
  769. const ssh_keyalg ssh_rsa_sha256 = {
  770. // WINSCP
  771. COMMON_KEYALG_FIELDS,
  772. /*.ssh_id =*/ "rsa-sha2-256",
  773. COMMON_KEYALG_FIELDS2,
  774. /*.extra =*/ &rsa_sha256_extra,
  775. /*.supported_flags =*/ 0,
  776. };
  777. const ssh_keyalg ssh_rsa_sha512 = {
  778. // WINSCP
  779. COMMON_KEYALG_FIELDS,
  780. /*.ssh_id =*/ "rsa-sha2-512",
  781. COMMON_KEYALG_FIELDS2,
  782. /*.extra =*/ &rsa_sha512_extra,
  783. /*.supported_flags =*/ 0,
  784. };
  785. RSAKey *ssh_rsakex_newkey(ptrlen data)
  786. {
  787. ssh_key *sshk = rsa2_new_pub(&ssh_rsa, data);
  788. if (!sshk)
  789. return NULL;
  790. return container_of(sshk, RSAKey, sshk);
  791. }
  792. void ssh_rsakex_freekey(RSAKey *key)
  793. {
  794. rsa2_freekey(&key->sshk);
  795. }
  796. int ssh_rsakex_klen(RSAKey *rsa)
  797. {
  798. return mp_get_nbits(rsa->modulus);
  799. }
  800. static void oaep_mask(const ssh_hashalg *h, void *seed, int seedlen,
  801. void *vdata, int datalen)
  802. {
  803. unsigned char *data = (unsigned char *)vdata;
  804. unsigned count = 0;
  805. ssh_hash *s = ssh_hash_new(h);
  806. while (datalen > 0) {
  807. int i, max = (datalen > h->hlen ? h->hlen : datalen);
  808. unsigned char hash[MAX_HASH_LEN];
  809. ssh_hash_reset(s);
  810. assert(h->hlen <= MAX_HASH_LEN);
  811. put_data(s, seed, seedlen);
  812. put_uint32(s, count);
  813. ssh_hash_digest(s, hash);
  814. count++;
  815. for (i = 0; i < max; i++)
  816. data[i] ^= hash[i];
  817. data += max;
  818. datalen -= max;
  819. }
  820. ssh_hash_free(s);
  821. }
  822. strbuf *ssh_rsakex_encrypt(RSAKey *rsa, const ssh_hashalg *h, ptrlen in)
  823. {
  824. mp_int *b1, *b2;
  825. int k, i;
  826. char *p;
  827. const int HLEN = h->hlen;
  828. /*
  829. * Here we encrypt using RSAES-OAEP. Essentially this means:
  830. *
  831. * - we have a SHA-based `mask generation function' which
  832. * creates a pseudo-random stream of mask data
  833. * deterministically from an input chunk of data.
  834. *
  835. * - we have a random chunk of data called a seed.
  836. *
  837. * - we use the seed to generate a mask which we XOR with our
  838. * plaintext.
  839. *
  840. * - then we use _the masked plaintext_ to generate a mask
  841. * which we XOR with the seed.
  842. *
  843. * - then we concatenate the masked seed and the masked
  844. * plaintext, and RSA-encrypt that lot.
  845. *
  846. * The result is that the data input to the encryption function
  847. * is random-looking and (hopefully) contains no exploitable
  848. * structure such as PKCS1-v1_5 does.
  849. *
  850. * For a precise specification, see RFC 3447, section 7.1.1.
  851. * Some of the variable names below are derived from that, so
  852. * it'd probably help to read it anyway.
  853. */
  854. /* k denotes the length in octets of the RSA modulus. */
  855. k = (7 + mp_get_nbits(rsa->modulus)) / 8;
  856. /* The length of the input data must be at most k - 2hLen - 2. */
  857. assert(in.len > 0 && in.len <= k - 2*HLEN - 2);
  858. /* The length of the output data wants to be precisely k. */
  859. { // WINSCP
  860. strbuf *toret = strbuf_new_nm();
  861. int outlen = k;
  862. unsigned char *out = strbuf_append(toret, outlen);
  863. /*
  864. * Now perform EME-OAEP encoding. First set up all the unmasked
  865. * output data.
  866. */
  867. /* Leading byte zero. */
  868. out[0] = 0;
  869. /* At position 1, the seed: HLEN bytes of random data. */
  870. random_read(out + 1, HLEN);
  871. /* At position 1+HLEN, the data block DB, consisting of: */
  872. /* The hash of the label (we only support an empty label here) */
  873. hash_simple(h, PTRLEN_LITERAL(""), out + HLEN + 1);
  874. /* A bunch of zero octets */
  875. memset(out + 2*HLEN + 1, 0, outlen - (2*HLEN + 1));
  876. /* A single 1 octet, followed by the input message data. */
  877. out[outlen - in.len - 1] = 1;
  878. memcpy(out + outlen - in.len, in.ptr, in.len);
  879. /*
  880. * Now use the seed data to mask the block DB.
  881. */
  882. oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
  883. /*
  884. * And now use the masked DB to mask the seed itself.
  885. */
  886. oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
  887. /*
  888. * Now `out' contains precisely the data we want to
  889. * RSA-encrypt.
  890. */
  891. b1 = mp_from_bytes_be(make_ptrlen(out, outlen));
  892. b2 = mp_modpow(b1, rsa->exponent, rsa->modulus);
  893. p = (char *)out;
  894. for (i = outlen; i--;) {
  895. *p++ = mp_get_byte(b2, i);
  896. }
  897. mp_free(b1);
  898. mp_free(b2);
  899. /*
  900. * And we're done.
  901. */
  902. return toret;
  903. } // WINSCP
  904. }
  905. mp_int *ssh_rsakex_decrypt(
  906. RSAKey *rsa, const ssh_hashalg *h, ptrlen ciphertext)
  907. {
  908. mp_int *b1, *b2;
  909. int outlen, i;
  910. unsigned char *out;
  911. unsigned char labelhash[64];
  912. BinarySource src[1];
  913. const int HLEN = h->hlen;
  914. /*
  915. * Decryption side of the RSA key exchange operation.
  916. */
  917. /* The length of the encrypted data should be exactly the length
  918. * in octets of the RSA modulus.. */
  919. outlen = (7 + mp_get_nbits(rsa->modulus)) / 8;
  920. if (ciphertext.len != outlen)
  921. return NULL;
  922. /* Do the RSA decryption, and extract the result into a byte array. */
  923. b1 = mp_from_bytes_be(ciphertext);
  924. b2 = rsa_privkey_op(b1, rsa);
  925. out = snewn(outlen, unsigned char);
  926. for (i = 0; i < outlen; i++)
  927. out[i] = mp_get_byte(b2, outlen-1-i);
  928. mp_free(b1);
  929. mp_free(b2);
  930. /* Do the OAEP masking operations, in the reverse order from encryption */
  931. oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
  932. oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
  933. /* Check the leading byte is zero. */
  934. if (out[0] != 0) {
  935. sfree(out);
  936. return NULL;
  937. }
  938. /* Check the label hash at position 1+HLEN */
  939. assert(HLEN <= lenof(labelhash));
  940. hash_simple(h, PTRLEN_LITERAL(""), labelhash);
  941. if (memcmp(out + HLEN + 1, labelhash, HLEN)) {
  942. sfree(out);
  943. return NULL;
  944. }
  945. /* Expect zero bytes followed by a 1 byte */
  946. for (i = 1 + 2 * HLEN; i < outlen; i++) {
  947. if (out[i] == 1) {
  948. i++; /* skip over the 1 byte */
  949. break;
  950. } else if (out[i] != 0) {
  951. sfree(out);
  952. return NULL;
  953. }
  954. }
  955. /* And what's left is the input message data, which should be
  956. * encoded as an ordinary SSH-2 mpint. */
  957. BinarySource_BARE_INIT(src, out + i, outlen - i);
  958. b1 = get_mp_ssh2(src);
  959. sfree(out);
  960. if (get_err(src) || get_avail(src) != 0) {
  961. mp_free(b1);
  962. return NULL;
  963. }
  964. /* Success! */
  965. return b1;
  966. }
  967. static const struct ssh_rsa_kex_extra ssh_rsa_kex_extra_sha1 = { 1024 };
  968. static const struct ssh_rsa_kex_extra ssh_rsa_kex_extra_sha256 = { 2048 };
  969. static const ssh_kex ssh_rsa_kex_sha1 = {
  970. "rsa1024-sha1", NULL, KEXTYPE_RSA,
  971. &ssh_sha1, &ssh_rsa_kex_extra_sha1,
  972. };
  973. static const ssh_kex ssh_rsa_kex_sha256 = {
  974. "rsa2048-sha256", NULL, KEXTYPE_RSA,
  975. &ssh_sha256, &ssh_rsa_kex_extra_sha256,
  976. };
  977. static const ssh_kex *const rsa_kex_list[] = {
  978. &ssh_rsa_kex_sha256,
  979. &ssh_rsa_kex_sha1
  980. };
  981. const ssh_kexes ssh_rsa_kex = { lenof(rsa_kex_list), rsa_kex_list };