sshpubk.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975
  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 <string.h>
  9. #include <errno.h>
  10. #include <stdlib.h>
  11. #include <assert.h>
  12. #include <ctype.h>
  13. #include "putty.h"
  14. #include "mpint.h"
  15. #include "ssh.h"
  16. #include "misc.h"
  17. /*
  18. * Fairly arbitrary size limit on any public or private key blob.
  19. * Chosen to match AGENT_MAX_MSGLEN, on the basis that any key too
  20. * large to transfer over the ssh-agent protocol is probably too large
  21. * to be useful in general.
  22. *
  23. * MAX_KEY_BLOB_LINES is the corresponding limit on the Public-Lines
  24. * or Private-Lines header field in a key file.
  25. */
  26. #define MAX_KEY_BLOB_SIZE 262144
  27. #define MAX_KEY_BLOB_LINES (MAX_KEY_BLOB_SIZE / 48)
  28. /*
  29. * Corresponding limit on the size of a key _file_ itself, based on
  30. * base64-encoding the key blob and then adding a few Kb for
  31. * surrounding metadata.
  32. */
  33. #define MAX_KEY_FILE_SIZE (MAX_KEY_BLOB_SIZE * 4 / 3 + 4096)
  34. static const ptrlen rsa1_signature =
  35. PTRLEN_DECL_LITERAL("SSH PRIVATE KEY FILE FORMAT 1.1\n\0");
  36. #define BASE64_TOINT(x) ( (x)-'A'<26 ? (x)-'A'+0 :\
  37. (x)-'a'<26 ? (x)-'a'+26 :\
  38. (x)-'0'<10 ? (x)-'0'+52 :\
  39. (x)=='+' ? 62 : \
  40. (x)=='/' ? 63 : 0 )
  41. LoadedFile *lf_new(size_t max_size)
  42. {
  43. LoadedFile *lf = snew_plus(LoadedFile, max_size);
  44. lf->data = snew_plus_get_aux(lf);
  45. lf->len = 0;
  46. lf->max_size = max_size;
  47. return lf;
  48. }
  49. void lf_free(LoadedFile *lf)
  50. {
  51. smemclr(lf->data, lf->max_size);
  52. smemclr(lf, sizeof(LoadedFile));
  53. sfree(lf);
  54. }
  55. LoadFileStatus lf_load_fp(LoadedFile *lf, FILE *fp)
  56. {
  57. lf->len = 0;
  58. while (lf->len < lf->max_size) {
  59. size_t retd = fread(lf->data + lf->len, 1, lf->max_size - lf->len, fp);
  60. if (ferror(fp))
  61. return LF_ERROR;
  62. if (retd == 0)
  63. break;
  64. lf->len += retd;
  65. }
  66. LoadFileStatus status = LF_OK;
  67. if (lf->len == lf->max_size) {
  68. /* The file might be too long to fit in our fixed-size
  69. * structure. Try reading one more byte, to check. */
  70. if (fgetc(fp) != EOF)
  71. status = LF_TOO_BIG;
  72. }
  73. BinarySource_INIT(lf, lf->data, lf->len);
  74. return status;
  75. }
  76. LoadFileStatus lf_load(LoadedFile *lf, const Filename *filename)
  77. {
  78. FILE *fp = f_open(filename, "rb", false);
  79. if (!fp)
  80. return LF_ERROR;
  81. LoadFileStatus status = lf_load_fp(lf, fp);
  82. fclose(fp);
  83. return status;
  84. }
  85. static inline bool lf_load_keyfile_helper(LoadFileStatus status,
  86. const char **errptr)
  87. {
  88. const char *error;
  89. switch (status) {
  90. case LF_OK:
  91. return true;
  92. case LF_TOO_BIG:
  93. error = "file is too large to be a key file";
  94. break;
  95. case LF_ERROR:
  96. error = strerror(errno);
  97. break;
  98. default:
  99. unreachable("bad status value in lf_load_keyfile_helper");
  100. }
  101. if (errptr)
  102. *errptr = error;
  103. return false;
  104. }
  105. LoadedFile *lf_load_keyfile(const Filename *filename, const char **errptr)
  106. {
  107. LoadedFile *lf = lf_new(MAX_KEY_FILE_SIZE);
  108. if (!lf_load_keyfile_helper(lf_load(lf, filename), errptr)) {
  109. lf_free(lf);
  110. return NULL;
  111. }
  112. return lf;
  113. }
  114. LoadedFile *lf_load_keyfile_fp(FILE *fp, const char **errptr)
  115. {
  116. LoadedFile *lf = lf_new(MAX_KEY_FILE_SIZE);
  117. if (!lf_load_keyfile_helper(lf_load_fp(lf, fp), errptr)) {
  118. lf_free(lf);
  119. return NULL;
  120. }
  121. return lf;
  122. }
  123. static bool expect_signature(BinarySource *src, ptrlen realsig)
  124. {
  125. ptrlen thissig = get_data(src, realsig.len);
  126. return !get_err(src) && ptrlen_eq_ptrlen(realsig, thissig);
  127. }
  128. static int rsa1_load_s_internal(BinarySource *src, RSAKey *key, bool pub_only,
  129. char **commentptr, const char *passphrase,
  130. const char **error)
  131. {
  132. strbuf *buf = NULL;
  133. int ciphertype;
  134. int ret = 0;
  135. ptrlen comment;
  136. *error = "not an SSH-1 RSA file";
  137. if (!expect_signature(src, rsa1_signature))
  138. goto end;
  139. *error = "file format error";
  140. /* One byte giving encryption type, and one reserved uint32. */
  141. ciphertype = get_byte(src);
  142. if (ciphertype != 0 && ciphertype != SSH1_CIPHER_3DES)
  143. goto end;
  144. if (get_uint32(src) != 0)
  145. goto end; /* reserved field nonzero, panic! */
  146. /* Now the serious stuff. An ordinary SSH-1 public key. */
  147. get_rsa_ssh1_pub(src, key, RSA_SSH1_MODULUS_FIRST);
  148. /* Next, the comment field. */
  149. comment = get_string(src);
  150. if (commentptr)
  151. *commentptr = mkstr(comment);
  152. if (key)
  153. key->comment = mkstr(comment);
  154. if (pub_only) {
  155. ret = 1;
  156. goto end;
  157. }
  158. if (!key) {
  159. ret = ciphertype != 0;
  160. *error = NULL;
  161. goto end;
  162. }
  163. /*
  164. * Decrypt remainder of buffer.
  165. */
  166. if (ciphertype) {
  167. size_t enclen = get_avail(src);
  168. if (enclen & 7)
  169. goto end;
  170. buf = strbuf_dup_nm(get_data(src, enclen));
  171. unsigned char keybuf[16];
  172. hash_simple(&ssh_md5, ptrlen_from_asciz(passphrase), keybuf);
  173. des3_decrypt_pubkey(keybuf, buf->u, enclen);
  174. smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
  175. BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(buf));
  176. }
  177. /*
  178. * We are now in the secret part of the key. The first four
  179. * bytes should be of the form a, b, a, b.
  180. */
  181. {
  182. int b0a = get_byte(src);
  183. int b1a = get_byte(src);
  184. int b0b = get_byte(src);
  185. int b1b = get_byte(src);
  186. if (b0a != b0b || b1a != b1b) {
  187. *error = "wrong passphrase";
  188. ret = -1;
  189. goto end;
  190. }
  191. }
  192. /*
  193. * After that, we have one further bignum which is our
  194. * decryption exponent, and then the three auxiliary values
  195. * (iqmp, q, p).
  196. */
  197. get_rsa_ssh1_priv(src, key);
  198. key->iqmp = get_mp_ssh1(src);
  199. key->q = get_mp_ssh1(src);
  200. key->p = get_mp_ssh1(src);
  201. if (!rsa_verify(key)) {
  202. *error = "rsa_verify failed";
  203. freersakey(key);
  204. ret = 0;
  205. } else {
  206. *error = NULL;
  207. ret = 1;
  208. }
  209. end:
  210. if (buf)
  211. strbuf_free(buf);
  212. return ret;
  213. }
  214. int rsa1_load_s(BinarySource *src, RSAKey *key,
  215. const char *passphrase, const char **errstr)
  216. {
  217. return rsa1_load_s_internal(src, key, false, NULL, passphrase, errstr);
  218. }
  219. int rsa1_load_f(const Filename *filename, RSAKey *key,
  220. const char *passphrase, const char **errstr)
  221. {
  222. LoadedFile *lf = lf_load_keyfile(filename, errstr);
  223. if (!lf)
  224. return false;
  225. int toret = rsa1_load_s(BinarySource_UPCAST(lf), key, passphrase, errstr);
  226. lf_free(lf);
  227. return toret;
  228. }
  229. /*
  230. * See whether an RSA key is encrypted. Return its comment field as
  231. * well.
  232. */
  233. bool rsa1_encrypted_s(BinarySource *src, char **comment)
  234. {
  235. const char *dummy;
  236. return rsa1_load_s_internal(src, NULL, false, comment, NULL, &dummy) == 1;
  237. }
  238. bool rsa1_encrypted_f(const Filename *filename, char **comment)
  239. {
  240. LoadedFile *lf = lf_load_keyfile(filename, NULL);
  241. if (!lf)
  242. return false; /* couldn't even open the file */
  243. bool toret = rsa1_encrypted_s(BinarySource_UPCAST(lf), comment);
  244. lf_free(lf);
  245. return toret;
  246. }
  247. /*
  248. * Read the public part of an SSH-1 RSA key from a file (public or
  249. * private), and generate its public blob in exponent-first order.
  250. */
  251. int rsa1_loadpub_s(BinarySource *src, BinarySink *bs,
  252. char **commentptr, const char **errorstr)
  253. {
  254. RSAKey key;
  255. int ret;
  256. const char *error = NULL;
  257. /* Default return if we fail. */
  258. ret = 0;
  259. bool is_privkey_file = expect_signature(src, rsa1_signature);
  260. BinarySource_REWIND(src);
  261. if (is_privkey_file) {
  262. /*
  263. * Load just the public half from an SSH-1 private key file.
  264. */
  265. memset(&key, 0, sizeof(key));
  266. if (rsa1_load_s_internal(src, &key, true, commentptr, NULL, &error)) {
  267. rsa_ssh1_public_blob(bs, &key, RSA_SSH1_EXPONENT_FIRST);
  268. freersakey(&key);
  269. ret = 1;
  270. }
  271. } else {
  272. /*
  273. * Try interpreting the file as an SSH-1 public key.
  274. */
  275. char *line, *p, *bitsp, *expp, *modp, *commentp;
  276. line = mkstr(get_chomped_line(src));
  277. p = line;
  278. bitsp = p;
  279. p += strspn(p, "0123456789");
  280. if (*p != ' ')
  281. goto not_public_either;
  282. *p++ = '\0';
  283. expp = p;
  284. p += strspn(p, "0123456789");
  285. if (*p != ' ')
  286. goto not_public_either;
  287. *p++ = '\0';
  288. modp = p;
  289. p += strspn(p, "0123456789");
  290. if (*p) {
  291. if (*p != ' ')
  292. goto not_public_either;
  293. *p++ = '\0';
  294. commentp = p;
  295. } else {
  296. commentp = NULL;
  297. }
  298. memset(&key, 0, sizeof(key));
  299. key.exponent = mp_from_decimal(expp);
  300. key.modulus = mp_from_decimal(modp);
  301. if (atoi(bitsp) != mp_get_nbits(key.modulus)) {
  302. mp_free(key.exponent);
  303. mp_free(key.modulus);
  304. sfree(line);
  305. error = "key bit count does not match in SSH-1 public key file";
  306. goto end;
  307. }
  308. if (commentptr)
  309. *commentptr = commentp ? dupstr(commentp) : NULL;
  310. rsa_ssh1_public_blob(bs, &key, RSA_SSH1_EXPONENT_FIRST);
  311. freersakey(&key);
  312. sfree(line);
  313. return 1;
  314. not_public_either:
  315. sfree(line);
  316. error = "not an SSH-1 RSA file";
  317. }
  318. end:
  319. if ((ret != 1) && errorstr)
  320. *errorstr = error;
  321. return ret;
  322. }
  323. int rsa1_loadpub_f(const Filename *filename, BinarySink *bs,
  324. char **commentptr, const char **errorstr)
  325. {
  326. LoadedFile *lf = lf_load_keyfile(filename, errorstr);
  327. if (!lf)
  328. return 0;
  329. int toret = rsa1_loadpub_s(BinarySource_UPCAST(lf), bs,
  330. commentptr, errorstr);
  331. lf_free(lf);
  332. return toret;
  333. }
  334. strbuf *rsa1_save_sb(RSAKey *key, const char *passphrase)
  335. {
  336. strbuf *buf = strbuf_new_nm();
  337. int estart;
  338. /*
  339. * The public part of the key.
  340. */
  341. put_datapl(buf, rsa1_signature);
  342. put_byte(buf, passphrase ? SSH1_CIPHER_3DES : 0); /* encryption type */
  343. put_uint32(buf, 0); /* reserved */
  344. rsa_ssh1_public_blob(BinarySink_UPCAST(buf), key,
  345. RSA_SSH1_MODULUS_FIRST);
  346. put_stringz(buf, NULLTOEMPTY(key->comment));
  347. /*
  348. * The encrypted portion starts here.
  349. */
  350. estart = buf->len;
  351. /*
  352. * Two bytes, then the same two bytes repeated.
  353. */
  354. {
  355. uint8_t bytes[2];
  356. random_read(bytes, 2);
  357. put_data(buf, bytes, 2);
  358. put_data(buf, bytes, 2);
  359. }
  360. /*
  361. * Four more bignums: the decryption exponent, then iqmp, then
  362. * q, then p.
  363. */
  364. put_mp_ssh1(buf, key->private_exponent);
  365. put_mp_ssh1(buf, key->iqmp);
  366. put_mp_ssh1(buf, key->q);
  367. put_mp_ssh1(buf, key->p);
  368. /*
  369. * Now write zeros until the encrypted portion is a multiple of
  370. * 8 bytes.
  371. */
  372. put_padding(buf, (estart - buf->len) & 7, 0);
  373. /*
  374. * Now encrypt the encrypted portion.
  375. */
  376. if (passphrase) {
  377. unsigned char keybuf[16];
  378. hash_simple(&ssh_md5, ptrlen_from_asciz(passphrase), keybuf);
  379. des3_encrypt_pubkey(keybuf, buf->u + estart, buf->len - estart);
  380. smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
  381. }
  382. return buf;
  383. }
  384. /*
  385. * Save an RSA key file. Return true on success.
  386. */
  387. bool rsa1_save_f(const Filename *filename, RSAKey *key, const char *passphrase)
  388. {
  389. FILE *fp = f_open(filename, "wb", true);
  390. if (!fp)
  391. return false;
  392. strbuf *buf = rsa1_save_sb(key, passphrase);
  393. bool toret = fwrite(buf->s, 1, buf->len, fp) == buf->len;
  394. if (fclose(fp))
  395. toret = false;
  396. strbuf_free(buf);
  397. return toret;
  398. }
  399. /* ----------------------------------------------------------------------
  400. * SSH-2 private key load/store functions.
  401. *
  402. * PuTTY's own file format for SSH-2 keys is given in doc/ppk.but, aka
  403. * the "PPK file format" appendix in the PuTTY manual.
  404. */
  405. static bool read_header(BinarySource *src, char *header)
  406. {
  407. int len = 39;
  408. int c;
  409. while (1) {
  410. c = get_byte(src);
  411. if (c == '\n' || c == '\r' || get_err(src))
  412. return false; /* failure */
  413. if (c == ':') {
  414. c = get_byte(src);
  415. if (c != ' ')
  416. return false;
  417. *header = '\0';
  418. return true; /* success! */
  419. }
  420. if (len == 0)
  421. return false; /* failure */
  422. *header++ = c;
  423. len--;
  424. }
  425. return false; /* failure */
  426. }
  427. static char *read_body(BinarySource *src)
  428. {
  429. strbuf *buf = strbuf_new_nm();
  430. while (1) {
  431. int c = get_byte(src);
  432. if (c == '\r' || c == '\n' || get_err(src)) {
  433. if (!get_err(src)) {
  434. c = get_byte(src);
  435. if (c != '\r' && c != '\n' && !get_err(src))
  436. src->pos--;
  437. }
  438. return strbuf_to_str(buf);
  439. }
  440. put_byte(buf, c);
  441. }
  442. }
  443. static bool read_blob(BinarySource *src, int nlines, BinarySink *bs)
  444. {
  445. unsigned char *blob;
  446. char *line;
  447. int linelen;
  448. int i, j, k;
  449. /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
  450. assert(nlines < MAX_KEY_BLOB_LINES);
  451. blob = snewn(48 * nlines, unsigned char);
  452. for (i = 0; i < nlines; i++) {
  453. line = read_body(src);
  454. if (!line) {
  455. sfree(blob);
  456. return false;
  457. }
  458. linelen = strlen(line);
  459. if (linelen % 4 != 0 || linelen > 64) {
  460. sfree(blob);
  461. sfree(line);
  462. return false;
  463. }
  464. for (j = 0; j < linelen; j += 4) {
  465. unsigned char decoded[3];
  466. k = base64_decode_atom(line + j, decoded);
  467. if (!k) {
  468. sfree(line);
  469. sfree(blob);
  470. return false;
  471. }
  472. put_data(bs, decoded, k);
  473. }
  474. sfree(line);
  475. }
  476. sfree(blob);
  477. return true;
  478. }
  479. /*
  480. * Magic error return value for when the passphrase is wrong.
  481. */
  482. ssh2_userkey ssh2_wrong_passphrase = { NULL, NULL };
  483. const ssh_keyalg *const all_keyalgs[] = {
  484. &ssh_rsa,
  485. &ssh_rsa_sha256,
  486. &ssh_rsa_sha512,
  487. &ssh_dsa,
  488. &ssh_ecdsa_nistp256,
  489. &ssh_ecdsa_nistp384,
  490. &ssh_ecdsa_nistp521,
  491. &ssh_ecdsa_ed25519,
  492. &ssh_ecdsa_ed448,
  493. &opensshcert_ssh_dsa,
  494. &opensshcert_ssh_rsa,
  495. &opensshcert_ssh_rsa_sha256,
  496. &opensshcert_ssh_rsa_sha512,
  497. &opensshcert_ssh_ecdsa_ed25519,
  498. &opensshcert_ssh_ecdsa_nistp256,
  499. &opensshcert_ssh_ecdsa_nistp384,
  500. &opensshcert_ssh_ecdsa_nistp521,
  501. };
  502. const size_t n_keyalgs = lenof(all_keyalgs);
  503. const ssh_keyalg *find_pubkey_alg_len(ptrlen name)
  504. {
  505. for (size_t i = 0; i < n_keyalgs; i++)
  506. if (ptrlen_eq_string(name, all_keyalgs[i]->ssh_id))
  507. return all_keyalgs[i];
  508. return NULL;
  509. }
  510. const ssh_keyalg *find_pubkey_alg(const char *name)
  511. {
  512. return find_pubkey_alg_len(ptrlen_from_asciz(name));
  513. }
  514. ptrlen pubkey_blob_to_alg_name(ptrlen blob)
  515. {
  516. BinarySource src[1];
  517. BinarySource_BARE_INIT_PL(src, blob);
  518. return get_string(src);
  519. }
  520. const ssh_keyalg *pubkey_blob_to_alg(ptrlen blob)
  521. {
  522. return find_pubkey_alg_len(pubkey_blob_to_alg_name(blob));
  523. }
  524. struct ppk_cipher {
  525. const char *name;
  526. size_t blocklen, keylen, ivlen;
  527. };
  528. static const struct ppk_cipher ppk_cipher_none = { "none", 1, 0, 0 };
  529. static const struct ppk_cipher ppk_cipher_aes256_cbc = { "aes256-cbc", 16, 32, 16 };
  530. static void ssh2_ppk_derive_keys(
  531. unsigned fmt_version, const struct ppk_cipher *ciphertype,
  532. ptrlen passphrase, strbuf *storage, ptrlen *cipherkey, ptrlen *cipheriv,
  533. ptrlen *mackey, ptrlen passphrase_salt, ppk_save_parameters *params)
  534. {
  535. size_t mac_keylen;
  536. switch (fmt_version) {
  537. case 3: {
  538. if (ciphertype->keylen == 0) {
  539. mac_keylen = 0;
  540. break;
  541. }
  542. ptrlen empty = PTRLEN_LITERAL("");
  543. mac_keylen = 32;
  544. uint32_t taglen = ciphertype->keylen + ciphertype->ivlen + mac_keylen;
  545. if (params->argon2_passes_auto) {
  546. uint32_t passes;
  547. argon2_choose_passes(
  548. params->argon2_flavour, params->argon2_mem,
  549. params->argon2_milliseconds, &passes,
  550. params->argon2_parallelism, taglen,
  551. passphrase, passphrase_salt, empty, empty, storage);
  552. params->argon2_passes_auto = false;
  553. params->argon2_passes = passes;
  554. } else {
  555. argon2(params->argon2_flavour, params->argon2_mem,
  556. params->argon2_passes, params->argon2_parallelism, taglen,
  557. passphrase, passphrase_salt, empty, empty, storage);
  558. }
  559. break;
  560. }
  561. case 2:
  562. case 1: {
  563. /* Counter-mode iteration to generate cipher key data. */
  564. for (unsigned ctr = 0; ctr * 20 < ciphertype->keylen; ctr++) {
  565. ssh_hash *h = ssh_hash_new(&ssh_sha1);
  566. put_uint32(h, ctr);
  567. put_datapl(h, passphrase);
  568. ssh_hash_final(h, strbuf_append(storage, 20));
  569. }
  570. strbuf_shrink_to(storage, ciphertype->keylen);
  571. /* In this version of the format, the CBC IV was always all 0. */
  572. put_padding(storage, ciphertype->ivlen, 0);
  573. /* Completely separate hash for the MAC key. */
  574. ssh_hash *h = ssh_hash_new(&ssh_sha1);
  575. mac_keylen = ssh_hash_alg(h)->hlen;
  576. put_datapl(h, PTRLEN_LITERAL("putty-private-key-file-mac-key"));
  577. put_datapl(h, passphrase);
  578. ssh_hash_final(h, strbuf_append(storage, mac_keylen));
  579. break;
  580. }
  581. default:
  582. unreachable("bad format version in ssh2_ppk_derive_keys");
  583. }
  584. BinarySource src[1];
  585. BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(storage));
  586. *cipherkey = get_data(src, ciphertype->keylen);
  587. *cipheriv = get_data(src, ciphertype->ivlen);
  588. *mackey = get_data(src, mac_keylen);
  589. }
  590. static int userkey_parse_line_counter(const char *text)
  591. {
  592. char *endptr;
  593. unsigned long ul = strtoul(text, &endptr, 10);
  594. if (*text && !*endptr && ul < MAX_KEY_BLOB_LINES)
  595. return ul;
  596. else
  597. return -1;
  598. }
  599. static bool str_to_uint32_t(const char *s, uint32_t *out)
  600. {
  601. char *endptr;
  602. unsigned long converted = strtoul(s, &endptr, 10);
  603. if (*s && !*endptr && converted <= ~(uint32_t)0) {
  604. *out = converted;
  605. return true;
  606. } else {
  607. return false;
  608. }
  609. }
  610. ssh2_userkey *ppk_load_s(BinarySource *src, const char *passphrase,
  611. const char **errorstr)
  612. {
  613. char header[40], *b, *encryption, *comment, *mac;
  614. const ssh_keyalg *alg;
  615. ssh2_userkey *ret;
  616. strbuf *public_blob, *private_blob, *cipher_mac_keys_blob;
  617. strbuf *passphrase_salt = strbuf_new();
  618. ptrlen cipherkey, cipheriv, mackey;
  619. const struct ppk_cipher *ciphertype;
  620. int i;
  621. bool is_mac;
  622. unsigned fmt_version;
  623. const char *error = NULL;
  624. ppk_save_parameters params;
  625. ret = NULL; /* return NULL for most errors */
  626. encryption = comment = mac = NULL;
  627. public_blob = private_blob = cipher_mac_keys_blob = NULL;
  628. /* Read the first header line which contains the key type. */
  629. if (!read_header(src, header)) {
  630. error = "no header line found in key file";
  631. goto error;
  632. }
  633. if (0 == strcmp(header, "PuTTY-User-Key-File-3")) {
  634. fmt_version = 3;
  635. } else if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {
  636. fmt_version = 2;
  637. } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {
  638. /* this is an old key file; warn and then continue */
  639. old_keyfile_warning();
  640. fmt_version = 1;
  641. } else if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) {
  642. /* this is a key file FROM THE FUTURE; refuse it, but with a
  643. * more specific error message than the generic one below */
  644. error = "PuTTY key format too new";
  645. goto error;
  646. } else {
  647. error = "not a PuTTY SSH-2 private key";
  648. goto error;
  649. }
  650. error = "file format error";
  651. if ((b = read_body(src)) == NULL)
  652. goto error;
  653. /* Select key algorithm structure. */
  654. alg = find_pubkey_alg(b);
  655. if (!alg) {
  656. sfree(b);
  657. goto error;
  658. }
  659. sfree(b);
  660. /* Read the Encryption header line. */
  661. if (!read_header(src, header) || 0 != strcmp(header, "Encryption"))
  662. goto error;
  663. if ((encryption = read_body(src)) == NULL)
  664. goto error;
  665. if (!strcmp(encryption, "aes256-cbc")) {
  666. ciphertype = &ppk_cipher_aes256_cbc;
  667. } else if (!strcmp(encryption, "none")) {
  668. ciphertype = &ppk_cipher_none;
  669. } else {
  670. goto error;
  671. }
  672. /* Read the Comment header line. */
  673. if (!read_header(src, header) || 0 != strcmp(header, "Comment"))
  674. goto error;
  675. if ((comment = read_body(src)) == NULL)
  676. goto error;
  677. memset(&params, 0, sizeof(params)); /* in particular, sets
  678. * passes_auto=false */
  679. /* Read the Public-Lines header line and the public blob. */
  680. if (!read_header(src, header) || 0 != strcmp(header, "Public-Lines"))
  681. goto error;
  682. if ((b = read_body(src)) == NULL)
  683. goto error;
  684. i = userkey_parse_line_counter(b);
  685. sfree(b);
  686. if (i < 0)
  687. goto error;
  688. public_blob = strbuf_new();
  689. if (!read_blob(src, i, BinarySink_UPCAST(public_blob)))
  690. goto error;
  691. if (fmt_version >= 3 && ciphertype->keylen != 0) {
  692. /* Read Argon2 key derivation parameters. */
  693. if (!read_header(src, header) || 0 != strcmp(header, "Key-Derivation"))
  694. goto error;
  695. if ((b = read_body(src)) == NULL)
  696. goto error;
  697. if (!strcmp(b, "Argon2d")) {
  698. params.argon2_flavour = Argon2d;
  699. } else if (!strcmp(b, "Argon2i")) {
  700. params.argon2_flavour = Argon2i;
  701. } else if (!strcmp(b, "Argon2id")) {
  702. params.argon2_flavour = Argon2id;
  703. } else {
  704. sfree(b);
  705. goto error;
  706. }
  707. sfree(b);
  708. if (!read_header(src, header) || 0 != strcmp(header, "Argon2-Memory"))
  709. goto error;
  710. if ((b = read_body(src)) == NULL)
  711. goto error;
  712. if (!str_to_uint32_t(b, &params.argon2_mem)) {
  713. sfree(b);
  714. goto error;
  715. }
  716. sfree(b);
  717. if (!read_header(src, header) || 0 != strcmp(header, "Argon2-Passes"))
  718. goto error;
  719. if ((b = read_body(src)) == NULL)
  720. goto error;
  721. if (!str_to_uint32_t(b, &params.argon2_passes)) {
  722. sfree(b);
  723. goto error;
  724. }
  725. sfree(b);
  726. if (!read_header(src, header) ||
  727. 0 != strcmp(header, "Argon2-Parallelism"))
  728. goto error;
  729. if ((b = read_body(src)) == NULL)
  730. goto error;
  731. if (!str_to_uint32_t(b, &params.argon2_parallelism)) {
  732. sfree(b);
  733. goto error;
  734. }
  735. sfree(b);
  736. if (!read_header(src, header) || 0 != strcmp(header, "Argon2-Salt"))
  737. goto error;
  738. if ((b = read_body(src)) == NULL)
  739. goto error;
  740. for (size_t i = 0; b[i]; i += 2) {
  741. if (isxdigit((unsigned char)b[i]) && b[i+1] &&
  742. isxdigit((unsigned char)b[i+1])) {
  743. char s[3];
  744. s[0] = b[i];
  745. s[1] = b[i+1];
  746. s[2] = '\0';
  747. put_byte(passphrase_salt, strtoul(s, NULL, 16));
  748. } else {
  749. sfree(b);
  750. goto error;
  751. }
  752. }
  753. sfree(b);
  754. }
  755. /* Read the Private-Lines header line and the Private blob. */
  756. if (!read_header(src, header) || 0 != strcmp(header, "Private-Lines"))
  757. goto error;
  758. if ((b = read_body(src)) == NULL)
  759. goto error;
  760. i = userkey_parse_line_counter(b);
  761. sfree(b);
  762. if (i < 0)
  763. goto error;
  764. private_blob = strbuf_new_nm();
  765. if (!read_blob(src, i, BinarySink_UPCAST(private_blob)))
  766. goto error;
  767. /* Read the Private-MAC or Private-Hash header line. */
  768. if (!read_header(src, header))
  769. goto error;
  770. if (0 == strcmp(header, "Private-MAC")) {
  771. if ((mac = read_body(src)) == NULL)
  772. goto error;
  773. is_mac = true;
  774. } else if (0 == strcmp(header, "Private-Hash") && fmt_version == 1) {
  775. if ((mac = read_body(src)) == NULL)
  776. goto error;
  777. is_mac = false;
  778. } else
  779. goto error;
  780. cipher_mac_keys_blob = strbuf_new();
  781. ssh2_ppk_derive_keys(fmt_version, ciphertype,
  782. ptrlen_from_asciz(passphrase ? passphrase : ""),
  783. cipher_mac_keys_blob, &cipherkey, &cipheriv, &mackey,
  784. ptrlen_from_strbuf(passphrase_salt), &params);
  785. /*
  786. * Decrypt the private blob.
  787. */
  788. if (private_blob->len % ciphertype->blocklen)
  789. goto error;
  790. if (ciphertype == &ppk_cipher_aes256_cbc) {
  791. aes256_decrypt_pubkey(cipherkey.ptr, cipheriv.ptr,
  792. private_blob->u, private_blob->len);
  793. }
  794. /*
  795. * Verify the MAC.
  796. */
  797. {
  798. unsigned char binary[32];
  799. char realmac[sizeof(binary) * 2 + 1];
  800. strbuf *macdata;
  801. bool free_macdata;
  802. const ssh2_macalg *mac_alg =
  803. fmt_version <= 2 ? &ssh_hmac_sha1 : &ssh_hmac_sha256;
  804. if (fmt_version == 1) {
  805. /* MAC (or hash) only covers the private blob. */
  806. macdata = private_blob;
  807. free_macdata = false;
  808. } else {
  809. macdata = strbuf_new_nm();
  810. put_stringz(macdata, alg->ssh_id);
  811. put_stringz(macdata, encryption);
  812. put_stringz(macdata, comment);
  813. put_string(macdata, public_blob->s,
  814. public_blob->len);
  815. put_string(macdata, private_blob->s,
  816. private_blob->len);
  817. free_macdata = true;
  818. }
  819. if (is_mac) {
  820. ssh2_mac *mac;
  821. mac = ssh2_mac_new(mac_alg, NULL);
  822. ssh2_mac_setkey(mac, mackey);
  823. ssh2_mac_start(mac);
  824. put_data(mac, macdata->s, macdata->len);
  825. ssh2_mac_genresult(mac, binary);
  826. ssh2_mac_free(mac);
  827. } else {
  828. hash_simple(&ssh_sha1, ptrlen_from_strbuf(macdata), binary);
  829. }
  830. if (free_macdata)
  831. strbuf_free(macdata);
  832. for (i = 0; i < mac_alg->len; i++)
  833. sprintf(realmac + 2 * i, "%02x", binary[i]);
  834. if (strcmp(mac, realmac)) {
  835. /* An incorrect MAC is an unconditional Error if the key is
  836. * unencrypted. Otherwise, it means Wrong Passphrase. */
  837. if (ciphertype->keylen != 0) {
  838. error = "wrong passphrase";
  839. ret = SSH2_WRONG_PASSPHRASE;
  840. } else {
  841. error = "MAC failed";
  842. ret = NULL;
  843. }
  844. goto error;
  845. }
  846. }
  847. /*
  848. * Create and return the key.
  849. */
  850. ret = snew(ssh2_userkey);
  851. ret->comment = comment;
  852. comment = NULL;
  853. ret->key = ssh_key_new_priv(
  854. alg, ptrlen_from_strbuf(public_blob),
  855. ptrlen_from_strbuf(private_blob));
  856. if (!ret->key) {
  857. sfree(ret);
  858. ret = NULL;
  859. error = "createkey failed";
  860. goto error;
  861. }
  862. error = NULL;
  863. /*
  864. * Error processing.
  865. */
  866. error:
  867. if (comment)
  868. sfree(comment);
  869. if (encryption)
  870. sfree(encryption);
  871. if (mac)
  872. sfree(mac);
  873. if (public_blob)
  874. strbuf_free(public_blob);
  875. if (private_blob)
  876. strbuf_free(private_blob);
  877. if (cipher_mac_keys_blob)
  878. strbuf_free(cipher_mac_keys_blob);
  879. strbuf_free(passphrase_salt);
  880. if (errorstr)
  881. *errorstr = error;
  882. return ret;
  883. }
  884. ssh2_userkey *ppk_load_f(const Filename *filename, const char *passphrase,
  885. const char **errorstr)
  886. {
  887. LoadedFile *lf = lf_load_keyfile(filename, errorstr);
  888. ssh2_userkey *toret;
  889. if (lf) {
  890. toret = ppk_load_s(BinarySource_UPCAST(lf), passphrase, errorstr);
  891. lf_free(lf);
  892. } else {
  893. toret = NULL;
  894. *errorstr = "can't open file";
  895. }
  896. return toret;
  897. }
  898. static bool rfc4716_loadpub(BinarySource *src, char **algorithm,
  899. BinarySink *bs,
  900. char **commentptr, const char **errorstr)
  901. {
  902. const char *error;
  903. char *line, *colon, *value;
  904. char *comment = NULL;
  905. strbuf *pubblob = NULL;
  906. char base64in[4];
  907. unsigned char base64out[3];
  908. int base64bytes;
  909. int alglen;
  910. line = mkstr(get_chomped_line(src));
  911. if (!line || 0 != strcmp(line, "---- BEGIN SSH2 PUBLIC KEY ----")) {
  912. error = "invalid begin line in SSH-2 public key file";
  913. goto error;
  914. }
  915. sfree(line); line = NULL;
  916. while (1) {
  917. line = mkstr(get_chomped_line(src));
  918. if (!line) {
  919. error = "truncated SSH-2 public key file";
  920. goto error;
  921. }
  922. colon = strstr(line, ": ");
  923. if (!colon)
  924. break;
  925. *colon = '\0';
  926. value = colon + 2;
  927. if (!strcmp(line, "Comment")) {
  928. char *p, *q;
  929. /* Remove containing double quotes, if present */
  930. p = value;
  931. if (*p == '"' && p[strlen(p)-1] == '"') {
  932. p[strlen(p)-1] = '\0';
  933. p++;
  934. }
  935. /* Remove \-escaping, not in RFC4716 but seen in the wild
  936. * in practice. */
  937. for (q = line; *p; p++) {
  938. if (*p == '\\' && p[1])
  939. p++;
  940. *q++ = *p;
  941. }
  942. *q = '\0';
  943. sfree(comment); /* *just* in case of multiple Comment headers */
  944. comment = dupstr(line);
  945. } else if (!strcmp(line, "Subject") ||
  946. !strncmp(line, "x-", 2)) {
  947. /* Headers we recognise and ignore. Do nothing. */
  948. } else {
  949. error = "unrecognised header in SSH-2 public key file";
  950. goto error;
  951. }
  952. sfree(line); line = NULL;
  953. }
  954. /*
  955. * Now line contains the initial line of base64 data. Loop round
  956. * while it still does contain base64.
  957. */
  958. pubblob = strbuf_new();
  959. base64bytes = 0;
  960. while (line && line[0] != '-') {
  961. char *p;
  962. for (p = line; *p; p++) {
  963. base64in[base64bytes++] = *p;
  964. if (base64bytes == 4) {
  965. int n = base64_decode_atom(base64in, base64out);
  966. put_data(pubblob, base64out, n);
  967. base64bytes = 0;
  968. }
  969. }
  970. sfree(line); line = NULL;
  971. line = mkstr(get_chomped_line(src));
  972. }
  973. /*
  974. * Finally, check the END line makes sense.
  975. */
  976. if (!line || 0 != strcmp(line, "---- END SSH2 PUBLIC KEY ----")) {
  977. error = "invalid end line in SSH-2 public key file";
  978. goto error;
  979. }
  980. sfree(line); line = NULL;
  981. /*
  982. * OK, we now have a public blob and optionally a comment. We must
  983. * return the key algorithm string too, so look for that at the
  984. * start of the public blob.
  985. */
  986. if (pubblob->len < 4) {
  987. error = "not enough data in SSH-2 public key file";
  988. goto error;
  989. }
  990. alglen = toint(GET_32BIT_MSB_FIRST(pubblob->u));
  991. if (alglen < 0 || alglen > pubblob->len-4) {
  992. error = "invalid algorithm prefix in SSH-2 public key file";
  993. goto error;
  994. }
  995. if (algorithm)
  996. *algorithm = dupprintf("%.*s", alglen, pubblob->s+4);
  997. if (commentptr)
  998. *commentptr = comment;
  999. else
  1000. sfree(comment);
  1001. put_datapl(bs, ptrlen_from_strbuf(pubblob));
  1002. strbuf_free(pubblob);
  1003. return true;
  1004. error:
  1005. sfree(line);
  1006. sfree(comment);
  1007. if (pubblob)
  1008. strbuf_free(pubblob);
  1009. if (errorstr)
  1010. *errorstr = error;
  1011. return false;
  1012. }
  1013. static bool openssh_loadpub(BinarySource *src, char **algorithm,
  1014. BinarySink *bs,
  1015. char **commentptr, const char **errorstr)
  1016. {
  1017. const char *error;
  1018. char *line, *base64;
  1019. char *comment = NULL;
  1020. unsigned char *pubblob = NULL;
  1021. int pubbloblen, pubblobsize;
  1022. int alglen;
  1023. line = mkstr(get_chomped_line(src));
  1024. base64 = strchr(line, ' ');
  1025. if (!base64) {
  1026. error = "no key blob in OpenSSH public key file";
  1027. goto error;
  1028. }
  1029. *base64++ = '\0';
  1030. comment = strchr(base64, ' ');
  1031. if (comment) {
  1032. *comment++ = '\0';
  1033. comment = dupstr(comment);
  1034. }
  1035. pubblobsize = strlen(base64) / 4 * 3;
  1036. pubblob = snewn(pubblobsize, unsigned char);
  1037. pubbloblen = 0;
  1038. while (!memchr(base64, '\0', 4)) {
  1039. assert(pubbloblen + 3 <= pubblobsize);
  1040. pubbloblen += base64_decode_atom(base64, pubblob + pubbloblen);
  1041. base64 += 4;
  1042. }
  1043. if (*base64) {
  1044. error = "invalid length for base64 data in OpenSSH public key file";
  1045. goto error;
  1046. }
  1047. /*
  1048. * Sanity check: the first word on the line should be the key
  1049. * algorithm, and should match the encoded string at the start of
  1050. * the public blob.
  1051. */
  1052. alglen = strlen(line);
  1053. if (pubbloblen < alglen + 4 ||
  1054. GET_32BIT_MSB_FIRST(pubblob) != alglen ||
  1055. 0 != memcmp(pubblob + 4, line, alglen)) {
  1056. error = "key algorithms do not match in OpenSSH public key file";
  1057. goto error;
  1058. }
  1059. /*
  1060. * Done.
  1061. */
  1062. if (algorithm)
  1063. *algorithm = dupstr(line);
  1064. if (commentptr)
  1065. *commentptr = comment;
  1066. else
  1067. sfree(comment);
  1068. sfree(line);
  1069. put_data(bs, pubblob, pubbloblen);
  1070. sfree(pubblob);
  1071. return true;
  1072. error:
  1073. sfree(line);
  1074. sfree(comment);
  1075. sfree(pubblob);
  1076. if (errorstr)
  1077. *errorstr = error;
  1078. return false;
  1079. }
  1080. bool ppk_loadpub_s(BinarySource *src, char **algorithm, BinarySink *bs,
  1081. char **commentptr, const char **errorstr)
  1082. {
  1083. char header[40], *b;
  1084. const ssh_keyalg *alg;
  1085. int type, i;
  1086. const char *error = NULL;
  1087. char *comment = NULL;
  1088. /* Initially, check if this is a public-only key file. Sometimes
  1089. * we'll be asked to read a public blob from one of those. */
  1090. type = key_type_s(src);
  1091. if (type == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {
  1092. bool ret = rfc4716_loadpub(src, algorithm, bs, commentptr, errorstr);
  1093. return ret;
  1094. } else if (type == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  1095. bool ret = openssh_loadpub(src, algorithm, bs, commentptr, errorstr);
  1096. return ret;
  1097. } else if (type != SSH_KEYTYPE_SSH2) {
  1098. error = "not a public key or a PuTTY SSH-2 private key";
  1099. goto error;
  1100. }
  1101. /* Read the first header line which contains the key type. */
  1102. if (!read_header(src, header)
  1103. || (0 != strcmp(header, "PuTTY-User-Key-File-3") &&
  1104. 0 != strcmp(header, "PuTTY-User-Key-File-2") &&
  1105. 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
  1106. if (0 == strncmp(header, "PuTTY-User-Key-File-", 20))
  1107. error = "PuTTY key format too new";
  1108. else
  1109. error = "not a public key or a PuTTY SSH-2 private key";
  1110. goto error;
  1111. }
  1112. error = "file format error";
  1113. if ((b = read_body(src)) == NULL)
  1114. goto error;
  1115. /* Select key algorithm structure. */
  1116. alg = find_pubkey_alg(b);
  1117. sfree(b);
  1118. if (!alg) {
  1119. goto error;
  1120. }
  1121. /* Read the Encryption header line. */
  1122. if (!read_header(src, header) || 0 != strcmp(header, "Encryption"))
  1123. goto error;
  1124. if ((b = read_body(src)) == NULL)
  1125. goto error;
  1126. sfree(b); /* we don't care */
  1127. /* Read the Comment header line. */
  1128. if (!read_header(src, header) || 0 != strcmp(header, "Comment"))
  1129. goto error;
  1130. if ((comment = read_body(src)) == NULL)
  1131. goto error;
  1132. if (commentptr)
  1133. *commentptr = comment;
  1134. else
  1135. sfree(comment);
  1136. /* Read the Public-Lines header line and the public blob. */
  1137. if (!read_header(src, header) || 0 != strcmp(header, "Public-Lines"))
  1138. goto error;
  1139. if ((b = read_body(src)) == NULL)
  1140. goto error;
  1141. i = userkey_parse_line_counter(b);
  1142. sfree(b);
  1143. if (i < 0)
  1144. goto error;
  1145. if (!read_blob(src, i, bs))
  1146. goto error;
  1147. if (algorithm)
  1148. *algorithm = dupstr(alg->ssh_id);
  1149. return true;
  1150. /*
  1151. * Error processing.
  1152. */
  1153. error:
  1154. if (errorstr)
  1155. *errorstr = error;
  1156. if (comment && commentptr) {
  1157. sfree(comment);
  1158. *commentptr = NULL;
  1159. }
  1160. return false;
  1161. }
  1162. bool ppk_loadpub_f(const Filename *filename, char **algorithm, BinarySink *bs,
  1163. char **commentptr, const char **errorstr)
  1164. {
  1165. LoadedFile *lf = lf_load_keyfile(filename, errorstr);
  1166. if (!lf)
  1167. return false;
  1168. bool toret = ppk_loadpub_s(BinarySource_UPCAST(lf), algorithm, bs,
  1169. commentptr, errorstr);
  1170. lf_free(lf);
  1171. return toret;
  1172. }
  1173. bool ppk_encrypted_s(BinarySource *src, char **commentptr)
  1174. {
  1175. char header[40], *b, *comment;
  1176. bool ret;
  1177. if (commentptr)
  1178. *commentptr = NULL;
  1179. if (!read_header(src, header)
  1180. || (0 != strcmp(header, "PuTTY-User-Key-File-3") &&
  1181. 0 != strcmp(header, "PuTTY-User-Key-File-2") &&
  1182. 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
  1183. return false;
  1184. }
  1185. if ((b = read_body(src)) == NULL) {
  1186. return false;
  1187. }
  1188. sfree(b); /* we don't care about key type here */
  1189. /* Read the Encryption header line. */
  1190. if (!read_header(src, header) || 0 != strcmp(header, "Encryption")) {
  1191. return false;
  1192. }
  1193. if ((b = read_body(src)) == NULL) {
  1194. return false;
  1195. }
  1196. /* Read the Comment header line. */
  1197. if (!read_header(src, header) || 0 != strcmp(header, "Comment")) {
  1198. sfree(b);
  1199. return true;
  1200. }
  1201. if ((comment = read_body(src)) == NULL) {
  1202. sfree(b);
  1203. return true;
  1204. }
  1205. if (commentptr)
  1206. *commentptr = comment;
  1207. else
  1208. sfree(comment);
  1209. if (!strcmp(b, "aes256-cbc"))
  1210. ret = true;
  1211. else
  1212. ret = false;
  1213. sfree(b);
  1214. return ret;
  1215. }
  1216. bool ppk_encrypted_f(const Filename *filename, char **commentptr)
  1217. {
  1218. LoadedFile *lf = lf_load_keyfile(filename, NULL);
  1219. if (!lf) {
  1220. if (commentptr)
  1221. *commentptr = NULL;
  1222. return false;
  1223. }
  1224. bool toret = ppk_encrypted_s(BinarySource_UPCAST(lf), commentptr);
  1225. lf_free(lf);
  1226. return toret;
  1227. }
  1228. int base64_lines(int datalen)
  1229. {
  1230. /* When encoding, we use 64 chars/line, which equals 48 real chars. */
  1231. return (datalen + 47) / 48;
  1232. }
  1233. const ppk_save_parameters ppk_save_default_parameters = {
  1234. .fmt_version = 3,
  1235. /*
  1236. * The Argon2 spec recommends the hybrid variant Argon2id, where
  1237. * you don't have a good reason to go with the pure Argon2d or
  1238. * Argon2i.
  1239. */
  1240. .argon2_flavour = Argon2id,
  1241. /*
  1242. * Memory requirement for hashing a password: I don't want to set
  1243. * this to some truly huge thing like a gigabyte, because for all
  1244. * I know people might perfectly reasonably be running PuTTY on
  1245. * machines that don't _have_ a gigabyte spare to hash a private
  1246. * key passphrase in the legitimate use cases.
  1247. *
  1248. * I've picked 8 MB as an amount of memory that isn't unreasonable
  1249. * to expect a desktop client machine to have, but is also large
  1250. * compared to the memory requirements of the PPK v2 password hash
  1251. * (which was plain SHA-1), so it still imposes a limit on
  1252. * parallel attacks on someone's key file.
  1253. */
  1254. .argon2_mem = 8192, /* require 8 Mb memory */
  1255. /*
  1256. * Automatically scale the number of Argon2 passes so that the
  1257. * overall time taken is about 1/10 second. (Again, I could crank
  1258. * this up to a larger time and _most_ people might be OK with it,
  1259. * but for the moment, I'm trying to err on the side of not
  1260. * stopping anyone from using the tools at all.)
  1261. */
  1262. .argon2_passes_auto = true,
  1263. .argon2_milliseconds = 100,
  1264. /*
  1265. * PuTTY's own Argon2 implementation is single-threaded. So we
  1266. * might as well set parallelism to 1, which requires that
  1267. * attackers' implementations must also be effectively
  1268. * single-threaded, and they don't get any benefit from using
  1269. * multiple cores on the same hash attempt. (Of course they can
  1270. * still use multiple cores for _separate_ hash attempts, but at
  1271. * least they don't get a speed advantage over us in computing
  1272. * even one hash.)
  1273. */
  1274. .argon2_parallelism = 1,
  1275. };
  1276. strbuf *ppk_save_sb(ssh2_userkey *key, const char *passphrase,
  1277. const ppk_save_parameters *params_orig)
  1278. {
  1279. strbuf *pub_blob, *priv_blob, *cipher_mac_keys_blob;
  1280. unsigned char *priv_blob_encrypted;
  1281. int priv_encrypted_len;
  1282. int cipherblk;
  1283. int i;
  1284. const char *cipherstr;
  1285. ptrlen cipherkey, cipheriv, mackey;
  1286. const struct ppk_cipher *ciphertype;
  1287. unsigned char priv_mac[32];
  1288. /*
  1289. * Fetch the key component blobs.
  1290. */
  1291. pub_blob = strbuf_new();
  1292. ssh_key_public_blob(key->key, BinarySink_UPCAST(pub_blob));
  1293. priv_blob = strbuf_new_nm();
  1294. ssh_key_private_blob(key->key, BinarySink_UPCAST(priv_blob));
  1295. /*
  1296. * Determine encryption details, and encrypt the private blob.
  1297. */
  1298. if (passphrase) {
  1299. cipherstr = "aes256-cbc";
  1300. cipherblk = 16;
  1301. ciphertype = &ppk_cipher_aes256_cbc;
  1302. } else {
  1303. cipherstr = "none";
  1304. cipherblk = 1;
  1305. ciphertype = &ppk_cipher_none;
  1306. }
  1307. priv_encrypted_len = priv_blob->len + cipherblk - 1;
  1308. priv_encrypted_len -= priv_encrypted_len % cipherblk;
  1309. priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);
  1310. memset(priv_blob_encrypted, 0, priv_encrypted_len);
  1311. memcpy(priv_blob_encrypted, priv_blob->u, priv_blob->len);
  1312. /* Create padding based on the SHA hash of the unpadded blob. This prevents
  1313. * too easy a known-plaintext attack on the last block. */
  1314. hash_simple(&ssh_sha1, ptrlen_from_strbuf(priv_blob), priv_mac);
  1315. assert(priv_encrypted_len - priv_blob->len < 20);
  1316. memcpy(priv_blob_encrypted + priv_blob->len, priv_mac,
  1317. priv_encrypted_len - priv_blob->len);
  1318. /* Copy the save parameters, so that when derive_keys chooses the
  1319. * number of Argon2 passes, it can write the result back to our
  1320. * copy for us to retrieve. */
  1321. ppk_save_parameters params = *params_orig;
  1322. strbuf *passphrase_salt = strbuf_new();
  1323. if (params.fmt_version == 3) {
  1324. /* Invent a salt for the password hash. */
  1325. if (params.salt)
  1326. put_data(passphrase_salt, params.salt, params.saltlen);
  1327. else
  1328. random_read(strbuf_append(passphrase_salt, 16), 16);
  1329. }
  1330. cipher_mac_keys_blob = strbuf_new();
  1331. ssh2_ppk_derive_keys(params.fmt_version, ciphertype,
  1332. ptrlen_from_asciz(passphrase ? passphrase : ""),
  1333. cipher_mac_keys_blob, &cipherkey, &cipheriv, &mackey,
  1334. ptrlen_from_strbuf(passphrase_salt), &params);
  1335. const ssh2_macalg *macalg = (params.fmt_version == 2 ?
  1336. &ssh_hmac_sha1 : &ssh_hmac_sha256);
  1337. /* Now create the MAC. */
  1338. {
  1339. strbuf *macdata;
  1340. macdata = strbuf_new_nm();
  1341. put_stringz(macdata, ssh_key_ssh_id(key->key));
  1342. put_stringz(macdata, cipherstr);
  1343. put_stringz(macdata, key->comment);
  1344. put_string(macdata, pub_blob->s, pub_blob->len);
  1345. put_string(macdata, priv_blob_encrypted, priv_encrypted_len);
  1346. mac_simple(macalg, mackey, ptrlen_from_strbuf(macdata), priv_mac);
  1347. strbuf_free(macdata);
  1348. }
  1349. if (passphrase) {
  1350. assert(cipherkey.len == 32);
  1351. aes256_encrypt_pubkey(cipherkey.ptr, cipheriv.ptr,
  1352. priv_blob_encrypted, priv_encrypted_len);
  1353. }
  1354. strbuf *out = strbuf_new_nm();
  1355. put_fmt(out, "PuTTY-User-Key-File-%u: %s\n",
  1356. params.fmt_version, ssh_key_ssh_id(key->key));
  1357. put_fmt(out, "Encryption: %s\n", cipherstr);
  1358. put_fmt(out, "Comment: %s\n", key->comment);
  1359. put_fmt(out, "Public-Lines: %d\n", base64_lines(pub_blob->len));
  1360. base64_encode_bs(BinarySink_UPCAST(out), ptrlen_from_strbuf(pub_blob), 64);
  1361. if (params.fmt_version == 3 && ciphertype->keylen != 0) {
  1362. put_fmt(out, "Key-Derivation: %s\n",
  1363. params.argon2_flavour == Argon2d ? "Argon2d" :
  1364. params.argon2_flavour == Argon2i ? "Argon2i" : "Argon2id");
  1365. put_fmt(out, "Argon2-Memory: %"PRIu32"\n", params.argon2_mem);
  1366. assert(!params.argon2_passes_auto);
  1367. put_fmt(out, "Argon2-Passes: %"PRIu32"\n", params.argon2_passes);
  1368. put_fmt(out, "Argon2-Parallelism: %"PRIu32"\n",
  1369. params.argon2_parallelism);
  1370. put_fmt(out, "Argon2-Salt: ");
  1371. for (size_t i = 0; i < passphrase_salt->len; i++)
  1372. put_fmt(out, "%02x", passphrase_salt->u[i]);
  1373. put_fmt(out, "\n");
  1374. }
  1375. put_fmt(out, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
  1376. base64_encode_bs(BinarySink_UPCAST(out),
  1377. make_ptrlen(priv_blob_encrypted, priv_encrypted_len), 64);
  1378. put_fmt(out, "Private-MAC: ");
  1379. for (i = 0; i < macalg->len; i++)
  1380. put_fmt(out, "%02x", priv_mac[i]);
  1381. put_fmt(out, "\n");
  1382. strbuf_free(cipher_mac_keys_blob);
  1383. strbuf_free(passphrase_salt);
  1384. strbuf_free(pub_blob);
  1385. strbuf_free(priv_blob);
  1386. smemclr(priv_blob_encrypted, priv_encrypted_len);
  1387. sfree(priv_blob_encrypted);
  1388. return out;
  1389. }
  1390. bool ppk_save_f(const Filename *filename, ssh2_userkey *key,
  1391. const char *passphrase, const ppk_save_parameters *params)
  1392. {
  1393. FILE *fp = f_open(filename, "wb", true);
  1394. if (!fp)
  1395. return false;
  1396. strbuf *buf = ppk_save_sb(key, passphrase, params);
  1397. bool toret = fwrite(buf->s, 1, buf->len, fp) == buf->len;
  1398. if (fclose(fp))
  1399. toret = false;
  1400. strbuf_free(buf);
  1401. return toret;
  1402. }
  1403. /* ----------------------------------------------------------------------
  1404. * Output public keys.
  1405. */
  1406. char *ssh1_pubkey_str(RSAKey *key)
  1407. {
  1408. char *buffer;
  1409. char *dec1, *dec2;
  1410. dec1 = mp_get_decimal(key->exponent);
  1411. dec2 = mp_get_decimal(key->modulus);
  1412. buffer = dupprintf("%"SIZEu" %s %s%s%s", mp_get_nbits(key->modulus),
  1413. dec1, dec2, key->comment ? " " : "",
  1414. key->comment ? key->comment : "");
  1415. sfree(dec1);
  1416. sfree(dec2);
  1417. return buffer;
  1418. }
  1419. void ssh1_write_pubkey(FILE *fp, RSAKey *key)
  1420. {
  1421. char *buffer = ssh1_pubkey_str(key);
  1422. fprintf(fp, "%s\n", buffer);
  1423. sfree(buffer);
  1424. }
  1425. static char *ssh2_pubkey_openssh_str_internal(const char *comment,
  1426. const void *v_pub_blob,
  1427. int pub_len)
  1428. {
  1429. const unsigned char *ssh2blob = (const unsigned char *)v_pub_blob;
  1430. ptrlen alg;
  1431. char *buffer, *p;
  1432. int i;
  1433. {
  1434. BinarySource src[1];
  1435. BinarySource_BARE_INIT(src, ssh2blob, pub_len);
  1436. alg = get_string(src);
  1437. if (get_err(src)) {
  1438. const char *replacement_str = "INVALID-ALGORITHM";
  1439. alg.ptr = replacement_str;
  1440. alg.len = strlen(replacement_str);
  1441. }
  1442. }
  1443. buffer = snewn(alg.len +
  1444. 4 * ((pub_len+2) / 3) +
  1445. (comment ? strlen(comment) : 0) + 3, char);
  1446. p = buffer + sprintf(buffer, "%.*s ", PTRLEN_PRINTF(alg));
  1447. i = 0;
  1448. while (i < pub_len) {
  1449. int n = (pub_len - i < 3 ? pub_len - i : 3);
  1450. base64_encode_atom(ssh2blob + i, n, p);
  1451. i += n;
  1452. p += 4;
  1453. }
  1454. if (comment) {
  1455. *p++ = ' ';
  1456. strcpy(p, comment);
  1457. } else
  1458. *p++ = '\0';
  1459. return buffer;
  1460. }
  1461. char *ssh2_pubkey_openssh_str(ssh2_userkey *key)
  1462. {
  1463. strbuf *blob;
  1464. char *ret;
  1465. blob = strbuf_new();
  1466. ssh_key_public_blob(key->key, BinarySink_UPCAST(blob));
  1467. ret = ssh2_pubkey_openssh_str_internal(
  1468. key->comment, blob->s, blob->len);
  1469. strbuf_free(blob);
  1470. return ret;
  1471. }
  1472. void ssh2_write_pubkey(FILE *fp, const char *comment,
  1473. const void *v_pub_blob, int pub_len,
  1474. int keytype)
  1475. {
  1476. unsigned char *pub_blob = (unsigned char *)v_pub_blob;
  1477. if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {
  1478. const char *p;
  1479. int i, column;
  1480. fprintf(fp, "---- BEGIN SSH2 PUBLIC KEY ----\n");
  1481. if (comment) {
  1482. fprintf(fp, "Comment: \"");
  1483. for (p = comment; *p; p++) {
  1484. if (*p == '\\' || *p == '\"')
  1485. fputc('\\', fp);
  1486. fputc(*p, fp);
  1487. }
  1488. fprintf(fp, "\"\n");
  1489. }
  1490. i = 0;
  1491. column = 0;
  1492. while (i < pub_len) {
  1493. char buf[5];
  1494. int n = (pub_len - i < 3 ? pub_len - i : 3);
  1495. base64_encode_atom(pub_blob + i, n, buf);
  1496. i += n;
  1497. buf[4] = '\0';
  1498. fputs(buf, fp);
  1499. if (++column >= 16) {
  1500. fputc('\n', fp);
  1501. column = 0;
  1502. }
  1503. }
  1504. if (column > 0)
  1505. fputc('\n', fp);
  1506. fprintf(fp, "---- END SSH2 PUBLIC KEY ----\n");
  1507. } else if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  1508. char *buffer = ssh2_pubkey_openssh_str_internal(comment,
  1509. v_pub_blob, pub_len);
  1510. fprintf(fp, "%s\n", buffer);
  1511. sfree(buffer);
  1512. } else {
  1513. unreachable("Bad key type in ssh2_write_pubkey");
  1514. }
  1515. }
  1516. /* ----------------------------------------------------------------------
  1517. * Utility functions to compute SSH-2 fingerprints in a uniform way.
  1518. */
  1519. static void ssh2_fingerprint_blob_md5(ptrlen blob, strbuf *sb)
  1520. {
  1521. unsigned char digest[16];
  1522. hash_simple(&ssh_md5, blob, digest);
  1523. for (unsigned i = 0; i < 16; i++)
  1524. put_fmt(sb, "%02x%s", digest[i], i==15 ? "" : ":");
  1525. }
  1526. static void ssh2_fingerprint_blob_sha256(ptrlen blob, strbuf *sb)
  1527. {
  1528. unsigned char digest[32];
  1529. hash_simple(&ssh_sha256, blob, digest);
  1530. put_datapl(sb, PTRLEN_LITERAL("SHA256:"));
  1531. for (unsigned i = 0; i < 32; i += 3) {
  1532. char buf[5];
  1533. unsigned len = 32-i;
  1534. if (len > 3)
  1535. len = 3;
  1536. base64_encode_atom(digest + i, len, buf);
  1537. put_data(sb, buf, 4);
  1538. }
  1539. strbuf_chomp(sb, '=');
  1540. }
  1541. char *ssh2_fingerprint_blob(ptrlen blob, FingerprintType fptype)
  1542. {
  1543. strbuf *sb = strbuf_new();
  1544. strbuf *tmp = NULL;
  1545. /*
  1546. * Identify the key algorithm, if possible.
  1547. *
  1548. * If we can't do that, then we have a seriously confused key
  1549. * blob, in which case we return only the hash.
  1550. */
  1551. BinarySource src[1];
  1552. BinarySource_BARE_INIT_PL(src, blob);
  1553. ptrlen algname = get_string(src);
  1554. if (!get_err(src)) {
  1555. const ssh_keyalg *alg = find_pubkey_alg_len(algname);
  1556. if (alg) {
  1557. int bits = ssh_key_public_bits(alg, blob);
  1558. put_fmt(sb, "%.*s %d ", PTRLEN_PRINTF(algname), bits);
  1559. if (!ssh_fptype_is_cert(fptype) && alg->is_certificate) {
  1560. ssh_key *key = ssh_key_new_pub(alg, blob);
  1561. if (key) {
  1562. tmp = strbuf_new();
  1563. ssh_key_public_blob(ssh_key_base_key(key),
  1564. BinarySink_UPCAST(tmp));
  1565. blob = ptrlen_from_strbuf(tmp);
  1566. ssh_key_free(key);
  1567. }
  1568. }
  1569. } else {
  1570. put_fmt(sb, "%.*s ", PTRLEN_PRINTF(algname));
  1571. }
  1572. }
  1573. switch (ssh_fptype_from_cert(fptype)) {
  1574. case SSH_FPTYPE_MD5:
  1575. ssh2_fingerprint_blob_md5(blob, sb);
  1576. break;
  1577. case SSH_FPTYPE_SHA256:
  1578. ssh2_fingerprint_blob_sha256(blob, sb);
  1579. break;
  1580. default:
  1581. unreachable("ssh_fptype_from_cert ruled out the other values");
  1582. }
  1583. if (tmp)
  1584. strbuf_free(tmp);
  1585. return strbuf_to_str(sb);
  1586. }
  1587. char *ssh2_double_fingerprint_blob(ptrlen blob, FingerprintType fptype)
  1588. {
  1589. if (ssh_fptype_is_cert(fptype))
  1590. fptype = ssh_fptype_from_cert(fptype);
  1591. char *fp = ssh2_fingerprint_blob(blob, fptype);
  1592. char *p = strrchr(fp, ' ');
  1593. char *hash = p ? p + 1 : fp;
  1594. char *fpc = ssh2_fingerprint_blob(blob, ssh_fptype_to_cert(fptype));
  1595. char *pc = strrchr(fpc, ' ');
  1596. char *hashc = pc ? pc + 1 : fpc;
  1597. if (strcmp(hash, hashc)) {
  1598. char *tmp = dupprintf("%s (with certificate: %s)", fp, hashc);
  1599. sfree(fp);
  1600. fp = tmp;
  1601. }
  1602. sfree(fpc);
  1603. return fp;
  1604. }
  1605. char **ssh2_all_fingerprints_for_blob(ptrlen blob)
  1606. {
  1607. char **fps = snewn(SSH_N_FPTYPES, char *);
  1608. for (unsigned i = 0; i < SSH_N_FPTYPES; i++)
  1609. fps[i] = ssh2_fingerprint_blob(blob, i);
  1610. return fps;
  1611. }
  1612. char *ssh2_fingerprint(ssh_key *data, FingerprintType fptype)
  1613. {
  1614. strbuf *blob = strbuf_new();
  1615. ssh_key_public_blob(data, BinarySink_UPCAST(blob));
  1616. char *ret = ssh2_fingerprint_blob(ptrlen_from_strbuf(blob), fptype);
  1617. strbuf_free(blob);
  1618. return ret;
  1619. }
  1620. char *ssh2_double_fingerprint(ssh_key *data, FingerprintType fptype)
  1621. {
  1622. strbuf *blob = strbuf_new();
  1623. ssh_key_public_blob(data, BinarySink_UPCAST(blob));
  1624. char *ret = ssh2_double_fingerprint_blob(ptrlen_from_strbuf(blob), fptype);
  1625. strbuf_free(blob);
  1626. return ret;
  1627. }
  1628. char **ssh2_all_fingerprints(ssh_key *data)
  1629. {
  1630. strbuf *blob = strbuf_new();
  1631. ssh_key_public_blob(data, BinarySink_UPCAST(blob));
  1632. char **ret = ssh2_all_fingerprints_for_blob(ptrlen_from_strbuf(blob));
  1633. strbuf_free(blob);
  1634. return ret;
  1635. }
  1636. void ssh2_free_all_fingerprints(char **fps)
  1637. {
  1638. for (unsigned i = 0; i < SSH_N_FPTYPES; i++)
  1639. sfree(fps[i]);
  1640. sfree(fps);
  1641. }
  1642. /* ----------------------------------------------------------------------
  1643. * Determine the type of a private key file.
  1644. */
  1645. static int key_type_s_internal(BinarySource *src)
  1646. {
  1647. static const ptrlen public_std_sig =
  1648. PTRLEN_DECL_LITERAL("---- BEGIN SSH2 PUBLIC KEY");
  1649. static const ptrlen putty2_sig =
  1650. PTRLEN_DECL_LITERAL("PuTTY-User-Key-File-");
  1651. static const ptrlen sshcom_sig =
  1652. PTRLEN_DECL_LITERAL("---- BEGIN SSH2 ENCRYPTED PRIVAT");
  1653. static const ptrlen openssh_new_sig =
  1654. PTRLEN_DECL_LITERAL("-----BEGIN OPENSSH PRIVATE KEY");
  1655. static const ptrlen openssh_sig =
  1656. PTRLEN_DECL_LITERAL("-----BEGIN ");
  1657. if (BinarySource_REWIND(src), expect_signature(src, rsa1_signature))
  1658. return SSH_KEYTYPE_SSH1;
  1659. if (BinarySource_REWIND(src), expect_signature(src, public_std_sig))
  1660. return SSH_KEYTYPE_SSH2_PUBLIC_RFC4716;
  1661. if (BinarySource_REWIND(src), expect_signature(src, putty2_sig))
  1662. return SSH_KEYTYPE_SSH2;
  1663. if (BinarySource_REWIND(src), expect_signature(src, openssh_new_sig))
  1664. return SSH_KEYTYPE_OPENSSH_NEW;
  1665. if (BinarySource_REWIND(src), expect_signature(src, openssh_sig))
  1666. return SSH_KEYTYPE_OPENSSH_PEM;
  1667. if (BinarySource_REWIND(src), expect_signature(src, sshcom_sig))
  1668. return SSH_KEYTYPE_SSHCOM;
  1669. BinarySource_REWIND(src);
  1670. if (get_chars(src, "0123456789").len > 0 && get_chars(src, " ").len == 1 &&
  1671. get_chars(src, "0123456789").len > 0 && get_chars(src, " ").len == 1 &&
  1672. get_chars(src, "0123456789").len > 0 &&
  1673. get_nonchars(src, " \n").len == 0)
  1674. return SSH_KEYTYPE_SSH1_PUBLIC;
  1675. BinarySource_REWIND(src);
  1676. if (find_pubkey_alg_len(get_nonchars(src, " \n")) > 0 &&
  1677. get_chars(src, " ").len == 1 &&
  1678. get_chars(src, "0123456789ABCDEFGHIJKLMNOPQRSTUV"
  1679. "WXYZabcdefghijklmnopqrstuvwxyz+/=").len > 0 &&
  1680. get_nonchars(src, " \n").len == 0)
  1681. return SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH;
  1682. return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */
  1683. }
  1684. int key_type_s(BinarySource *src)
  1685. {
  1686. int toret = key_type_s_internal(src);
  1687. BinarySource_REWIND(src);
  1688. return toret;
  1689. }
  1690. int key_type(const Filename *filename)
  1691. {
  1692. LoadedFile *lf = lf_new(1024);
  1693. if (lf_load(lf, filename) == LF_ERROR) {
  1694. lf_free(lf);
  1695. return SSH_KEYTYPE_UNOPENABLE;
  1696. }
  1697. int toret = key_type_s(BinarySource_UPCAST(lf));
  1698. lf_free(lf);
  1699. return toret;
  1700. }
  1701. /*
  1702. * Convert the type word to a string, for `wrong type' error
  1703. * messages.
  1704. */
  1705. const char *key_type_to_str(int type)
  1706. {
  1707. switch (type) {
  1708. case SSH_KEYTYPE_UNOPENABLE:
  1709. return "unable to open file";
  1710. case SSH_KEYTYPE_UNKNOWN:
  1711. return "not a recognised key file format";
  1712. case SSH_KEYTYPE_SSH1_PUBLIC:
  1713. return "SSH-1 public key";
  1714. case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716:
  1715. return "SSH-2 public key (RFC 4716 format)";
  1716. case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH:
  1717. return "SSH-2 public key (OpenSSH format)";
  1718. case SSH_KEYTYPE_SSH1:
  1719. return "SSH-1 private key";
  1720. case SSH_KEYTYPE_SSH2:
  1721. return "PuTTY SSH-2 private key";
  1722. case SSH_KEYTYPE_OPENSSH_PEM:
  1723. return "OpenSSH SSH-2 private key (old PEM format)";
  1724. case SSH_KEYTYPE_OPENSSH_NEW:
  1725. return "OpenSSH SSH-2 private key (new format)";
  1726. case SSH_KEYTYPE_SSHCOM:
  1727. return "ssh.com SSH-2 private key";
  1728. /*
  1729. * This function is called with a key type derived from
  1730. * looking at an actual key file, so the output-only type
  1731. * OPENSSH_AUTO should never get here, and is much an INTERNAL
  1732. * ERROR as a code we don't even understand.
  1733. */
  1734. case SSH_KEYTYPE_OPENSSH_AUTO:
  1735. unreachable("OPENSSH_AUTO should never reach key_type_to_str");
  1736. default:
  1737. unreachable("bad key type in key_type_to_str");
  1738. }
  1739. }