sshpubk.c 46 KB

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