sshrsa.c 27 KB

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