sshpubk.c 48 KB

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