sshpubk.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  1. /*
  2. * Generic SSH public-key handling operations. In particular,
  3. * reading of SSH public-key files, and also the generic `sign'
  4. * operation for SSH-2 (which checks the type of the key and
  5. * dispatches to the appropriate key-type specific function).
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <assert.h>
  10. #include "putty.h"
  11. #include "ssh.h"
  12. #include "misc.h"
  13. #define rsa_signature "SSH PRIVATE KEY FILE FORMAT 1.1\n"
  14. #define BASE64_TOINT(x) ( (x)-'A'<26 ? (x)-'A'+0 :\
  15. (x)-'a'<26 ? (x)-'a'+26 :\
  16. (x)-'0'<10 ? (x)-'0'+52 :\
  17. (x)=='+' ? 62 : \
  18. (x)=='/' ? 63 : 0 )
  19. static int key_type_fp(FILE *fp);
  20. static int loadrsakey_main(FILE * fp, struct RSAKey *key, int pub_only,
  21. char **commentptr, const char *passphrase,
  22. const char **error)
  23. {
  24. unsigned char buf[16384];
  25. unsigned char keybuf[16];
  26. int len;
  27. int i, j, ciphertype;
  28. int ret = 0;
  29. struct MD5Context md5c;
  30. char *comment;
  31. *error = NULL;
  32. /* Slurp the whole file (minus the header) into a buffer. */
  33. len = fread(buf, 1, sizeof(buf), fp);
  34. fclose(fp);
  35. if (len < 0 || len == sizeof(buf)) {
  36. *error = "error reading file";
  37. goto end; /* file too big or not read */
  38. }
  39. i = 0;
  40. *error = "file format error";
  41. /*
  42. * A zero byte. (The signature includes a terminating NUL.)
  43. */
  44. if (len - i < 1 || buf[i] != 0)
  45. goto end;
  46. i++;
  47. /* One byte giving encryption type, and one reserved uint32. */
  48. if (len - i < 1)
  49. goto end;
  50. ciphertype = buf[i];
  51. if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES)
  52. goto end;
  53. i++;
  54. if (len - i < 4)
  55. goto end; /* reserved field not present */
  56. if (buf[i] != 0 || buf[i + 1] != 0 || buf[i + 2] != 0
  57. || buf[i + 3] != 0) goto end; /* reserved field nonzero, panic! */
  58. i += 4;
  59. /* Now the serious stuff. An ordinary SSH-1 public key. */
  60. j = makekey(buf + i, len - i, key, NULL, 1);
  61. if (j < 0)
  62. goto end; /* overran */
  63. i += j;
  64. /* Next, the comment field. */
  65. j = toint(GET_32BIT(buf + i));
  66. i += 4;
  67. if (j < 0 || len - i < j)
  68. goto end;
  69. comment = snewn(j + 1, char);
  70. if (comment) {
  71. memcpy(comment, buf + i, j);
  72. comment[j] = '\0';
  73. }
  74. i += j;
  75. if (commentptr)
  76. *commentptr = dupstr(comment);
  77. if (key)
  78. key->comment = comment;
  79. else
  80. sfree(comment);
  81. if (pub_only) {
  82. ret = 1;
  83. goto end;
  84. }
  85. if (!key) {
  86. ret = ciphertype != 0;
  87. *error = NULL;
  88. goto end;
  89. }
  90. /*
  91. * Decrypt remainder of buffer.
  92. */
  93. if (ciphertype) {
  94. MD5Init(&md5c);
  95. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  96. MD5Final(keybuf, &md5c);
  97. des3_decrypt_pubkey(keybuf, buf + i, (len - i + 7) & ~7);
  98. smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
  99. }
  100. /*
  101. * We are now in the secret part of the key. The first four
  102. * bytes should be of the form a, b, a, b.
  103. */
  104. if (len - i < 4)
  105. goto end;
  106. if (buf[i] != buf[i + 2] || buf[i + 1] != buf[i + 3]) {
  107. *error = "wrong passphrase";
  108. ret = -1;
  109. goto end;
  110. }
  111. i += 4;
  112. /*
  113. * After that, we have one further bignum which is our
  114. * decryption exponent, and then the three auxiliary values
  115. * (iqmp, q, p).
  116. */
  117. j = makeprivate(buf + i, len - i, key);
  118. if (j < 0) goto end;
  119. i += j;
  120. j = ssh1_read_bignum(buf + i, len - i, &key->iqmp);
  121. if (j < 0) goto end;
  122. i += j;
  123. j = ssh1_read_bignum(buf + i, len - i, &key->q);
  124. if (j < 0) goto end;
  125. i += j;
  126. j = ssh1_read_bignum(buf + i, len - i, &key->p);
  127. if (j < 0) goto end;
  128. i += j;
  129. if (!rsa_verify(key)) {
  130. *error = "rsa_verify failed";
  131. freersakey(key);
  132. ret = 0;
  133. } else
  134. ret = 1;
  135. end:
  136. smemclr(buf, sizeof(buf)); /* burn the evidence */
  137. return ret;
  138. }
  139. int loadrsakey(const Filename *filename, struct RSAKey *key,
  140. const char *passphrase, const char **errorstr)
  141. {
  142. FILE *fp;
  143. char buf[64];
  144. int ret = 0;
  145. const char *error = NULL;
  146. fp = f_open(filename, "rb", FALSE);
  147. if (!fp) {
  148. error = "can't open file";
  149. goto end;
  150. }
  151. /*
  152. * Read the first line of the file and see if it's a v1 private
  153. * key file.
  154. */
  155. if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
  156. /*
  157. * This routine will take care of calling fclose() for us.
  158. */
  159. ret = loadrsakey_main(fp, key, FALSE, NULL, passphrase, &error);
  160. fp = NULL;
  161. goto end;
  162. }
  163. /*
  164. * Otherwise, we have nothing. Return empty-handed.
  165. */
  166. error = "not an SSH-1 RSA file";
  167. end:
  168. if (fp)
  169. fclose(fp);
  170. if ((ret != 1) && errorstr)
  171. *errorstr = error;
  172. return ret;
  173. }
  174. /*
  175. * See whether an RSA key is encrypted. Return its comment field as
  176. * well.
  177. */
  178. int rsakey_encrypted(const Filename *filename, char **comment)
  179. {
  180. FILE *fp;
  181. char buf[64];
  182. fp = f_open(filename, "rb", FALSE);
  183. if (!fp)
  184. return 0; /* doesn't even exist */
  185. /*
  186. * Read the first line of the file and see if it's a v1 private
  187. * key file.
  188. */
  189. if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
  190. const char *dummy;
  191. /*
  192. * This routine will take care of calling fclose() for us.
  193. */
  194. return loadrsakey_main(fp, NULL, FALSE, comment, NULL, &dummy);
  195. }
  196. fclose(fp);
  197. return 0; /* wasn't the right kind of file */
  198. }
  199. /*
  200. * Return a malloc'ed chunk of memory containing the public blob of
  201. * an RSA key, as given in the agent protocol (modulus bits,
  202. * exponent, modulus).
  203. */
  204. int rsakey_pubblob(const Filename *filename, void **blob, int *bloblen,
  205. char **commentptr, const char **errorstr)
  206. {
  207. FILE *fp;
  208. char buf[64];
  209. struct RSAKey key;
  210. int ret;
  211. const char *error = NULL;
  212. /* Default return if we fail. */
  213. *blob = NULL;
  214. *bloblen = 0;
  215. ret = 0;
  216. fp = f_open(filename, "rb", FALSE);
  217. if (!fp) {
  218. error = "can't open file";
  219. goto end;
  220. }
  221. /*
  222. * Read the first line of the file and see if it's a v1 private
  223. * key file.
  224. */
  225. if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
  226. memset(&key, 0, sizeof(key));
  227. if (loadrsakey_main(fp, &key, TRUE, commentptr, NULL, &error)) {
  228. *blob = rsa_public_blob(&key, bloblen);
  229. freersakey(&key);
  230. ret = 1;
  231. }
  232. fp = NULL; /* loadrsakey_main unconditionally closes fp */
  233. } else {
  234. /*
  235. * Try interpreting the file as an SSH-1 public key.
  236. */
  237. char *line, *p, *bitsp, *expp, *modp, *commentp;
  238. rewind(fp);
  239. line = chomp(fgetline(fp));
  240. p = line;
  241. bitsp = p;
  242. p += strspn(p, "0123456789");
  243. if (*p != ' ')
  244. goto not_public_either;
  245. *p++ = '\0';
  246. expp = p;
  247. p += strspn(p, "0123456789");
  248. if (*p != ' ')
  249. goto not_public_either;
  250. *p++ = '\0';
  251. modp = p;
  252. p += strspn(p, "0123456789");
  253. if (*p) {
  254. if (*p != ' ')
  255. goto not_public_either;
  256. *p++ = '\0';
  257. commentp = p;
  258. } else {
  259. commentp = NULL;
  260. }
  261. memset(&key, 0, sizeof(key));
  262. key.exponent = bignum_from_decimal(expp);
  263. key.modulus = bignum_from_decimal(modp);
  264. if (atoi(bitsp) != bignum_bitcount(key.modulus)) {
  265. freebn(key.exponent);
  266. freebn(key.modulus);
  267. sfree(line);
  268. error = "key bit count does not match in SSH-1 public key file";
  269. goto end;
  270. }
  271. if (commentptr)
  272. *commentptr = commentp ? dupstr(commentp) : NULL;
  273. *blob = rsa_public_blob(&key, bloblen);
  274. freersakey(&key);
  275. sfree(line);
  276. fclose(fp);
  277. return 1;
  278. not_public_either:
  279. sfree(line);
  280. error = "not an SSH-1 RSA file";
  281. }
  282. end:
  283. if (fp)
  284. fclose(fp);
  285. if ((ret != 1) && errorstr)
  286. *errorstr = error;
  287. return ret;
  288. }
  289. /*
  290. * Save an RSA key file. Return nonzero on success.
  291. */
  292. int saversakey(const Filename *filename, struct RSAKey *key, char *passphrase)
  293. {
  294. unsigned char buf[16384];
  295. unsigned char keybuf[16];
  296. struct MD5Context md5c;
  297. unsigned char *p, *estart;
  298. FILE *fp;
  299. /*
  300. * Write the initial signature.
  301. */
  302. p = buf;
  303. memcpy(p, rsa_signature, sizeof(rsa_signature));
  304. p += sizeof(rsa_signature);
  305. /*
  306. * One byte giving encryption type, and one reserved (zero)
  307. * uint32.
  308. */
  309. *p++ = (passphrase ? SSH_CIPHER_3DES : 0);
  310. PUT_32BIT(p, 0);
  311. p += 4;
  312. /*
  313. * An ordinary SSH-1 public key consists of: a uint32
  314. * containing the bit count, then two bignums containing the
  315. * modulus and exponent respectively.
  316. */
  317. PUT_32BIT(p, bignum_bitcount(key->modulus));
  318. p += 4;
  319. p += ssh1_write_bignum(p, key->modulus);
  320. p += ssh1_write_bignum(p, key->exponent);
  321. /*
  322. * A string containing the comment field.
  323. */
  324. if (key->comment) {
  325. PUT_32BIT(p, strlen(key->comment));
  326. p += 4;
  327. memcpy(p, key->comment, strlen(key->comment));
  328. p += strlen(key->comment);
  329. } else {
  330. PUT_32BIT(p, 0);
  331. p += 4;
  332. }
  333. /*
  334. * The encrypted portion starts here.
  335. */
  336. estart = p;
  337. /*
  338. * Two bytes, then the same two bytes repeated.
  339. */
  340. *p++ = random_byte();
  341. *p++ = random_byte();
  342. p[0] = p[-2];
  343. p[1] = p[-1];
  344. p += 2;
  345. /*
  346. * Four more bignums: the decryption exponent, then iqmp, then
  347. * q, then p.
  348. */
  349. p += ssh1_write_bignum(p, key->private_exponent);
  350. p += ssh1_write_bignum(p, key->iqmp);
  351. p += ssh1_write_bignum(p, key->q);
  352. p += ssh1_write_bignum(p, key->p);
  353. /*
  354. * Now write zeros until the encrypted portion is a multiple of
  355. * 8 bytes.
  356. */
  357. while ((p - estart) % 8)
  358. *p++ = '\0';
  359. /*
  360. * Now encrypt the encrypted portion.
  361. */
  362. if (passphrase) {
  363. MD5Init(&md5c);
  364. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  365. MD5Final(keybuf, &md5c);
  366. des3_encrypt_pubkey(keybuf, estart, p - estart);
  367. smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
  368. }
  369. /*
  370. * Done. Write the result to the file.
  371. */
  372. fp = f_open(filename, "wb", TRUE);
  373. if (fp) {
  374. int ret = (fwrite(buf, 1, p - buf, fp) == (size_t) (p - buf));
  375. if (fclose(fp))
  376. ret = 0;
  377. return ret;
  378. } else
  379. return 0;
  380. }
  381. /* ----------------------------------------------------------------------
  382. * SSH-2 private key load/store functions.
  383. */
  384. /*
  385. * PuTTY's own format for SSH-2 keys is as follows:
  386. *
  387. * The file is text. Lines are terminated by CRLF, although CR-only
  388. * and LF-only are tolerated on input.
  389. *
  390. * The first line says "PuTTY-User-Key-File-2: " plus the name of the
  391. * algorithm ("ssh-dss", "ssh-rsa" etc).
  392. *
  393. * The next line says "Encryption: " plus an encryption type.
  394. * Currently the only supported encryption types are "aes256-cbc"
  395. * and "none".
  396. *
  397. * The next line says "Comment: " plus the comment string.
  398. *
  399. * Next there is a line saying "Public-Lines: " plus a number N.
  400. * The following N lines contain a base64 encoding of the public
  401. * part of the key. This is encoded as the standard SSH-2 public key
  402. * blob (with no initial length): so for RSA, for example, it will
  403. * read
  404. *
  405. * string "ssh-rsa"
  406. * mpint exponent
  407. * mpint modulus
  408. *
  409. * Next, there is a line saying "Private-Lines: " plus a number N,
  410. * and then N lines containing the (potentially encrypted) private
  411. * part of the key. For the key type "ssh-rsa", this will be
  412. * composed of
  413. *
  414. * mpint private_exponent
  415. * mpint p (the larger of the two primes)
  416. * mpint q (the smaller prime)
  417. * mpint iqmp (the inverse of q modulo p)
  418. * data padding (to reach a multiple of the cipher block size)
  419. *
  420. * And for "ssh-dss", it will be composed of
  421. *
  422. * mpint x (the private key parameter)
  423. * [ string hash 20-byte hash of mpints p || q || g only in old format ]
  424. *
  425. * Finally, there is a line saying "Private-MAC: " plus a hex
  426. * representation of a HMAC-SHA-1 of:
  427. *
  428. * string name of algorithm ("ssh-dss", "ssh-rsa")
  429. * string encryption type
  430. * string comment
  431. * string public-blob
  432. * string private-plaintext (the plaintext version of the
  433. * private part, including the final
  434. * padding)
  435. *
  436. * The key to the MAC is itself a SHA-1 hash of:
  437. *
  438. * data "putty-private-key-file-mac-key"
  439. * data passphrase
  440. *
  441. * (An empty passphrase is used for unencrypted keys.)
  442. *
  443. * If the key is encrypted, the encryption key is derived from the
  444. * passphrase by means of a succession of SHA-1 hashes. Each hash
  445. * is the hash of:
  446. *
  447. * uint32 sequence-number
  448. * data passphrase
  449. *
  450. * where the sequence-number increases from zero. As many of these
  451. * hashes are used as necessary.
  452. *
  453. * For backwards compatibility with snapshots between 0.51 and
  454. * 0.52, we also support the older key file format, which begins
  455. * with "PuTTY-User-Key-File-1" (version number differs). In this
  456. * format the Private-MAC: field only covers the private-plaintext
  457. * field and nothing else (and without the 4-byte string length on
  458. * the front too). Moreover, the Private-MAC: field can be replaced
  459. * with a Private-Hash: field which is a plain SHA-1 hash instead of
  460. * an HMAC (this was generated for unencrypted keys).
  461. */
  462. static int read_header(FILE * fp, char *header)
  463. {
  464. int len = 39;
  465. int c;
  466. while (1) {
  467. c = fgetc(fp);
  468. if (c == '\n' || c == '\r' || c == EOF)
  469. return 0; /* failure */
  470. if (c == ':') {
  471. c = fgetc(fp);
  472. if (c != ' ')
  473. return 0;
  474. *header = '\0';
  475. return 1; /* success! */
  476. }
  477. if (len == 0)
  478. return 0; /* failure */
  479. *header++ = c;
  480. len--;
  481. }
  482. return 0; /* failure */
  483. }
  484. static char *read_body(FILE * fp)
  485. {
  486. char *text;
  487. int len;
  488. int size;
  489. int c;
  490. size = 128;
  491. text = snewn(size, char);
  492. len = 0;
  493. text[len] = '\0';
  494. while (1) {
  495. c = fgetc(fp);
  496. if (c == '\r' || c == '\n' || c == EOF) {
  497. if (c != EOF) {
  498. c = fgetc(fp);
  499. if (c != '\r' && c != '\n')
  500. ungetc(c, fp);
  501. }
  502. return text;
  503. }
  504. if (len + 1 >= size) {
  505. size += 128;
  506. text = sresize(text, size, char);
  507. }
  508. text[len++] = c;
  509. text[len] = '\0';
  510. }
  511. }
  512. static unsigned char *read_blob(FILE * fp, int nlines, int *bloblen)
  513. {
  514. unsigned char *blob;
  515. char *line;
  516. int linelen, len;
  517. int i, j, k;
  518. /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
  519. blob = snewn(48 * nlines, unsigned char);
  520. len = 0;
  521. for (i = 0; i < nlines; i++) {
  522. line = read_body(fp);
  523. if (!line) {
  524. sfree(blob);
  525. return NULL;
  526. }
  527. linelen = strlen(line);
  528. if (linelen % 4 != 0 || linelen > 64) {
  529. sfree(blob);
  530. sfree(line);
  531. return NULL;
  532. }
  533. for (j = 0; j < linelen; j += 4) {
  534. k = base64_decode_atom(line + j, blob + len);
  535. if (!k) {
  536. sfree(line);
  537. sfree(blob);
  538. return NULL;
  539. }
  540. len += k;
  541. }
  542. sfree(line);
  543. }
  544. *bloblen = len;
  545. return blob;
  546. }
  547. /*
  548. * Magic error return value for when the passphrase is wrong.
  549. */
  550. struct ssh2_userkey ssh2_wrong_passphrase = {
  551. NULL, NULL, NULL
  552. };
  553. const struct ssh_signkey *find_pubkey_alg_len(int namelen, const char *name)
  554. {
  555. if (match_ssh_id(namelen, name, "ssh-rsa"))
  556. return &ssh_rsa;
  557. else if (match_ssh_id(namelen, name, "ssh-dss"))
  558. return &ssh_dss;
  559. else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp256"))
  560. return &ssh_ecdsa_nistp256;
  561. else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp384"))
  562. return &ssh_ecdsa_nistp384;
  563. else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp521"))
  564. return &ssh_ecdsa_nistp521;
  565. else if (match_ssh_id(namelen, name, "ssh-ed25519"))
  566. return &ssh_ecdsa_ed25519;
  567. else
  568. return NULL;
  569. }
  570. const struct ssh_signkey *find_pubkey_alg(const char *name)
  571. {
  572. return find_pubkey_alg_len(strlen(name), name);
  573. }
  574. struct ssh2_userkey *ssh2_load_userkey(const Filename *filename,
  575. const char *passphrase,
  576. const char **errorstr)
  577. {
  578. FILE *fp;
  579. char header[40], *b, *encryption, *comment, *mac;
  580. const struct ssh_signkey *alg;
  581. struct ssh2_userkey *ret;
  582. int cipher, cipherblk;
  583. unsigned char *public_blob, *private_blob;
  584. int public_blob_len, private_blob_len;
  585. int i, is_mac, old_fmt;
  586. int passlen = passphrase ? strlen(passphrase) : 0;
  587. const char *error = NULL;
  588. ret = NULL; /* return NULL for most errors */
  589. encryption = comment = mac = NULL;
  590. public_blob = private_blob = NULL;
  591. fp = f_open(filename, "rb", FALSE);
  592. if (!fp) {
  593. error = "can't open file";
  594. goto error;
  595. }
  596. /* Read the first header line which contains the key type. */
  597. if (!read_header(fp, header))
  598. goto error;
  599. if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {
  600. old_fmt = 0;
  601. } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {
  602. /* this is an old key file; warn and then continue */
  603. old_keyfile_warning();
  604. old_fmt = 1;
  605. } else if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) {
  606. /* this is a key file FROM THE FUTURE; refuse it, but with a
  607. * more specific error message than the generic one below */
  608. error = "PuTTY key format too new";
  609. goto error;
  610. } else {
  611. error = "not a PuTTY SSH-2 private key";
  612. goto error;
  613. }
  614. error = "file format error";
  615. if ((b = read_body(fp)) == NULL)
  616. goto error;
  617. /* Select key algorithm structure. */
  618. alg = find_pubkey_alg(b);
  619. if (!alg) {
  620. sfree(b);
  621. goto error;
  622. }
  623. sfree(b);
  624. /* Read the Encryption header line. */
  625. if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
  626. goto error;
  627. if ((encryption = read_body(fp)) == NULL)
  628. goto error;
  629. if (!strcmp(encryption, "aes256-cbc")) {
  630. cipher = 1;
  631. cipherblk = 16;
  632. } else if (!strcmp(encryption, "none")) {
  633. cipher = 0;
  634. cipherblk = 1;
  635. } else {
  636. goto error;
  637. }
  638. /* Read the Comment header line. */
  639. if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
  640. goto error;
  641. if ((comment = read_body(fp)) == NULL)
  642. goto error;
  643. /* Read the Public-Lines header line and the public blob. */
  644. if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
  645. goto error;
  646. if ((b = read_body(fp)) == NULL)
  647. goto error;
  648. i = atoi(b);
  649. sfree(b);
  650. if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
  651. goto error;
  652. /* Read the Private-Lines header line and the Private blob. */
  653. if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))
  654. goto error;
  655. if ((b = read_body(fp)) == NULL)
  656. goto error;
  657. i = atoi(b);
  658. sfree(b);
  659. if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)
  660. goto error;
  661. /* Read the Private-MAC or Private-Hash header line. */
  662. if (!read_header(fp, header))
  663. goto error;
  664. if (0 == strcmp(header, "Private-MAC")) {
  665. if ((mac = read_body(fp)) == NULL)
  666. goto error;
  667. is_mac = 1;
  668. } else if (0 == strcmp(header, "Private-Hash") && old_fmt) {
  669. if ((mac = read_body(fp)) == NULL)
  670. goto error;
  671. is_mac = 0;
  672. } else
  673. goto error;
  674. fclose(fp);
  675. fp = NULL;
  676. /*
  677. * Decrypt the private blob.
  678. */
  679. if (cipher) {
  680. unsigned char key[40];
  681. SHA_State s;
  682. if (!passphrase)
  683. goto error;
  684. if (private_blob_len % cipherblk)
  685. goto error;
  686. SHA_Init(&s);
  687. SHA_Bytes(&s, "\0\0\0\0", 4);
  688. SHA_Bytes(&s, passphrase, passlen);
  689. SHA_Final(&s, key + 0);
  690. SHA_Init(&s);
  691. SHA_Bytes(&s, "\0\0\0\1", 4);
  692. SHA_Bytes(&s, passphrase, passlen);
  693. SHA_Final(&s, key + 20);
  694. aes256_decrypt_pubkey(key, private_blob, private_blob_len);
  695. }
  696. /*
  697. * Verify the MAC.
  698. */
  699. {
  700. char realmac[41];
  701. unsigned char binary[20];
  702. unsigned char *macdata;
  703. int maclen;
  704. int free_macdata;
  705. if (old_fmt) {
  706. /* MAC (or hash) only covers the private blob. */
  707. macdata = private_blob;
  708. maclen = private_blob_len;
  709. free_macdata = 0;
  710. } else {
  711. unsigned char *p;
  712. int namelen = strlen(alg->name);
  713. int enclen = strlen(encryption);
  714. int commlen = strlen(comment);
  715. maclen = (4 + namelen +
  716. 4 + enclen +
  717. 4 + commlen +
  718. 4 + public_blob_len +
  719. 4 + private_blob_len);
  720. macdata = snewn(maclen, unsigned char);
  721. p = macdata;
  722. #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
  723. DO_STR(alg->name, namelen);
  724. DO_STR(encryption, enclen);
  725. DO_STR(comment, commlen);
  726. DO_STR(public_blob, public_blob_len);
  727. DO_STR(private_blob, private_blob_len);
  728. free_macdata = 1;
  729. }
  730. if (is_mac) {
  731. SHA_State s;
  732. unsigned char mackey[20];
  733. char header[] = "putty-private-key-file-mac-key";
  734. SHA_Init(&s);
  735. SHA_Bytes(&s, header, sizeof(header)-1);
  736. if (cipher && passphrase)
  737. SHA_Bytes(&s, passphrase, passlen);
  738. SHA_Final(&s, mackey);
  739. hmac_sha1_simple(mackey, 20, macdata, maclen, binary);
  740. smemclr(mackey, sizeof(mackey));
  741. smemclr(&s, sizeof(s));
  742. } else {
  743. SHA_Simple(macdata, maclen, binary);
  744. }
  745. if (free_macdata) {
  746. smemclr(macdata, maclen);
  747. sfree(macdata);
  748. }
  749. for (i = 0; i < 20; i++)
  750. sprintf(realmac + 2 * i, "%02x", binary[i]);
  751. if (strcmp(mac, realmac)) {
  752. /* An incorrect MAC is an unconditional Error if the key is
  753. * unencrypted. Otherwise, it means Wrong Passphrase. */
  754. if (cipher) {
  755. error = "wrong passphrase";
  756. ret = SSH2_WRONG_PASSPHRASE;
  757. } else {
  758. error = "MAC failed";
  759. ret = NULL;
  760. }
  761. goto error;
  762. }
  763. }
  764. sfree(mac);
  765. mac = NULL;
  766. /*
  767. * Create and return the key.
  768. */
  769. ret = snew(struct ssh2_userkey);
  770. ret->alg = alg;
  771. ret->comment = comment;
  772. ret->data = alg->createkey(alg, public_blob, public_blob_len,
  773. private_blob, private_blob_len);
  774. if (!ret->data) {
  775. sfree(ret);
  776. ret = NULL;
  777. error = "createkey failed";
  778. goto error;
  779. }
  780. sfree(public_blob);
  781. smemclr(private_blob, private_blob_len);
  782. sfree(private_blob);
  783. sfree(encryption);
  784. if (errorstr)
  785. *errorstr = NULL;
  786. return ret;
  787. /*
  788. * Error processing.
  789. */
  790. error:
  791. if (fp)
  792. fclose(fp);
  793. if (comment)
  794. sfree(comment);
  795. if (encryption)
  796. sfree(encryption);
  797. if (mac)
  798. sfree(mac);
  799. if (public_blob)
  800. sfree(public_blob);
  801. if (private_blob) {
  802. smemclr(private_blob, private_blob_len);
  803. sfree(private_blob);
  804. }
  805. if (errorstr)
  806. *errorstr = error;
  807. return ret;
  808. }
  809. unsigned char *rfc4716_loadpub(FILE *fp, char **algorithm,
  810. int *pub_blob_len, char **commentptr,
  811. const char **errorstr)
  812. {
  813. const char *error;
  814. char *line, *colon, *value;
  815. char *comment = NULL;
  816. unsigned char *pubblob = NULL;
  817. int pubbloblen, pubblobsize;
  818. char base64in[4];
  819. unsigned char base64out[3];
  820. int base64bytes;
  821. int alglen;
  822. line = chomp(fgetline(fp));
  823. if (!line || 0 != strcmp(line, "---- BEGIN SSH2 PUBLIC KEY ----")) {
  824. error = "invalid begin line in SSH-2 public key file";
  825. goto error;
  826. }
  827. sfree(line); line = NULL;
  828. while (1) {
  829. line = chomp(fgetline(fp));
  830. if (!line) {
  831. error = "truncated SSH-2 public key file";
  832. goto error;
  833. }
  834. colon = strstr(line, ": ");
  835. if (!colon)
  836. break;
  837. *colon = '\0';
  838. value = colon + 2;
  839. if (!strcmp(line, "Comment")) {
  840. char *p, *q;
  841. /* Remove containing double quotes, if present */
  842. p = value;
  843. if (*p == '"' && p[strlen(p)-1] == '"') {
  844. p[strlen(p)-1] = '\0';
  845. p++;
  846. }
  847. /* Remove \-escaping, not in RFC4716 but seen in the wild
  848. * in practice. */
  849. for (q = line; *p; p++) {
  850. if (*p == '\\' && p[1])
  851. p++;
  852. *q++ = *p;
  853. }
  854. *q = '\0';
  855. comment = dupstr(line);
  856. } else if (!strcmp(line, "Subject") ||
  857. !strncmp(line, "x-", 2)) {
  858. /* Headers we recognise and ignore. Do nothing. */
  859. } else {
  860. error = "unrecognised header in SSH-2 public key file";
  861. goto error;
  862. }
  863. sfree(line); line = NULL;
  864. }
  865. /*
  866. * Now line contains the initial line of base64 data. Loop round
  867. * while it still does contain base64.
  868. */
  869. pubblobsize = 4096;
  870. pubblob = snewn(pubblobsize, unsigned char);
  871. pubbloblen = 0;
  872. base64bytes = 0;
  873. while (line && line[0] != '-') {
  874. char *p;
  875. for (p = line; *p; p++) {
  876. base64in[base64bytes++] = *p;
  877. if (base64bytes == 4) {
  878. int n = base64_decode_atom(base64in, base64out);
  879. if (pubbloblen + n > pubblobsize) {
  880. pubblobsize = (pubbloblen + n) * 5 / 4 + 1024;
  881. pubblob = sresize(pubblob, pubblobsize, unsigned char);
  882. }
  883. memcpy(pubblob + pubbloblen, base64out, n);
  884. pubbloblen += n;
  885. base64bytes = 0;
  886. }
  887. }
  888. sfree(line); line = NULL;
  889. line = chomp(fgetline(fp));
  890. }
  891. /*
  892. * Finally, check the END line makes sense.
  893. */
  894. if (!line || 0 != strcmp(line, "---- END SSH2 PUBLIC KEY ----")) {
  895. error = "invalid end line in SSH-2 public key file";
  896. goto error;
  897. }
  898. sfree(line); line = NULL;
  899. /*
  900. * OK, we now have a public blob and optionally a comment. We must
  901. * return the key algorithm string too, so look for that at the
  902. * start of the public blob.
  903. */
  904. if (pubbloblen < 4) {
  905. error = "not enough data in SSH-2 public key file";
  906. goto error;
  907. }
  908. alglen = toint(GET_32BIT(pubblob));
  909. if (alglen < 0 || alglen > pubbloblen-4) {
  910. error = "invalid algorithm prefix in SSH-2 public key file";
  911. goto error;
  912. }
  913. if (algorithm)
  914. *algorithm = dupprintf("%.*s", alglen, pubblob+4);
  915. if (pub_blob_len)
  916. *pub_blob_len = pubbloblen;
  917. if (commentptr)
  918. *commentptr = comment;
  919. else
  920. sfree(comment);
  921. return pubblob;
  922. error:
  923. sfree(line);
  924. sfree(comment);
  925. sfree(pubblob);
  926. if (errorstr)
  927. *errorstr = error;
  928. return NULL;
  929. }
  930. unsigned char *openssh_loadpub(FILE *fp, char **algorithm,
  931. int *pub_blob_len, char **commentptr,
  932. const char **errorstr)
  933. {
  934. const char *error;
  935. char *line, *base64;
  936. char *comment = NULL;
  937. unsigned char *pubblob = NULL;
  938. int pubbloblen, pubblobsize;
  939. int alglen;
  940. line = chomp(fgetline(fp));
  941. base64 = strchr(line, ' ');
  942. if (!base64) {
  943. error = "no key blob in OpenSSH public key file";
  944. goto error;
  945. }
  946. *base64++ = '\0';
  947. comment = strchr(base64, ' ');
  948. if (comment) {
  949. *comment++ = '\0';
  950. comment = dupstr(comment);
  951. }
  952. pubblobsize = strlen(base64) / 4 * 3;
  953. pubblob = snewn(pubblobsize, unsigned char);
  954. pubbloblen = 0;
  955. while (!memchr(base64, '\0', 4)) {
  956. assert(pubbloblen + 3 <= pubblobsize);
  957. pubbloblen += base64_decode_atom(base64, pubblob + pubbloblen);
  958. base64 += 4;
  959. }
  960. if (*base64) {
  961. error = "invalid length for base64 data in OpenSSH public key file";
  962. goto error;
  963. }
  964. /*
  965. * Sanity check: the first word on the line should be the key
  966. * algorithm, and should match the encoded string at the start of
  967. * the public blob.
  968. */
  969. alglen = strlen(line);
  970. if (pubbloblen < alglen + 4 ||
  971. GET_32BIT(pubblob) != alglen ||
  972. 0 != memcmp(pubblob + 4, line, alglen)) {
  973. error = "key algorithms do not match in OpenSSH public key file";
  974. goto error;
  975. }
  976. /*
  977. * Done.
  978. */
  979. if (algorithm)
  980. *algorithm = dupstr(line);
  981. if (pub_blob_len)
  982. *pub_blob_len = pubbloblen;
  983. if (commentptr)
  984. *commentptr = comment;
  985. else
  986. sfree(comment);
  987. sfree(line);
  988. return pubblob;
  989. error:
  990. sfree(line);
  991. sfree(comment);
  992. sfree(pubblob);
  993. if (errorstr)
  994. *errorstr = error;
  995. return NULL;
  996. }
  997. unsigned char *ssh2_userkey_loadpub(const Filename *filename, char **algorithm,
  998. int *pub_blob_len, char **commentptr,
  999. const char **errorstr)
  1000. {
  1001. FILE *fp;
  1002. char header[40], *b;
  1003. const struct ssh_signkey *alg;
  1004. unsigned char *public_blob;
  1005. int public_blob_len;
  1006. int type, i;
  1007. const char *error = NULL;
  1008. char *comment = NULL;
  1009. public_blob = NULL;
  1010. fp = f_open(filename, "rb", FALSE);
  1011. if (!fp) {
  1012. error = "can't open file";
  1013. goto error;
  1014. }
  1015. /* Initially, check if this is a public-only key file. Sometimes
  1016. * we'll be asked to read a public blob from one of those. */
  1017. type = key_type_fp(fp);
  1018. if (type == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {
  1019. unsigned char *ret = rfc4716_loadpub(fp, algorithm, pub_blob_len,
  1020. commentptr, errorstr);
  1021. fclose(fp);
  1022. return ret;
  1023. } else if (type == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  1024. unsigned char *ret = openssh_loadpub(fp, algorithm, pub_blob_len,
  1025. commentptr, errorstr);
  1026. fclose(fp);
  1027. return ret;
  1028. } else if (type != SSH_KEYTYPE_SSH2) {
  1029. error = "not a PuTTY SSH-2 private key";
  1030. goto error;
  1031. }
  1032. /* Read the first header line which contains the key type. */
  1033. if (!read_header(fp, header)
  1034. || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
  1035. 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
  1036. if (0 == strncmp(header, "PuTTY-User-Key-File-", 20))
  1037. error = "PuTTY key format too new";
  1038. else
  1039. error = "not a PuTTY SSH-2 private key";
  1040. goto error;
  1041. }
  1042. error = "file format error";
  1043. if ((b = read_body(fp)) == NULL)
  1044. goto error;
  1045. /* Select key algorithm structure. */
  1046. alg = find_pubkey_alg(b);
  1047. sfree(b);
  1048. if (!alg) {
  1049. goto error;
  1050. }
  1051. /* Read the Encryption header line. */
  1052. if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
  1053. goto error;
  1054. if ((b = read_body(fp)) == NULL)
  1055. goto error;
  1056. sfree(b); /* we don't care */
  1057. /* Read the Comment header line. */
  1058. if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
  1059. goto error;
  1060. if ((comment = read_body(fp)) == NULL)
  1061. goto error;
  1062. if (commentptr)
  1063. *commentptr = comment;
  1064. else
  1065. sfree(comment);
  1066. /* Read the Public-Lines header line and the public blob. */
  1067. if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
  1068. goto error;
  1069. if ((b = read_body(fp)) == NULL)
  1070. goto error;
  1071. i = atoi(b);
  1072. sfree(b);
  1073. if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
  1074. goto error;
  1075. fclose(fp);
  1076. if (pub_blob_len)
  1077. *pub_blob_len = public_blob_len;
  1078. if (algorithm)
  1079. *algorithm = dupstr(alg->name);
  1080. return public_blob;
  1081. /*
  1082. * Error processing.
  1083. */
  1084. error:
  1085. if (fp)
  1086. fclose(fp);
  1087. if (public_blob)
  1088. sfree(public_blob);
  1089. if (errorstr)
  1090. *errorstr = error;
  1091. if (comment && commentptr) {
  1092. sfree(comment);
  1093. *commentptr = NULL;
  1094. }
  1095. return NULL;
  1096. }
  1097. int ssh2_userkey_encrypted(const Filename *filename, char **commentptr)
  1098. {
  1099. FILE *fp;
  1100. char header[40], *b, *comment;
  1101. int ret;
  1102. if (commentptr)
  1103. *commentptr = NULL;
  1104. fp = f_open(filename, "rb", FALSE);
  1105. if (!fp)
  1106. return 0;
  1107. if (!read_header(fp, header)
  1108. || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
  1109. 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
  1110. fclose(fp);
  1111. return 0;
  1112. }
  1113. if ((b = read_body(fp)) == NULL) {
  1114. fclose(fp);
  1115. return 0;
  1116. }
  1117. sfree(b); /* we don't care about key type here */
  1118. /* Read the Encryption header line. */
  1119. if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
  1120. fclose(fp);
  1121. return 0;
  1122. }
  1123. if ((b = read_body(fp)) == NULL) {
  1124. fclose(fp);
  1125. return 0;
  1126. }
  1127. /* Read the Comment header line. */
  1128. if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
  1129. fclose(fp);
  1130. sfree(b);
  1131. return 1;
  1132. }
  1133. if ((comment = read_body(fp)) == NULL) {
  1134. fclose(fp);
  1135. sfree(b);
  1136. return 1;
  1137. }
  1138. if (commentptr)
  1139. *commentptr = comment;
  1140. else
  1141. sfree(comment);
  1142. fclose(fp);
  1143. if (!strcmp(b, "aes256-cbc"))
  1144. ret = 1;
  1145. else
  1146. ret = 0;
  1147. sfree(b);
  1148. return ret;
  1149. }
  1150. int base64_lines(int datalen)
  1151. {
  1152. /* When encoding, we use 64 chars/line, which equals 48 real chars. */
  1153. return (datalen + 47) / 48;
  1154. }
  1155. void base64_encode(FILE *fp, const unsigned char *data, int datalen, int cpl)
  1156. {
  1157. int linelen = 0;
  1158. char out[4];
  1159. int n, i;
  1160. while (datalen > 0) {
  1161. n = (datalen < 3 ? datalen : 3);
  1162. base64_encode_atom(data, n, out);
  1163. data += n;
  1164. datalen -= n;
  1165. for (i = 0; i < 4; i++) {
  1166. if (linelen >= cpl) {
  1167. linelen = 0;
  1168. fputc('\n', fp);
  1169. }
  1170. fputc(out[i], fp);
  1171. linelen++;
  1172. }
  1173. }
  1174. fputc('\n', fp);
  1175. }
  1176. int ssh2_save_userkey(const Filename *filename, struct ssh2_userkey *key,
  1177. char *passphrase)
  1178. {
  1179. FILE *fp;
  1180. unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
  1181. int pub_blob_len, priv_blob_len, priv_encrypted_len;
  1182. int passlen;
  1183. int cipherblk;
  1184. int i;
  1185. const char *cipherstr;
  1186. unsigned char priv_mac[20];
  1187. /*
  1188. * Fetch the key component blobs.
  1189. */
  1190. pub_blob = key->alg->public_blob(key->data, &pub_blob_len);
  1191. priv_blob = key->alg->private_blob(key->data, &priv_blob_len);
  1192. if (!pub_blob || !priv_blob) {
  1193. sfree(pub_blob);
  1194. sfree(priv_blob);
  1195. return 0;
  1196. }
  1197. /*
  1198. * Determine encryption details, and encrypt the private blob.
  1199. */
  1200. if (passphrase) {
  1201. cipherstr = "aes256-cbc";
  1202. cipherblk = 16;
  1203. } else {
  1204. cipherstr = "none";
  1205. cipherblk = 1;
  1206. }
  1207. priv_encrypted_len = priv_blob_len + cipherblk - 1;
  1208. priv_encrypted_len -= priv_encrypted_len % cipherblk;
  1209. priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);
  1210. memset(priv_blob_encrypted, 0, priv_encrypted_len);
  1211. memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);
  1212. /* Create padding based on the SHA hash of the unpadded blob. This prevents
  1213. * too easy a known-plaintext attack on the last block. */
  1214. SHA_Simple(priv_blob, priv_blob_len, priv_mac);
  1215. assert(priv_encrypted_len - priv_blob_len < 20);
  1216. memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,
  1217. priv_encrypted_len - priv_blob_len);
  1218. /* Now create the MAC. */
  1219. {
  1220. unsigned char *macdata;
  1221. int maclen;
  1222. unsigned char *p;
  1223. int namelen = strlen(key->alg->name);
  1224. int enclen = strlen(cipherstr);
  1225. int commlen = strlen(key->comment);
  1226. SHA_State s;
  1227. unsigned char mackey[20];
  1228. char header[] = "putty-private-key-file-mac-key";
  1229. maclen = (4 + namelen +
  1230. 4 + enclen +
  1231. 4 + commlen +
  1232. 4 + pub_blob_len +
  1233. 4 + priv_encrypted_len);
  1234. macdata = snewn(maclen, unsigned char);
  1235. p = macdata;
  1236. #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
  1237. DO_STR(key->alg->name, namelen);
  1238. DO_STR(cipherstr, enclen);
  1239. DO_STR(key->comment, commlen);
  1240. DO_STR(pub_blob, pub_blob_len);
  1241. DO_STR(priv_blob_encrypted, priv_encrypted_len);
  1242. SHA_Init(&s);
  1243. SHA_Bytes(&s, header, sizeof(header)-1);
  1244. if (passphrase)
  1245. SHA_Bytes(&s, passphrase, strlen(passphrase));
  1246. SHA_Final(&s, mackey);
  1247. hmac_sha1_simple(mackey, 20, macdata, maclen, priv_mac);
  1248. smemclr(macdata, maclen);
  1249. sfree(macdata);
  1250. smemclr(mackey, sizeof(mackey));
  1251. smemclr(&s, sizeof(s));
  1252. }
  1253. if (passphrase) {
  1254. unsigned char key[40];
  1255. SHA_State s;
  1256. passlen = strlen(passphrase);
  1257. SHA_Init(&s);
  1258. SHA_Bytes(&s, "\0\0\0\0", 4);
  1259. SHA_Bytes(&s, passphrase, passlen);
  1260. SHA_Final(&s, key + 0);
  1261. SHA_Init(&s);
  1262. SHA_Bytes(&s, "\0\0\0\1", 4);
  1263. SHA_Bytes(&s, passphrase, passlen);
  1264. SHA_Final(&s, key + 20);
  1265. aes256_encrypt_pubkey(key, priv_blob_encrypted,
  1266. priv_encrypted_len);
  1267. smemclr(key, sizeof(key));
  1268. smemclr(&s, sizeof(s));
  1269. }
  1270. fp = f_open(filename, "w", TRUE);
  1271. if (!fp) {
  1272. sfree(pub_blob);
  1273. smemclr(priv_blob, priv_blob_len);
  1274. sfree(priv_blob);
  1275. smemclr(priv_blob_encrypted, priv_blob_len);
  1276. sfree(priv_blob_encrypted);
  1277. return 0;
  1278. }
  1279. fprintf(fp, "PuTTY-User-Key-File-2: %s\n", key->alg->name);
  1280. fprintf(fp, "Encryption: %s\n", cipherstr);
  1281. fprintf(fp, "Comment: %s\n", key->comment);
  1282. fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));
  1283. base64_encode(fp, pub_blob, pub_blob_len, 64);
  1284. fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
  1285. base64_encode(fp, priv_blob_encrypted, priv_encrypted_len, 64);
  1286. fprintf(fp, "Private-MAC: ");
  1287. for (i = 0; i < 20; i++)
  1288. fprintf(fp, "%02x", priv_mac[i]);
  1289. fprintf(fp, "\n");
  1290. fclose(fp);
  1291. sfree(pub_blob);
  1292. smemclr(priv_blob, priv_blob_len);
  1293. sfree(priv_blob);
  1294. smemclr(priv_blob_encrypted, priv_blob_len);
  1295. sfree(priv_blob_encrypted);
  1296. return 1;
  1297. }
  1298. /* ----------------------------------------------------------------------
  1299. * Output public keys.
  1300. */
  1301. char *ssh1_pubkey_str(struct RSAKey *key)
  1302. {
  1303. char *buffer;
  1304. char *dec1, *dec2;
  1305. dec1 = bignum_decimal(key->exponent);
  1306. dec2 = bignum_decimal(key->modulus);
  1307. buffer = dupprintf("%d %s %s%s%s", bignum_bitcount(key->modulus),
  1308. dec1, dec2,
  1309. key->comment ? " " : "",
  1310. key->comment ? key->comment : "");
  1311. sfree(dec1);
  1312. sfree(dec2);
  1313. return buffer;
  1314. }
  1315. void ssh1_write_pubkey(FILE *fp, struct RSAKey *key)
  1316. {
  1317. char *buffer = ssh1_pubkey_str(key);
  1318. fprintf(fp, "%s\n", buffer);
  1319. sfree(buffer);
  1320. }
  1321. static char *ssh2_pubkey_openssh_str_internal(const char *comment,
  1322. const void *v_pub_blob,
  1323. int pub_len)
  1324. {
  1325. const unsigned char *ssh2blob = (const unsigned char *)v_pub_blob;
  1326. const char *alg;
  1327. int alglen;
  1328. char *buffer, *p;
  1329. int i;
  1330. if (pub_len < 4) {
  1331. alg = NULL;
  1332. } else {
  1333. alglen = GET_32BIT(ssh2blob);
  1334. if (alglen > 0 && alglen < pub_len - 4) {
  1335. alg = (const char *)ssh2blob + 4;
  1336. } else {
  1337. alg = NULL;
  1338. }
  1339. }
  1340. if (!alg) {
  1341. alg = "INVALID-ALGORITHM";
  1342. alglen = strlen(alg);
  1343. }
  1344. buffer = snewn(alglen +
  1345. 4 * ((pub_len+2) / 3) +
  1346. (comment ? strlen(comment) : 0) + 3, char);
  1347. p = buffer + sprintf(buffer, "%.*s ", alglen, alg);
  1348. i = 0;
  1349. while (i < pub_len) {
  1350. int n = (pub_len - i < 3 ? pub_len - i : 3);
  1351. base64_encode_atom(ssh2blob + i, n, p);
  1352. i += n;
  1353. p += 4;
  1354. }
  1355. if (*comment) {
  1356. *p++ = ' ';
  1357. strcpy(p, comment);
  1358. } else
  1359. *p++ = '\0';
  1360. return buffer;
  1361. }
  1362. char *ssh2_pubkey_openssh_str(struct ssh2_userkey *key)
  1363. {
  1364. int bloblen;
  1365. unsigned char *blob;
  1366. char *ret;
  1367. blob = key->alg->public_blob(key->data, &bloblen);
  1368. ret = ssh2_pubkey_openssh_str_internal(key->comment, blob, bloblen);
  1369. sfree(blob);
  1370. return ret;
  1371. }
  1372. void ssh2_write_pubkey(FILE *fp, const char *comment,
  1373. const void *v_pub_blob, int pub_len,
  1374. int keytype)
  1375. {
  1376. unsigned char *pub_blob = (unsigned char *)v_pub_blob;
  1377. if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {
  1378. const char *p;
  1379. int i, column;
  1380. fprintf(fp, "---- BEGIN SSH2 PUBLIC KEY ----\n");
  1381. if (comment) {
  1382. fprintf(fp, "Comment: \"");
  1383. for (p = comment; *p; p++) {
  1384. if (*p == '\\' || *p == '\"')
  1385. fputc('\\', fp);
  1386. fputc(*p, fp);
  1387. }
  1388. fprintf(fp, "\"\n");
  1389. }
  1390. i = 0;
  1391. column = 0;
  1392. while (i < pub_len) {
  1393. char buf[5];
  1394. int n = (pub_len - i < 3 ? pub_len - i : 3);
  1395. base64_encode_atom(pub_blob + i, n, buf);
  1396. i += n;
  1397. buf[4] = '\0';
  1398. fputs(buf, fp);
  1399. if (++column >= 16) {
  1400. fputc('\n', fp);
  1401. column = 0;
  1402. }
  1403. }
  1404. if (column > 0)
  1405. fputc('\n', fp);
  1406. fprintf(fp, "---- END SSH2 PUBLIC KEY ----\n");
  1407. } else if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  1408. char *buffer = ssh2_pubkey_openssh_str_internal(comment,
  1409. v_pub_blob, pub_len);
  1410. fprintf(fp, "%s\n", buffer);
  1411. sfree(buffer);
  1412. } else {
  1413. assert(0 && "Bad key type in ssh2_write_pubkey");
  1414. }
  1415. }
  1416. /* ----------------------------------------------------------------------
  1417. * Utility functions to compute SSH-2 fingerprints in a uniform way.
  1418. */
  1419. char *ssh2_fingerprint_blob(const void *blob, int bloblen)
  1420. {
  1421. unsigned char digest[16];
  1422. char fingerprint_str[16*3];
  1423. const char *algstr;
  1424. int alglen;
  1425. const struct ssh_signkey *alg;
  1426. int i;
  1427. /*
  1428. * The fingerprint hash itself is always just the MD5 of the blob.
  1429. */
  1430. MD5Simple(blob, bloblen, digest);
  1431. for (i = 0; i < 16; i++)
  1432. sprintf(fingerprint_str + i*3, "%02x%s", digest[i], i==15 ? "" : ":");
  1433. /*
  1434. * Identify the key algorithm, if possible.
  1435. */
  1436. alglen = toint(GET_32BIT((const unsigned char *)blob));
  1437. if (alglen > 0 && alglen < bloblen-4) {
  1438. algstr = (const char *)blob + 4;
  1439. /*
  1440. * If we can actually identify the algorithm as one we know
  1441. * about, get hold of the key's bit count too.
  1442. */
  1443. alg = find_pubkey_alg_len(alglen, algstr);
  1444. if (alg) {
  1445. int bits = alg->pubkey_bits(alg, blob, bloblen);
  1446. return dupprintf("%.*s %d %s", alglen, algstr,
  1447. bits, fingerprint_str);
  1448. } else {
  1449. return dupprintf("%.*s %s", alglen, algstr, fingerprint_str);
  1450. }
  1451. } else {
  1452. /*
  1453. * No algorithm available (which means a seriously confused
  1454. * key blob, but there we go). Return only the hash.
  1455. */
  1456. return dupstr(fingerprint_str);
  1457. }
  1458. }
  1459. char *ssh2_fingerprint(const struct ssh_signkey *alg, void *data)
  1460. {
  1461. int len;
  1462. unsigned char *blob = alg->public_blob(data, &len);
  1463. char *ret = ssh2_fingerprint_blob(blob, len);
  1464. sfree(blob);
  1465. return ret;
  1466. }
  1467. /* ----------------------------------------------------------------------
  1468. * Determine the type of a private key file.
  1469. */
  1470. static int key_type_fp(FILE *fp)
  1471. {
  1472. char buf[1024];
  1473. const char public_std_sig[] = "---- BEGIN SSH2 PUBLIC KEY";
  1474. const char putty2_sig[] = "PuTTY-User-Key-File-";
  1475. const char sshcom_sig[] = "---- BEGIN SSH2 ENCRYPTED PRIVAT";
  1476. const char openssh_new_sig[] = "-----BEGIN OPENSSH PRIVATE KEY";
  1477. const char openssh_sig[] = "-----BEGIN ";
  1478. int i;
  1479. char *p;
  1480. i = fread(buf, 1, sizeof(buf)-1, fp);
  1481. rewind(fp);
  1482. if (i < 0)
  1483. return SSH_KEYTYPE_UNOPENABLE;
  1484. if (i < 32)
  1485. return SSH_KEYTYPE_UNKNOWN;
  1486. assert(i > 0 && i < sizeof(buf));
  1487. buf[i] = '\0';
  1488. if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1))
  1489. return SSH_KEYTYPE_SSH1;
  1490. if (!memcmp(buf, public_std_sig, sizeof(public_std_sig)-1))
  1491. return SSH_KEYTYPE_SSH2_PUBLIC_RFC4716;
  1492. if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1))
  1493. return SSH_KEYTYPE_SSH2;
  1494. if (!memcmp(buf, openssh_new_sig, sizeof(openssh_new_sig)-1))
  1495. return SSH_KEYTYPE_OPENSSH_NEW;
  1496. if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1))
  1497. return SSH_KEYTYPE_OPENSSH_PEM;
  1498. if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1))
  1499. return SSH_KEYTYPE_SSHCOM;
  1500. if ((p = buf + strspn(buf, "0123456789"), *p == ' ') &&
  1501. (p = p+1 + strspn(p+1, "0123456789"), *p == ' ') &&
  1502. (p = p+1 + strspn(p+1, "0123456789"), *p == ' ' || *p == '\n' || !*p))
  1503. return SSH_KEYTYPE_SSH1_PUBLIC;
  1504. if ((p = buf + strcspn(buf, " "), find_pubkey_alg_len(p-buf, buf)) &&
  1505. (p = p+1 + strspn(p+1, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij"
  1506. "klmnopqrstuvwxyz+/="),
  1507. *p == ' ' || *p == '\n' || !*p))
  1508. return SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH;
  1509. return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */
  1510. }
  1511. int key_type(const Filename *filename)
  1512. {
  1513. FILE *fp;
  1514. int ret;
  1515. fp = f_open(filename, "r", FALSE);
  1516. if (!fp)
  1517. return SSH_KEYTYPE_UNOPENABLE;
  1518. ret = key_type_fp(fp);
  1519. fclose(fp);
  1520. return ret;
  1521. }
  1522. /*
  1523. * Convert the type word to a string, for `wrong type' error
  1524. * messages.
  1525. */
  1526. const char *key_type_to_str(int type)
  1527. {
  1528. switch (type) {
  1529. case SSH_KEYTYPE_UNOPENABLE: return "unable to open file"; break;
  1530. case SSH_KEYTYPE_UNKNOWN: return "not a recognised key file format"; break;
  1531. case SSH_KEYTYPE_SSH1_PUBLIC: return "SSH-1 public key"; break;
  1532. case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716: return "SSH-2 public key (RFC 4716 format)"; break;
  1533. case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH: return "SSH-2 public key (OpenSSH format)"; break;
  1534. case SSH_KEYTYPE_SSH1: return "SSH-1 private key"; break;
  1535. case SSH_KEYTYPE_SSH2: return "PuTTY SSH-2 private key"; break;
  1536. case SSH_KEYTYPE_OPENSSH_PEM: return "OpenSSH SSH-2 private key (old PEM format)"; break;
  1537. case SSH_KEYTYPE_OPENSSH_NEW: return "OpenSSH SSH-2 private key (new format)"; break;
  1538. case SSH_KEYTYPE_SSHCOM: return "ssh.com SSH-2 private key"; break;
  1539. /*
  1540. * This function is called with a key type derived from
  1541. * looking at an actual key file, so the output-only type
  1542. * OPENSSH_AUTO should never get here, and is much an INTERNAL
  1543. * ERROR as a code we don't even understand.
  1544. */
  1545. case SSH_KEYTYPE_OPENSSH_AUTO: return "INTERNAL ERROR (OPENSSH_AUTO)"; break;
  1546. default: return "INTERNAL ERROR"; break;
  1547. }
  1548. }