sshpubk.c 46 KB

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