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