sshrsa.c 29 KB

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