sshpubk.c 45 KB

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