sshrsa.c 29 KB

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