sshrsa.c 29 KB

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