sshpubk.c 46 KB

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