sshrsa.c 30 KB

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