sshrsa.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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(unsigned char *data, int len, struct RSAKey *result,
  11. unsigned char **keystr, int order)
  12. {
  13. 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(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. /*
  235. * Now check that this number is strictly greater than
  236. * zero, and strictly less than modulus.
  237. */
  238. if (bignum_cmp(random, Zero) <= 0 ||
  239. bignum_cmp(random, key->modulus) >= 0) {
  240. freebn(random);
  241. continue;
  242. }
  243. /*
  244. * Also, make sure it has an inverse mod modulus.
  245. */
  246. random_inverse = modinv(random, key->modulus);
  247. if (!random_inverse) {
  248. freebn(random);
  249. continue;
  250. }
  251. break;
  252. }
  253. /*
  254. * RSA blinding relies on the fact that (xy)^d mod n is equal
  255. * to (x^d mod n) * (y^d mod n) mod n. We invent a random pair
  256. * y and y^d; then we multiply x by y, raise to the power d mod
  257. * n as usual, and divide by y^d to recover x^d. Thus an
  258. * attacker can't correlate the timing of the modpow with the
  259. * input, because they don't know anything about the number
  260. * that was input to the actual modpow.
  261. *
  262. * The clever bit is that we don't have to do a huge modpow to
  263. * get y and y^d; we will use the number we just invented as
  264. * _y^d_, and use the _public_ exponent to compute (y^d)^e = y
  265. * from it, which is much faster to do.
  266. */
  267. random_encrypted = crt_modpow(random, key->exponent,
  268. key->modulus, key->p, key->q, key->iqmp);
  269. input_blinded = modmul(input, random_encrypted, key->modulus);
  270. ret_blinded = crt_modpow(input_blinded, key->private_exponent,
  271. key->modulus, key->p, key->q, key->iqmp);
  272. ret = modmul(ret_blinded, random_inverse, key->modulus);
  273. freebn(ret_blinded);
  274. freebn(input_blinded);
  275. freebn(random_inverse);
  276. freebn(random_encrypted);
  277. freebn(random);
  278. return ret;
  279. }
  280. Bignum rsadecrypt(Bignum input, struct RSAKey *key)
  281. {
  282. return rsa_privkey_op(input, key);
  283. }
  284. int rsastr_len(struct RSAKey *key)
  285. {
  286. Bignum md, ex;
  287. int mdlen, exlen;
  288. md = key->modulus;
  289. ex = key->exponent;
  290. mdlen = (bignum_bitcount(md) + 15) / 16;
  291. exlen = (bignum_bitcount(ex) + 15) / 16;
  292. return 4 * (mdlen + exlen) + 20;
  293. }
  294. void rsastr_fmt(char *str, struct RSAKey *key)
  295. {
  296. Bignum md, ex;
  297. int len = 0, i, nibbles;
  298. static const char hex[] = "0123456789abcdef";
  299. md = key->modulus;
  300. ex = key->exponent;
  301. len += sprintf(str + len, "0x");
  302. nibbles = (3 + bignum_bitcount(ex)) / 4;
  303. if (nibbles < 1)
  304. nibbles = 1;
  305. for (i = nibbles; i--;)
  306. str[len++] = hex[(bignum_byte(ex, i / 2) >> (4 * (i % 2))) & 0xF];
  307. len += sprintf(str + len, ",0x");
  308. nibbles = (3 + bignum_bitcount(md)) / 4;
  309. if (nibbles < 1)
  310. nibbles = 1;
  311. for (i = nibbles; i--;)
  312. str[len++] = hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF];
  313. str[len] = '\0';
  314. }
  315. /*
  316. * Generate a fingerprint string for the key. Compatible with the
  317. * OpenSSH fingerprint code.
  318. */
  319. void rsa_fingerprint(char *str, int len, struct RSAKey *key)
  320. {
  321. struct MD5Context md5c;
  322. unsigned char digest[16];
  323. char buffer[16 * 3 + 40];
  324. int numlen, slen, i;
  325. MD5Init(&md5c);
  326. numlen = ssh1_bignum_length(key->modulus) - 2;
  327. for (i = numlen; i--;) {
  328. unsigned char c = bignum_byte(key->modulus, i);
  329. MD5Update(&md5c, &c, 1);
  330. }
  331. numlen = ssh1_bignum_length(key->exponent) - 2;
  332. for (i = numlen; i--;) {
  333. unsigned char c = bignum_byte(key->exponent, i);
  334. MD5Update(&md5c, &c, 1);
  335. }
  336. MD5Final(digest, &md5c);
  337. sprintf(buffer, "%d ", bignum_bitcount(key->modulus));
  338. for (i = 0; i < 16; i++)
  339. sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
  340. digest[i]);
  341. strncpy(str, buffer, len);
  342. str[len - 1] = '\0';
  343. slen = strlen(str);
  344. if (key->comment && slen < len - 1) {
  345. str[slen] = ' ';
  346. strncpy(str + slen + 1, key->comment, len - slen - 1);
  347. str[len - 1] = '\0';
  348. }
  349. }
  350. /*
  351. * Verify that the public data in an RSA key matches the private
  352. * data. We also check the private data itself: we ensure that p >
  353. * q and that iqmp really is the inverse of q mod p.
  354. */
  355. int rsa_verify(struct RSAKey *key)
  356. {
  357. Bignum n, ed, pm1, qm1;
  358. int cmp;
  359. /* n must equal pq. */
  360. n = bigmul(key->p, key->q);
  361. cmp = bignum_cmp(n, key->modulus);
  362. freebn(n);
  363. if (cmp != 0)
  364. return 0;
  365. /* e * d must be congruent to 1, modulo (p-1) and modulo (q-1). */
  366. pm1 = copybn(key->p);
  367. decbn(pm1);
  368. ed = modmul(key->exponent, key->private_exponent, pm1);
  369. freebn(pm1);
  370. cmp = bignum_cmp(ed, One);
  371. freebn(ed);
  372. if (cmp != 0)
  373. return 0;
  374. qm1 = copybn(key->q);
  375. decbn(qm1);
  376. ed = modmul(key->exponent, key->private_exponent, qm1);
  377. freebn(qm1);
  378. cmp = bignum_cmp(ed, One);
  379. freebn(ed);
  380. if (cmp != 0)
  381. return 0;
  382. /*
  383. * Ensure p > q.
  384. *
  385. * I have seen key blobs in the wild which were generated with
  386. * p < q, so instead of rejecting the key in this case we
  387. * should instead flip them round into the canonical order of
  388. * p > q. This also involves regenerating iqmp.
  389. */
  390. if (bignum_cmp(key->p, key->q) <= 0) {
  391. Bignum tmp = key->p;
  392. key->p = key->q;
  393. key->q = tmp;
  394. freebn(key->iqmp);
  395. key->iqmp = modinv(key->q, key->p);
  396. if (!key->iqmp)
  397. return 0;
  398. }
  399. /*
  400. * Ensure iqmp * q is congruent to 1, modulo p.
  401. */
  402. n = modmul(key->iqmp, key->q, key->p);
  403. cmp = bignum_cmp(n, One);
  404. freebn(n);
  405. if (cmp != 0)
  406. return 0;
  407. return 1;
  408. }
  409. /* Public key blob as used by Pageant: exponent before modulus. */
  410. unsigned char *rsa_public_blob(struct RSAKey *key, int *len)
  411. {
  412. int length, pos;
  413. unsigned char *ret;
  414. length = (ssh1_bignum_length(key->modulus) +
  415. ssh1_bignum_length(key->exponent) + 4);
  416. ret = snewn(length, unsigned char);
  417. PUT_32BIT(ret, bignum_bitcount(key->modulus));
  418. pos = 4;
  419. pos += ssh1_write_bignum(ret + pos, key->exponent);
  420. pos += ssh1_write_bignum(ret + pos, key->modulus);
  421. *len = length;
  422. return ret;
  423. }
  424. /* Given a public blob, determine its length. */
  425. int rsa_public_blob_len(void *data, int maxlen)
  426. {
  427. unsigned char *p = (unsigned char *)data;
  428. int n;
  429. if (maxlen < 4)
  430. return -1;
  431. p += 4; /* length word */
  432. maxlen -= 4;
  433. n = ssh1_read_bignum(p, maxlen, NULL); /* exponent */
  434. if (n < 0)
  435. return -1;
  436. p += n;
  437. n = ssh1_read_bignum(p, maxlen, NULL); /* modulus */
  438. if (n < 0)
  439. return -1;
  440. p += n;
  441. return p - (unsigned char *)data;
  442. }
  443. void freersakey(struct RSAKey *key)
  444. {
  445. if (key->modulus)
  446. freebn(key->modulus);
  447. if (key->exponent)
  448. freebn(key->exponent);
  449. if (key->private_exponent)
  450. freebn(key->private_exponent);
  451. if (key->p)
  452. freebn(key->p);
  453. if (key->q)
  454. freebn(key->q);
  455. if (key->iqmp)
  456. freebn(key->iqmp);
  457. if (key->comment)
  458. sfree(key->comment);
  459. }
  460. /* ----------------------------------------------------------------------
  461. * Implementation of the ssh-rsa signing key type.
  462. */
  463. static void getstring(char **data, int *datalen, char **p, int *length)
  464. {
  465. *p = NULL;
  466. if (*datalen < 4)
  467. return;
  468. *length = toint(GET_32BIT(*data));
  469. if (*length < 0)
  470. return;
  471. *datalen -= 4;
  472. *data += 4;
  473. if (*datalen < *length)
  474. return;
  475. *p = *data;
  476. *data += *length;
  477. *datalen -= *length;
  478. }
  479. static Bignum getmp(char **data, int *datalen)
  480. {
  481. char *p;
  482. int length;
  483. Bignum b;
  484. getstring(data, datalen, &p, &length);
  485. if (!p)
  486. return NULL;
  487. b = bignum_from_bytes((unsigned char *)p, length);
  488. return b;
  489. }
  490. static void rsa2_freekey(void *key); /* forward reference */
  491. static void *rsa2_newkey(char *data, int len)
  492. {
  493. char *p;
  494. int slen;
  495. struct RSAKey *rsa;
  496. rsa = snew(struct RSAKey);
  497. getstring(&data, &len, &p, &slen);
  498. if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
  499. sfree(rsa);
  500. return NULL;
  501. }
  502. rsa->exponent = getmp(&data, &len);
  503. rsa->modulus = getmp(&data, &len);
  504. rsa->private_exponent = NULL;
  505. rsa->p = rsa->q = rsa->iqmp = NULL;
  506. rsa->comment = NULL;
  507. if (!rsa->exponent || !rsa->modulus) {
  508. rsa2_freekey(rsa);
  509. return NULL;
  510. }
  511. return rsa;
  512. }
  513. static void rsa2_freekey(void *key)
  514. {
  515. struct RSAKey *rsa = (struct RSAKey *) key;
  516. freersakey(rsa);
  517. sfree(rsa);
  518. }
  519. static char *rsa2_fmtkey(void *key)
  520. {
  521. struct RSAKey *rsa = (struct RSAKey *) key;
  522. char *p;
  523. int len;
  524. len = rsastr_len(rsa);
  525. p = snewn(len, char);
  526. rsastr_fmt(p, rsa);
  527. return p;
  528. }
  529. static unsigned char *rsa2_public_blob(void *key, int *len)
  530. {
  531. struct RSAKey *rsa = (struct RSAKey *) key;
  532. int elen, mlen, bloblen;
  533. int i;
  534. unsigned char *blob, *p;
  535. elen = (bignum_bitcount(rsa->exponent) + 8) / 8;
  536. mlen = (bignum_bitcount(rsa->modulus) + 8) / 8;
  537. /*
  538. * string "ssh-rsa", mpint exp, mpint mod. Total 19+elen+mlen.
  539. * (three length fields, 12+7=19).
  540. */
  541. bloblen = 19 + elen + mlen;
  542. blob = snewn(bloblen, unsigned char);
  543. p = blob;
  544. PUT_32BIT(p, 7);
  545. p += 4;
  546. memcpy(p, "ssh-rsa", 7);
  547. p += 7;
  548. PUT_32BIT(p, elen);
  549. p += 4;
  550. for (i = elen; i--;)
  551. *p++ = bignum_byte(rsa->exponent, i);
  552. PUT_32BIT(p, mlen);
  553. p += 4;
  554. for (i = mlen; i--;)
  555. *p++ = bignum_byte(rsa->modulus, i);
  556. assert(p == blob + bloblen);
  557. *len = bloblen;
  558. return blob;
  559. }
  560. static unsigned char *rsa2_private_blob(void *key, int *len)
  561. {
  562. struct RSAKey *rsa = (struct RSAKey *) key;
  563. int dlen, plen, qlen, ulen, bloblen;
  564. int i;
  565. unsigned char *blob, *p;
  566. dlen = (bignum_bitcount(rsa->private_exponent) + 8) / 8;
  567. plen = (bignum_bitcount(rsa->p) + 8) / 8;
  568. qlen = (bignum_bitcount(rsa->q) + 8) / 8;
  569. ulen = (bignum_bitcount(rsa->iqmp) + 8) / 8;
  570. /*
  571. * mpint private_exp, mpint p, mpint q, mpint iqmp. Total 16 +
  572. * sum of lengths.
  573. */
  574. bloblen = 16 + dlen + plen + qlen + ulen;
  575. blob = snewn(bloblen, unsigned char);
  576. p = blob;
  577. PUT_32BIT(p, dlen);
  578. p += 4;
  579. for (i = dlen; i--;)
  580. *p++ = bignum_byte(rsa->private_exponent, i);
  581. PUT_32BIT(p, plen);
  582. p += 4;
  583. for (i = plen; i--;)
  584. *p++ = bignum_byte(rsa->p, i);
  585. PUT_32BIT(p, qlen);
  586. p += 4;
  587. for (i = qlen; i--;)
  588. *p++ = bignum_byte(rsa->q, i);
  589. PUT_32BIT(p, ulen);
  590. p += 4;
  591. for (i = ulen; i--;)
  592. *p++ = bignum_byte(rsa->iqmp, i);
  593. assert(p == blob + bloblen);
  594. *len = bloblen;
  595. return blob;
  596. }
  597. static void *rsa2_createkey(unsigned char *pub_blob, int pub_len,
  598. unsigned char *priv_blob, int priv_len)
  599. {
  600. struct RSAKey *rsa;
  601. char *pb = (char *) priv_blob;
  602. rsa = rsa2_newkey((char *) pub_blob, pub_len);
  603. rsa->private_exponent = getmp(&pb, &priv_len);
  604. rsa->p = getmp(&pb, &priv_len);
  605. rsa->q = getmp(&pb, &priv_len);
  606. rsa->iqmp = getmp(&pb, &priv_len);
  607. if (!rsa_verify(rsa)) {
  608. rsa2_freekey(rsa);
  609. return NULL;
  610. }
  611. return rsa;
  612. }
  613. static void *rsa2_openssh_createkey(unsigned char **blob, int *len)
  614. {
  615. char **b = (char **) blob;
  616. struct RSAKey *rsa;
  617. rsa = snew(struct RSAKey);
  618. rsa->comment = NULL;
  619. rsa->modulus = getmp(b, len);
  620. rsa->exponent = getmp(b, len);
  621. rsa->private_exponent = getmp(b, len);
  622. rsa->iqmp = getmp(b, len);
  623. rsa->p = getmp(b, len);
  624. rsa->q = getmp(b, len);
  625. if (!rsa->modulus || !rsa->exponent || !rsa->private_exponent ||
  626. !rsa->iqmp || !rsa->p || !rsa->q) {
  627. rsa2_freekey(rsa);
  628. return NULL;
  629. }
  630. if (!rsa_verify(rsa)) {
  631. rsa2_freekey(rsa);
  632. return NULL;
  633. }
  634. return rsa;
  635. }
  636. static int rsa2_openssh_fmtkey(void *key, unsigned char *blob, int len)
  637. {
  638. struct RSAKey *rsa = (struct RSAKey *) key;
  639. int bloblen, i;
  640. bloblen =
  641. ssh2_bignum_length(rsa->modulus) +
  642. ssh2_bignum_length(rsa->exponent) +
  643. ssh2_bignum_length(rsa->private_exponent) +
  644. ssh2_bignum_length(rsa->iqmp) +
  645. ssh2_bignum_length(rsa->p) + ssh2_bignum_length(rsa->q);
  646. if (bloblen > len)
  647. return bloblen;
  648. bloblen = 0;
  649. #define ENC(x) \
  650. PUT_32BIT(blob+bloblen, ssh2_bignum_length((x))-4); bloblen += 4; \
  651. for (i = ssh2_bignum_length((x))-4; i-- ;) blob[bloblen++]=bignum_byte((x),i);
  652. ENC(rsa->modulus);
  653. ENC(rsa->exponent);
  654. ENC(rsa->private_exponent);
  655. ENC(rsa->iqmp);
  656. ENC(rsa->p);
  657. ENC(rsa->q);
  658. return bloblen;
  659. }
  660. static int rsa2_pubkey_bits(void *blob, int len)
  661. {
  662. struct RSAKey *rsa;
  663. int ret;
  664. rsa = rsa2_newkey((char *) blob, len);
  665. ret = bignum_bitcount(rsa->modulus);
  666. rsa2_freekey(rsa);
  667. return ret;
  668. }
  669. static char *rsa2_fingerprint(void *key)
  670. {
  671. struct RSAKey *rsa = (struct RSAKey *) key;
  672. struct MD5Context md5c;
  673. unsigned char digest[16], lenbuf[4];
  674. char buffer[16 * 3 + 40];
  675. char *ret;
  676. int numlen, i;
  677. MD5Init(&md5c);
  678. MD5Update(&md5c, (unsigned char *)"\0\0\0\7ssh-rsa", 11);
  679. #define ADD_BIGNUM(bignum) \
  680. numlen = (bignum_bitcount(bignum)+8)/8; \
  681. PUT_32BIT(lenbuf, numlen); MD5Update(&md5c, lenbuf, 4); \
  682. for (i = numlen; i-- ;) { \
  683. unsigned char c = bignum_byte(bignum, i); \
  684. MD5Update(&md5c, &c, 1); \
  685. }
  686. ADD_BIGNUM(rsa->exponent);
  687. ADD_BIGNUM(rsa->modulus);
  688. #undef ADD_BIGNUM
  689. MD5Final(digest, &md5c);
  690. sprintf(buffer, "ssh-rsa %d ", bignum_bitcount(rsa->modulus));
  691. for (i = 0; i < 16; i++)
  692. sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
  693. digest[i]);
  694. ret = snewn(strlen(buffer) + 1, char);
  695. if (ret)
  696. strcpy(ret, buffer);
  697. return ret;
  698. }
  699. /*
  700. * This is the magic ASN.1/DER prefix that goes in the decoded
  701. * signature, between the string of FFs and the actual SHA hash
  702. * value. The meaning of it is:
  703. *
  704. * 00 -- this marks the end of the FFs; not part of the ASN.1 bit itself
  705. *
  706. * 30 21 -- a constructed SEQUENCE of length 0x21
  707. * 30 09 -- a constructed sub-SEQUENCE of length 9
  708. * 06 05 -- an object identifier, length 5
  709. * 2B 0E 03 02 1A -- object id { 1 3 14 3 2 26 }
  710. * (the 1,3 comes from 0x2B = 43 = 40*1+3)
  711. * 05 00 -- NULL
  712. * 04 14 -- a primitive OCTET STRING of length 0x14
  713. * [0x14 bytes of hash data follows]
  714. *
  715. * The object id in the middle there is listed as `id-sha1' in
  716. * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1d2.asn (the
  717. * ASN module for PKCS #1) and its expanded form is as follows:
  718. *
  719. * id-sha1 OBJECT IDENTIFIER ::= {
  720. * iso(1) identified-organization(3) oiw(14) secsig(3)
  721. * algorithms(2) 26 }
  722. */
  723. static const unsigned char asn1_weird_stuff[] = {
  724. 0x00, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
  725. 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
  726. };
  727. #define ASN1_LEN ( (int) sizeof(asn1_weird_stuff) )
  728. static int rsa2_verifysig(void *key, char *sig, int siglen,
  729. char *data, int datalen)
  730. {
  731. struct RSAKey *rsa = (struct RSAKey *) key;
  732. Bignum in, out;
  733. char *p;
  734. int slen;
  735. int bytes, i, j, ret;
  736. unsigned char hash[20];
  737. getstring(&sig, &siglen, &p, &slen);
  738. if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
  739. return 0;
  740. }
  741. in = getmp(&sig, &siglen);
  742. if (!in)
  743. return 0;
  744. out = modpow(in, rsa->exponent, rsa->modulus);
  745. freebn(in);
  746. ret = 1;
  747. bytes = (bignum_bitcount(rsa->modulus)+7) / 8;
  748. /* Top (partial) byte should be zero. */
  749. if (bignum_byte(out, bytes - 1) != 0)
  750. ret = 0;
  751. /* First whole byte should be 1. */
  752. if (bignum_byte(out, bytes - 2) != 1)
  753. ret = 0;
  754. /* Most of the rest should be FF. */
  755. for (i = bytes - 3; i >= 20 + ASN1_LEN; i--) {
  756. if (bignum_byte(out, i) != 0xFF)
  757. ret = 0;
  758. }
  759. /* Then we expect to see the asn1_weird_stuff. */
  760. for (i = 20 + ASN1_LEN - 1, j = 0; i >= 20; i--, j++) {
  761. if (bignum_byte(out, i) != asn1_weird_stuff[j])
  762. ret = 0;
  763. }
  764. /* Finally, we expect to see the SHA-1 hash of the signed data. */
  765. SHA_Simple(data, datalen, hash);
  766. for (i = 19, j = 0; i >= 0; i--, j++) {
  767. if (bignum_byte(out, i) != hash[j])
  768. ret = 0;
  769. }
  770. freebn(out);
  771. return ret;
  772. }
  773. static unsigned char *rsa2_sign(void *key, char *data, int datalen,
  774. int *siglen)
  775. {
  776. struct RSAKey *rsa = (struct RSAKey *) key;
  777. unsigned char *bytes;
  778. int nbytes;
  779. unsigned char hash[20];
  780. Bignum in, out;
  781. int i, j;
  782. SHA_Simple(data, datalen, hash);
  783. nbytes = (bignum_bitcount(rsa->modulus) - 1) / 8;
  784. assert(1 <= nbytes - 20 - ASN1_LEN);
  785. bytes = snewn(nbytes, unsigned char);
  786. bytes[0] = 1;
  787. for (i = 1; i < nbytes - 20 - ASN1_LEN; i++)
  788. bytes[i] = 0xFF;
  789. for (i = nbytes - 20 - ASN1_LEN, j = 0; i < nbytes - 20; i++, j++)
  790. bytes[i] = asn1_weird_stuff[j];
  791. for (i = nbytes - 20, j = 0; i < nbytes; i++, j++)
  792. bytes[i] = hash[j];
  793. in = bignum_from_bytes(bytes, nbytes);
  794. sfree(bytes);
  795. out = rsa_privkey_op(in, rsa);
  796. freebn(in);
  797. nbytes = (bignum_bitcount(out) + 7) / 8;
  798. bytes = snewn(4 + 7 + 4 + nbytes, unsigned char);
  799. PUT_32BIT(bytes, 7);
  800. memcpy(bytes + 4, "ssh-rsa", 7);
  801. PUT_32BIT(bytes + 4 + 7, nbytes);
  802. for (i = 0; i < nbytes; i++)
  803. bytes[4 + 7 + 4 + i] = bignum_byte(out, nbytes - 1 - i);
  804. freebn(out);
  805. *siglen = 4 + 7 + 4 + nbytes;
  806. return bytes;
  807. }
  808. const struct ssh_signkey ssh_rsa = {
  809. rsa2_newkey,
  810. rsa2_freekey,
  811. rsa2_fmtkey,
  812. rsa2_public_blob,
  813. rsa2_private_blob,
  814. rsa2_createkey,
  815. rsa2_openssh_createkey,
  816. rsa2_openssh_fmtkey,
  817. rsa2_pubkey_bits,
  818. rsa2_fingerprint,
  819. rsa2_verifysig,
  820. rsa2_sign,
  821. "ssh-rsa",
  822. "rsa2"
  823. };
  824. void *ssh_rsakex_newkey(char *data, int len)
  825. {
  826. return rsa2_newkey(data, len);
  827. }
  828. void ssh_rsakex_freekey(void *key)
  829. {
  830. rsa2_freekey(key);
  831. }
  832. int ssh_rsakex_klen(void *key)
  833. {
  834. struct RSAKey *rsa = (struct RSAKey *) key;
  835. return bignum_bitcount(rsa->modulus);
  836. }
  837. static void oaep_mask(const struct ssh_hash *h, void *seed, int seedlen,
  838. void *vdata, int datalen)
  839. {
  840. unsigned char *data = (unsigned char *)vdata;
  841. unsigned count = 0;
  842. while (datalen > 0) {
  843. int i, max = (datalen > h->hlen ? h->hlen : datalen);
  844. void *s;
  845. unsigned char counter[4], hash[SSH2_KEX_MAX_HASH_LEN];
  846. assert(h->hlen <= SSH2_KEX_MAX_HASH_LEN);
  847. PUT_32BIT(counter, count);
  848. s = h->init();
  849. h->bytes(s, seed, seedlen);
  850. h->bytes(s, counter, 4);
  851. h->final(s, hash);
  852. count++;
  853. for (i = 0; i < max; i++)
  854. data[i] ^= hash[i];
  855. data += max;
  856. datalen -= max;
  857. }
  858. }
  859. void ssh_rsakex_encrypt(const struct ssh_hash *h, unsigned char *in, int inlen,
  860. unsigned char *out, int outlen,
  861. void *key)
  862. {
  863. Bignum b1, b2;
  864. struct RSAKey *rsa = (struct RSAKey *) key;
  865. int k, i;
  866. char *p;
  867. const int HLEN = h->hlen;
  868. /*
  869. * Here we encrypt using RSAES-OAEP. Essentially this means:
  870. *
  871. * - we have a SHA-based `mask generation function' which
  872. * creates a pseudo-random stream of mask data
  873. * deterministically from an input chunk of data.
  874. *
  875. * - we have a random chunk of data called a seed.
  876. *
  877. * - we use the seed to generate a mask which we XOR with our
  878. * plaintext.
  879. *
  880. * - then we use _the masked plaintext_ to generate a mask
  881. * which we XOR with the seed.
  882. *
  883. * - then we concatenate the masked seed and the masked
  884. * plaintext, and RSA-encrypt that lot.
  885. *
  886. * The result is that the data input to the encryption function
  887. * is random-looking and (hopefully) contains no exploitable
  888. * structure such as PKCS1-v1_5 does.
  889. *
  890. * For a precise specification, see RFC 3447, section 7.1.1.
  891. * Some of the variable names below are derived from that, so
  892. * it'd probably help to read it anyway.
  893. */
  894. /* k denotes the length in octets of the RSA modulus. */
  895. k = (7 + bignum_bitcount(rsa->modulus)) / 8;
  896. /* The length of the input data must be at most k - 2hLen - 2. */
  897. assert(inlen > 0 && inlen <= k - 2*HLEN - 2);
  898. /* The length of the output data wants to be precisely k. */
  899. assert(outlen == k);
  900. /*
  901. * Now perform EME-OAEP encoding. First set up all the unmasked
  902. * output data.
  903. */
  904. /* Leading byte zero. */
  905. out[0] = 0;
  906. /* At position 1, the seed: HLEN bytes of random data. */
  907. for (i = 0; i < HLEN; i++)
  908. out[i + 1] = random_byte();
  909. /* At position 1+HLEN, the data block DB, consisting of: */
  910. /* The hash of the label (we only support an empty label here) */
  911. h->final(h->init(), out + HLEN + 1);
  912. /* A bunch of zero octets */
  913. memset(out + 2*HLEN + 1, 0, outlen - (2*HLEN + 1));
  914. /* A single 1 octet, followed by the input message data. */
  915. out[outlen - inlen - 1] = 1;
  916. memcpy(out + outlen - inlen, in, inlen);
  917. /*
  918. * Now use the seed data to mask the block DB.
  919. */
  920. oaep_mask(h, out+1, HLEN, out+HLEN+1, outlen-HLEN-1);
  921. /*
  922. * And now use the masked DB to mask the seed itself.
  923. */
  924. oaep_mask(h, out+HLEN+1, outlen-HLEN-1, out+1, HLEN);
  925. /*
  926. * Now `out' contains precisely the data we want to
  927. * RSA-encrypt.
  928. */
  929. b1 = bignum_from_bytes(out, outlen);
  930. b2 = modpow(b1, rsa->exponent, rsa->modulus);
  931. p = (char *)out;
  932. for (i = outlen; i--;) {
  933. *p++ = bignum_byte(b2, i);
  934. }
  935. freebn(b1);
  936. freebn(b2);
  937. /*
  938. * And we're done.
  939. */
  940. }
  941. static const struct ssh_kex ssh_rsa_kex_sha1 = {
  942. "rsa1024-sha1", NULL, KEXTYPE_RSA, NULL, NULL, 0, 0, &ssh_sha1
  943. };
  944. static const struct ssh_kex ssh_rsa_kex_sha256 = {
  945. "rsa2048-sha256", NULL, KEXTYPE_RSA, NULL, NULL, 0, 0, &ssh_sha256
  946. };
  947. static const struct ssh_kex *const rsa_kex_list[] = {
  948. &ssh_rsa_kex_sha256,
  949. &ssh_rsa_kex_sha1
  950. };
  951. const struct ssh_kexes ssh_rsa_kex = {
  952. sizeof(rsa_kex_list) / sizeof(*rsa_kex_list),
  953. rsa_kex_list
  954. };