sshpubk.c 45 KB

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