sshpubk.c 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968
  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. char *line;
  446. int linelen;
  447. int i, j, k;
  448. /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
  449. for (i = 0; i < nlines; i++) {
  450. line = read_body(src);
  451. if (!line)
  452. return false;
  453. linelen = strlen(line);
  454. if (linelen % 4 != 0 || linelen > 64) {
  455. sfree(line);
  456. return false;
  457. }
  458. for (j = 0; j < linelen; j += 4) {
  459. unsigned char decoded[3];
  460. k = base64_decode_atom(line + j, decoded);
  461. if (!k) {
  462. sfree(line);
  463. return false;
  464. }
  465. put_data(bs, decoded, k);
  466. }
  467. sfree(line);
  468. }
  469. return true;
  470. }
  471. /*
  472. * Magic error return value for when the passphrase is wrong.
  473. */
  474. ssh2_userkey ssh2_wrong_passphrase = { NULL, NULL };
  475. const ssh_keyalg *const all_keyalgs[] = {
  476. &ssh_rsa,
  477. &ssh_rsa_sha256,
  478. &ssh_rsa_sha512,
  479. &ssh_dsa,
  480. &ssh_ecdsa_nistp256,
  481. &ssh_ecdsa_nistp384,
  482. &ssh_ecdsa_nistp521,
  483. &ssh_ecdsa_ed25519,
  484. &ssh_ecdsa_ed448,
  485. &opensshcert_ssh_dsa,
  486. &opensshcert_ssh_rsa,
  487. &opensshcert_ssh_rsa_sha256,
  488. &opensshcert_ssh_rsa_sha512,
  489. &opensshcert_ssh_ecdsa_ed25519,
  490. &opensshcert_ssh_ecdsa_nistp256,
  491. &opensshcert_ssh_ecdsa_nistp384,
  492. &opensshcert_ssh_ecdsa_nistp521,
  493. };
  494. const size_t n_keyalgs = lenof(all_keyalgs);
  495. const ssh_keyalg *find_pubkey_alg_len(ptrlen name)
  496. {
  497. for (size_t i = 0; i < n_keyalgs; i++)
  498. if (ptrlen_eq_string(name, all_keyalgs[i]->ssh_id))
  499. return all_keyalgs[i];
  500. return NULL;
  501. }
  502. const ssh_keyalg *find_pubkey_alg(const char *name)
  503. {
  504. return find_pubkey_alg_len(ptrlen_from_asciz(name));
  505. }
  506. ptrlen pubkey_blob_to_alg_name(ptrlen blob)
  507. {
  508. BinarySource src[1];
  509. BinarySource_BARE_INIT_PL(src, blob);
  510. return get_string(src);
  511. }
  512. const ssh_keyalg *pubkey_blob_to_alg(ptrlen blob)
  513. {
  514. return find_pubkey_alg_len(pubkey_blob_to_alg_name(blob));
  515. }
  516. struct ppk_cipher {
  517. const char *name;
  518. size_t blocklen, keylen, ivlen;
  519. };
  520. static const struct ppk_cipher ppk_cipher_none = { "none", 1, 0, 0 };
  521. static const struct ppk_cipher ppk_cipher_aes256_cbc = { "aes256-cbc", 16, 32, 16 };
  522. static void ssh2_ppk_derive_keys(
  523. unsigned fmt_version, const struct ppk_cipher *ciphertype,
  524. ptrlen passphrase, strbuf *storage, ptrlen *cipherkey, ptrlen *cipheriv,
  525. ptrlen *mackey, ptrlen passphrase_salt, ppk_save_parameters *params)
  526. {
  527. size_t mac_keylen;
  528. switch (fmt_version) {
  529. case 3: {
  530. if (ciphertype->keylen == 0) {
  531. mac_keylen = 0;
  532. break;
  533. }
  534. ptrlen empty = PTRLEN_LITERAL("");
  535. mac_keylen = 32;
  536. uint32_t taglen = ciphertype->keylen + ciphertype->ivlen + mac_keylen;
  537. if (params->argon2_passes_auto) {
  538. uint32_t passes;
  539. argon2_choose_passes(
  540. params->argon2_flavour, params->argon2_mem,
  541. params->argon2_milliseconds, &passes,
  542. params->argon2_parallelism, taglen,
  543. passphrase, passphrase_salt, empty, empty, storage);
  544. params->argon2_passes_auto = false;
  545. params->argon2_passes = passes;
  546. } else {
  547. argon2(params->argon2_flavour, params->argon2_mem,
  548. params->argon2_passes, params->argon2_parallelism, taglen,
  549. passphrase, passphrase_salt, empty, empty, storage);
  550. }
  551. break;
  552. }
  553. case 2:
  554. case 1: {
  555. /* Counter-mode iteration to generate cipher key data. */
  556. for (unsigned ctr = 0; ctr * 20 < ciphertype->keylen; ctr++) {
  557. ssh_hash *h = ssh_hash_new(&ssh_sha1);
  558. put_uint32(h, ctr);
  559. put_datapl(h, passphrase);
  560. ssh_hash_final(h, strbuf_append(storage, 20));
  561. }
  562. strbuf_shrink_to(storage, ciphertype->keylen);
  563. /* In this version of the format, the CBC IV was always all 0. */
  564. put_padding(storage, ciphertype->ivlen, 0);
  565. /* Completely separate hash for the MAC key. */
  566. ssh_hash *h = ssh_hash_new(&ssh_sha1);
  567. mac_keylen = ssh_hash_alg(h)->hlen;
  568. put_datapl(h, PTRLEN_LITERAL("putty-private-key-file-mac-key"));
  569. put_datapl(h, passphrase);
  570. ssh_hash_final(h, strbuf_append(storage, mac_keylen));
  571. break;
  572. }
  573. default:
  574. unreachable("bad format version in ssh2_ppk_derive_keys");
  575. }
  576. BinarySource src[1];
  577. BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(storage));
  578. *cipherkey = get_data(src, ciphertype->keylen);
  579. *cipheriv = get_data(src, ciphertype->ivlen);
  580. *mackey = get_data(src, mac_keylen);
  581. }
  582. static int userkey_parse_line_counter(const char *text)
  583. {
  584. char *endptr;
  585. unsigned long ul = strtoul(text, &endptr, 10);
  586. if (*text && !*endptr && ul < MAX_KEY_BLOB_LINES)
  587. return ul;
  588. else
  589. return -1;
  590. }
  591. static bool str_to_uint32_t(const char *s, uint32_t *out)
  592. {
  593. char *endptr;
  594. unsigned long converted = strtoul(s, &endptr, 10);
  595. if (*s && !*endptr && converted <= ~(uint32_t)0) {
  596. *out = converted;
  597. return true;
  598. } else {
  599. return false;
  600. }
  601. }
  602. ssh2_userkey *ppk_load_s(BinarySource *src, const char *passphrase,
  603. const char **errorstr)
  604. {
  605. char header[40], *b, *encryption, *comment, *mac;
  606. const ssh_keyalg *alg;
  607. ssh2_userkey *ret;
  608. strbuf *public_blob, *private_blob, *cipher_mac_keys_blob;
  609. strbuf *passphrase_salt = strbuf_new();
  610. ptrlen cipherkey, cipheriv, mackey;
  611. const struct ppk_cipher *ciphertype;
  612. int i;
  613. bool is_mac;
  614. unsigned fmt_version;
  615. const char *error = NULL;
  616. ppk_save_parameters params;
  617. ret = NULL; /* return NULL for most errors */
  618. encryption = comment = mac = NULL;
  619. public_blob = private_blob = cipher_mac_keys_blob = NULL;
  620. /* Read the first header line which contains the key type. */
  621. if (!read_header(src, header)) {
  622. error = "no header line found in key file";
  623. goto error;
  624. }
  625. if (0 == strcmp(header, "PuTTY-User-Key-File-3")) {
  626. fmt_version = 3;
  627. } else if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {
  628. fmt_version = 2;
  629. } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {
  630. /* this is an old key file; warn and then continue */
  631. old_keyfile_warning();
  632. fmt_version = 1;
  633. } else if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) {
  634. /* this is a key file FROM THE FUTURE; refuse it, but with a
  635. * more specific error message than the generic one below */
  636. error = "PuTTY key format too new";
  637. goto error;
  638. } else {
  639. error = "not a PuTTY SSH-2 private key";
  640. goto error;
  641. }
  642. error = "file format error";
  643. if ((b = read_body(src)) == NULL)
  644. goto error;
  645. /* Select key algorithm structure. */
  646. alg = find_pubkey_alg(b);
  647. if (!alg) {
  648. sfree(b);
  649. goto error;
  650. }
  651. sfree(b);
  652. /* Read the Encryption header line. */
  653. if (!read_header(src, header) || 0 != strcmp(header, "Encryption"))
  654. goto error;
  655. if ((encryption = read_body(src)) == NULL)
  656. goto error;
  657. if (!strcmp(encryption, "aes256-cbc")) {
  658. ciphertype = &ppk_cipher_aes256_cbc;
  659. } else if (!strcmp(encryption, "none")) {
  660. ciphertype = &ppk_cipher_none;
  661. } else {
  662. goto error;
  663. }
  664. /* Read the Comment header line. */
  665. if (!read_header(src, header) || 0 != strcmp(header, "Comment"))
  666. goto error;
  667. if ((comment = read_body(src)) == NULL)
  668. goto error;
  669. memset(&params, 0, sizeof(params)); /* in particular, sets
  670. * passes_auto=false */
  671. /* Read the Public-Lines header line and the public blob. */
  672. if (!read_header(src, header) || 0 != strcmp(header, "Public-Lines"))
  673. goto error;
  674. if ((b = read_body(src)) == NULL)
  675. goto error;
  676. i = userkey_parse_line_counter(b);
  677. sfree(b);
  678. if (i < 0)
  679. goto error;
  680. public_blob = strbuf_new();
  681. if (!read_blob(src, i, BinarySink_UPCAST(public_blob)))
  682. goto error;
  683. if (fmt_version >= 3 && ciphertype->keylen != 0) {
  684. /* Read Argon2 key derivation parameters. */
  685. if (!read_header(src, header) || 0 != strcmp(header, "Key-Derivation"))
  686. goto error;
  687. if ((b = read_body(src)) == NULL)
  688. goto error;
  689. if (!strcmp(b, "Argon2d")) {
  690. params.argon2_flavour = Argon2d;
  691. } else if (!strcmp(b, "Argon2i")) {
  692. params.argon2_flavour = Argon2i;
  693. } else if (!strcmp(b, "Argon2id")) {
  694. params.argon2_flavour = Argon2id;
  695. } else {
  696. sfree(b);
  697. goto error;
  698. }
  699. sfree(b);
  700. if (!read_header(src, header) || 0 != strcmp(header, "Argon2-Memory"))
  701. goto error;
  702. if ((b = read_body(src)) == NULL)
  703. goto error;
  704. if (!str_to_uint32_t(b, &params.argon2_mem)) {
  705. sfree(b);
  706. goto error;
  707. }
  708. sfree(b);
  709. if (!read_header(src, header) || 0 != strcmp(header, "Argon2-Passes"))
  710. goto error;
  711. if ((b = read_body(src)) == NULL)
  712. goto error;
  713. if (!str_to_uint32_t(b, &params.argon2_passes)) {
  714. sfree(b);
  715. goto error;
  716. }
  717. sfree(b);
  718. if (!read_header(src, header) ||
  719. 0 != strcmp(header, "Argon2-Parallelism"))
  720. goto error;
  721. if ((b = read_body(src)) == NULL)
  722. goto error;
  723. if (!str_to_uint32_t(b, &params.argon2_parallelism)) {
  724. sfree(b);
  725. goto error;
  726. }
  727. sfree(b);
  728. if (!read_header(src, header) || 0 != strcmp(header, "Argon2-Salt"))
  729. goto error;
  730. if ((b = read_body(src)) == NULL)
  731. goto error;
  732. for (size_t i = 0; b[i]; i += 2) {
  733. if (isxdigit((unsigned char)b[i]) && b[i+1] &&
  734. isxdigit((unsigned char)b[i+1])) {
  735. char s[3];
  736. s[0] = b[i];
  737. s[1] = b[i+1];
  738. s[2] = '\0';
  739. put_byte(passphrase_salt, strtoul(s, NULL, 16));
  740. } else {
  741. sfree(b);
  742. goto error;
  743. }
  744. }
  745. sfree(b);
  746. }
  747. /* Read the Private-Lines header line and the Private blob. */
  748. if (!read_header(src, header) || 0 != strcmp(header, "Private-Lines"))
  749. goto error;
  750. if ((b = read_body(src)) == NULL)
  751. goto error;
  752. i = userkey_parse_line_counter(b);
  753. sfree(b);
  754. if (i < 0)
  755. goto error;
  756. private_blob = strbuf_new_nm();
  757. if (!read_blob(src, i, BinarySink_UPCAST(private_blob)))
  758. goto error;
  759. /* Read the Private-MAC or Private-Hash header line. */
  760. if (!read_header(src, header))
  761. goto error;
  762. if (0 == strcmp(header, "Private-MAC")) {
  763. if ((mac = read_body(src)) == NULL)
  764. goto error;
  765. is_mac = true;
  766. } else if (0 == strcmp(header, "Private-Hash") && fmt_version == 1) {
  767. if ((mac = read_body(src)) == NULL)
  768. goto error;
  769. is_mac = false;
  770. } else
  771. goto error;
  772. cipher_mac_keys_blob = strbuf_new();
  773. ssh2_ppk_derive_keys(fmt_version, ciphertype,
  774. ptrlen_from_asciz(passphrase ? passphrase : ""),
  775. cipher_mac_keys_blob, &cipherkey, &cipheriv, &mackey,
  776. ptrlen_from_strbuf(passphrase_salt), &params);
  777. /*
  778. * Decrypt the private blob.
  779. */
  780. if (private_blob->len % ciphertype->blocklen)
  781. goto error;
  782. if (ciphertype == &ppk_cipher_aes256_cbc) {
  783. aes256_decrypt_pubkey(cipherkey.ptr, cipheriv.ptr,
  784. private_blob->u, private_blob->len);
  785. }
  786. /*
  787. * Verify the MAC.
  788. */
  789. {
  790. unsigned char binary[32];
  791. char realmac[sizeof(binary) * 2 + 1];
  792. strbuf *macdata;
  793. bool free_macdata;
  794. const ssh2_macalg *mac_alg =
  795. fmt_version <= 2 ? &ssh_hmac_sha1 : &ssh_hmac_sha256;
  796. if (fmt_version == 1) {
  797. /* MAC (or hash) only covers the private blob. */
  798. macdata = private_blob;
  799. free_macdata = false;
  800. } else {
  801. macdata = strbuf_new_nm();
  802. put_stringz(macdata, alg->ssh_id);
  803. put_stringz(macdata, encryption);
  804. put_stringz(macdata, comment);
  805. put_string(macdata, public_blob->s,
  806. public_blob->len);
  807. put_string(macdata, private_blob->s,
  808. private_blob->len);
  809. free_macdata = true;
  810. }
  811. if (is_mac) {
  812. ssh2_mac *mac;
  813. mac = ssh2_mac_new(mac_alg, NULL);
  814. ssh2_mac_setkey(mac, mackey);
  815. ssh2_mac_start(mac);
  816. put_data(mac, macdata->s, macdata->len);
  817. ssh2_mac_genresult(mac, binary);
  818. ssh2_mac_free(mac);
  819. } else {
  820. hash_simple(&ssh_sha1, ptrlen_from_strbuf(macdata), binary);
  821. }
  822. if (free_macdata)
  823. strbuf_free(macdata);
  824. for (i = 0; i < mac_alg->len; i++)
  825. sprintf(realmac + 2 * i, "%02x", binary[i]);
  826. if (strcmp(mac, realmac)) {
  827. /* An incorrect MAC is an unconditional Error if the key is
  828. * unencrypted. Otherwise, it means Wrong Passphrase. */
  829. if (ciphertype->keylen != 0) {
  830. error = "wrong passphrase";
  831. ret = SSH2_WRONG_PASSPHRASE;
  832. } else {
  833. error = "MAC failed";
  834. ret = NULL;
  835. }
  836. goto error;
  837. }
  838. }
  839. /*
  840. * Create and return the key.
  841. */
  842. ret = snew(ssh2_userkey);
  843. ret->comment = comment;
  844. comment = NULL;
  845. ret->key = ssh_key_new_priv(
  846. alg, ptrlen_from_strbuf(public_blob),
  847. ptrlen_from_strbuf(private_blob));
  848. if (!ret->key) {
  849. sfree(ret);
  850. ret = NULL;
  851. error = "createkey failed";
  852. goto error;
  853. }
  854. error = NULL;
  855. /*
  856. * Error processing.
  857. */
  858. error:
  859. if (comment)
  860. sfree(comment);
  861. if (encryption)
  862. sfree(encryption);
  863. if (mac)
  864. sfree(mac);
  865. if (public_blob)
  866. strbuf_free(public_blob);
  867. if (private_blob)
  868. strbuf_free(private_blob);
  869. if (cipher_mac_keys_blob)
  870. strbuf_free(cipher_mac_keys_blob);
  871. strbuf_free(passphrase_salt);
  872. if (errorstr)
  873. *errorstr = error;
  874. return ret;
  875. }
  876. ssh2_userkey *ppk_load_f(const Filename *filename, const char *passphrase,
  877. const char **errorstr)
  878. {
  879. LoadedFile *lf = lf_load_keyfile(filename, errorstr);
  880. ssh2_userkey *toret;
  881. if (lf) {
  882. toret = ppk_load_s(BinarySource_UPCAST(lf), passphrase, errorstr);
  883. lf_free(lf);
  884. } else {
  885. toret = NULL;
  886. *errorstr = "can't open file";
  887. }
  888. return toret;
  889. }
  890. static bool rfc4716_loadpub(BinarySource *src, char **algorithm,
  891. BinarySink *bs,
  892. char **commentptr, const char **errorstr)
  893. {
  894. const char *error;
  895. char *line, *colon, *value;
  896. char *comment = NULL;
  897. strbuf *pubblob = NULL;
  898. char base64in[4];
  899. unsigned char base64out[3];
  900. int base64bytes;
  901. int alglen;
  902. line = mkstr(get_chomped_line(src));
  903. if (!line || 0 != strcmp(line, "---- BEGIN SSH2 PUBLIC KEY ----")) {
  904. error = "invalid begin line in SSH-2 public key file";
  905. goto error;
  906. }
  907. sfree(line); line = NULL;
  908. while (1) {
  909. line = mkstr(get_chomped_line(src));
  910. if (!line) {
  911. error = "truncated SSH-2 public key file";
  912. goto error;
  913. }
  914. colon = strstr(line, ": ");
  915. if (!colon)
  916. break;
  917. *colon = '\0';
  918. value = colon + 2;
  919. if (!strcmp(line, "Comment")) {
  920. char *p, *q;
  921. /* Remove containing double quotes, if present */
  922. p = value;
  923. if (*p == '"' && p[strlen(p)-1] == '"') {
  924. p[strlen(p)-1] = '\0';
  925. p++;
  926. }
  927. /* Remove \-escaping, not in RFC4716 but seen in the wild
  928. * in practice. */
  929. for (q = line; *p; p++) {
  930. if (*p == '\\' && p[1])
  931. p++;
  932. *q++ = *p;
  933. }
  934. *q = '\0';
  935. sfree(comment); /* *just* in case of multiple Comment headers */
  936. comment = dupstr(line);
  937. } else if (!strcmp(line, "Subject") ||
  938. !strncmp(line, "x-", 2)) {
  939. /* Headers we recognise and ignore. Do nothing. */
  940. } else {
  941. error = "unrecognised header in SSH-2 public key file";
  942. goto error;
  943. }
  944. sfree(line); line = NULL;
  945. }
  946. /*
  947. * Now line contains the initial line of base64 data. Loop round
  948. * while it still does contain base64.
  949. */
  950. pubblob = strbuf_new();
  951. base64bytes = 0;
  952. while (line && line[0] != '-') {
  953. char *p;
  954. for (p = line; *p; p++) {
  955. base64in[base64bytes++] = *p;
  956. if (base64bytes == 4) {
  957. int n = base64_decode_atom(base64in, base64out);
  958. put_data(pubblob, base64out, n);
  959. base64bytes = 0;
  960. }
  961. }
  962. sfree(line); line = NULL;
  963. line = mkstr(get_chomped_line(src));
  964. }
  965. /*
  966. * Finally, check the END line makes sense.
  967. */
  968. if (!line || 0 != strcmp(line, "---- END SSH2 PUBLIC KEY ----")) {
  969. error = "invalid end line in SSH-2 public key file";
  970. goto error;
  971. }
  972. sfree(line); line = NULL;
  973. /*
  974. * OK, we now have a public blob and optionally a comment. We must
  975. * return the key algorithm string too, so look for that at the
  976. * start of the public blob.
  977. */
  978. if (pubblob->len < 4) {
  979. error = "not enough data in SSH-2 public key file";
  980. goto error;
  981. }
  982. alglen = toint(GET_32BIT_MSB_FIRST(pubblob->u));
  983. if (alglen < 0 || alglen > pubblob->len-4) {
  984. error = "invalid algorithm prefix in SSH-2 public key file";
  985. goto error;
  986. }
  987. if (algorithm)
  988. *algorithm = dupprintf("%.*s", alglen, pubblob->s+4);
  989. if (commentptr)
  990. *commentptr = comment;
  991. else
  992. sfree(comment);
  993. put_datapl(bs, ptrlen_from_strbuf(pubblob));
  994. strbuf_free(pubblob);
  995. return true;
  996. error:
  997. sfree(line);
  998. sfree(comment);
  999. if (pubblob)
  1000. strbuf_free(pubblob);
  1001. if (errorstr)
  1002. *errorstr = error;
  1003. return false;
  1004. }
  1005. static bool openssh_loadpub(BinarySource *src, char **algorithm,
  1006. BinarySink *bs,
  1007. char **commentptr, const char **errorstr)
  1008. {
  1009. const char *error;
  1010. char *line, *base64;
  1011. char *comment = NULL;
  1012. unsigned char *pubblob = NULL;
  1013. int pubbloblen, pubblobsize;
  1014. int alglen;
  1015. line = mkstr(get_chomped_line(src));
  1016. base64 = strchr(line, ' ');
  1017. if (!base64) {
  1018. error = "no key blob in OpenSSH public key file";
  1019. goto error;
  1020. }
  1021. *base64++ = '\0';
  1022. comment = strchr(base64, ' ');
  1023. if (comment) {
  1024. *comment++ = '\0';
  1025. comment = dupstr(comment);
  1026. }
  1027. pubblobsize = strlen(base64) / 4 * 3;
  1028. pubblob = snewn(pubblobsize, unsigned char);
  1029. pubbloblen = 0;
  1030. while (!memchr(base64, '\0', 4)) {
  1031. assert(pubbloblen + 3 <= pubblobsize);
  1032. pubbloblen += base64_decode_atom(base64, pubblob + pubbloblen);
  1033. base64 += 4;
  1034. }
  1035. if (*base64) {
  1036. error = "invalid length for base64 data in OpenSSH public key file";
  1037. goto error;
  1038. }
  1039. /*
  1040. * Sanity check: the first word on the line should be the key
  1041. * algorithm, and should match the encoded string at the start of
  1042. * the public blob.
  1043. */
  1044. alglen = strlen(line);
  1045. if (pubbloblen < alglen + 4 ||
  1046. GET_32BIT_MSB_FIRST(pubblob) != alglen ||
  1047. 0 != memcmp(pubblob + 4, line, alglen)) {
  1048. error = "key algorithms do not match in OpenSSH public key file";
  1049. goto error;
  1050. }
  1051. /*
  1052. * Done.
  1053. */
  1054. if (algorithm)
  1055. *algorithm = dupstr(line);
  1056. if (commentptr)
  1057. *commentptr = comment;
  1058. else
  1059. sfree(comment);
  1060. sfree(line);
  1061. put_data(bs, pubblob, pubbloblen);
  1062. sfree(pubblob);
  1063. return true;
  1064. error:
  1065. sfree(line);
  1066. sfree(comment);
  1067. sfree(pubblob);
  1068. if (errorstr)
  1069. *errorstr = error;
  1070. return false;
  1071. }
  1072. bool ppk_loadpub_s(BinarySource *src, char **algorithm, BinarySink *bs,
  1073. char **commentptr, const char **errorstr)
  1074. {
  1075. char header[40], *b;
  1076. const ssh_keyalg *alg;
  1077. int type, i;
  1078. const char *error = NULL;
  1079. char *comment = NULL;
  1080. /* Initially, check if this is a public-only key file. Sometimes
  1081. * we'll be asked to read a public blob from one of those. */
  1082. type = key_type_s(src);
  1083. if (type == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {
  1084. bool ret = rfc4716_loadpub(src, algorithm, bs, commentptr, errorstr);
  1085. return ret;
  1086. } else if (type == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  1087. bool ret = openssh_loadpub(src, algorithm, bs, commentptr, errorstr);
  1088. return ret;
  1089. } else if (type != SSH_KEYTYPE_SSH2) {
  1090. error = "not a public key or a PuTTY SSH-2 private key";
  1091. goto error;
  1092. }
  1093. /* Read the first header line which contains the key type. */
  1094. if (!read_header(src, header)
  1095. || (0 != strcmp(header, "PuTTY-User-Key-File-3") &&
  1096. 0 != strcmp(header, "PuTTY-User-Key-File-2") &&
  1097. 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
  1098. if (0 == strncmp(header, "PuTTY-User-Key-File-", 20))
  1099. error = "PuTTY key format too new";
  1100. else
  1101. error = "not a public key or a PuTTY SSH-2 private key";
  1102. goto error;
  1103. }
  1104. error = "file format error";
  1105. if ((b = read_body(src)) == NULL)
  1106. goto error;
  1107. /* Select key algorithm structure. */
  1108. alg = find_pubkey_alg(b);
  1109. sfree(b);
  1110. if (!alg) {
  1111. goto error;
  1112. }
  1113. /* Read the Encryption header line. */
  1114. if (!read_header(src, header) || 0 != strcmp(header, "Encryption"))
  1115. goto error;
  1116. if ((b = read_body(src)) == NULL)
  1117. goto error;
  1118. sfree(b); /* we don't care */
  1119. /* Read the Comment header line. */
  1120. if (!read_header(src, header) || 0 != strcmp(header, "Comment"))
  1121. goto error;
  1122. if ((comment = read_body(src)) == NULL)
  1123. goto error;
  1124. if (commentptr)
  1125. *commentptr = comment;
  1126. else
  1127. sfree(comment);
  1128. /* Read the Public-Lines header line and the public blob. */
  1129. if (!read_header(src, header) || 0 != strcmp(header, "Public-Lines"))
  1130. goto error;
  1131. if ((b = read_body(src)) == NULL)
  1132. goto error;
  1133. i = userkey_parse_line_counter(b);
  1134. sfree(b);
  1135. if (i < 0)
  1136. goto error;
  1137. if (!read_blob(src, i, bs))
  1138. goto error;
  1139. if (algorithm)
  1140. *algorithm = dupstr(alg->ssh_id);
  1141. return true;
  1142. /*
  1143. * Error processing.
  1144. */
  1145. error:
  1146. if (errorstr)
  1147. *errorstr = error;
  1148. if (comment && commentptr) {
  1149. sfree(comment);
  1150. *commentptr = NULL;
  1151. }
  1152. return false;
  1153. }
  1154. bool ppk_loadpub_f(const Filename *filename, char **algorithm, BinarySink *bs,
  1155. char **commentptr, const char **errorstr)
  1156. {
  1157. LoadedFile *lf = lf_load_keyfile(filename, errorstr);
  1158. if (!lf)
  1159. return false;
  1160. bool toret = ppk_loadpub_s(BinarySource_UPCAST(lf), algorithm, bs,
  1161. commentptr, errorstr);
  1162. lf_free(lf);
  1163. return toret;
  1164. }
  1165. bool ppk_encrypted_s(BinarySource *src, char **commentptr)
  1166. {
  1167. char header[40], *b, *comment;
  1168. bool ret;
  1169. if (commentptr)
  1170. *commentptr = NULL;
  1171. if (!read_header(src, header)
  1172. || (0 != strcmp(header, "PuTTY-User-Key-File-3") &&
  1173. 0 != strcmp(header, "PuTTY-User-Key-File-2") &&
  1174. 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
  1175. return false;
  1176. }
  1177. if ((b = read_body(src)) == NULL) {
  1178. return false;
  1179. }
  1180. sfree(b); /* we don't care about key type here */
  1181. /* Read the Encryption header line. */
  1182. if (!read_header(src, header) || 0 != strcmp(header, "Encryption")) {
  1183. return false;
  1184. }
  1185. if ((b = read_body(src)) == NULL) {
  1186. return false;
  1187. }
  1188. /* Read the Comment header line. */
  1189. if (!read_header(src, header) || 0 != strcmp(header, "Comment")) {
  1190. sfree(b);
  1191. return true;
  1192. }
  1193. if ((comment = read_body(src)) == NULL) {
  1194. sfree(b);
  1195. return true;
  1196. }
  1197. if (commentptr)
  1198. *commentptr = comment;
  1199. else
  1200. sfree(comment);
  1201. if (!strcmp(b, "aes256-cbc"))
  1202. ret = true;
  1203. else
  1204. ret = false;
  1205. sfree(b);
  1206. return ret;
  1207. }
  1208. bool ppk_encrypted_f(const Filename *filename, char **commentptr)
  1209. {
  1210. LoadedFile *lf = lf_load_keyfile(filename, NULL);
  1211. if (!lf) {
  1212. if (commentptr)
  1213. *commentptr = NULL;
  1214. return false;
  1215. }
  1216. bool toret = ppk_encrypted_s(BinarySource_UPCAST(lf), commentptr);
  1217. lf_free(lf);
  1218. return toret;
  1219. }
  1220. int base64_lines(int datalen)
  1221. {
  1222. /* When encoding, we use 64 chars/line, which equals 48 real chars. */
  1223. return (datalen + 47) / 48;
  1224. }
  1225. const ppk_save_parameters ppk_save_default_parameters = {
  1226. .fmt_version = 3,
  1227. /*
  1228. * The Argon2 spec recommends the hybrid variant Argon2id, where
  1229. * you don't have a good reason to go with the pure Argon2d or
  1230. * Argon2i.
  1231. */
  1232. .argon2_flavour = Argon2id,
  1233. /*
  1234. * Memory requirement for hashing a password: I don't want to set
  1235. * this to some truly huge thing like a gigabyte, because for all
  1236. * I know people might perfectly reasonably be running PuTTY on
  1237. * machines that don't _have_ a gigabyte spare to hash a private
  1238. * key passphrase in the legitimate use cases.
  1239. *
  1240. * I've picked 8 MB as an amount of memory that isn't unreasonable
  1241. * to expect a desktop client machine to have, but is also large
  1242. * compared to the memory requirements of the PPK v2 password hash
  1243. * (which was plain SHA-1), so it still imposes a limit on
  1244. * parallel attacks on someone's key file.
  1245. */
  1246. .argon2_mem = 8192, /* require 8 Mb memory */
  1247. /*
  1248. * Automatically scale the number of Argon2 passes so that the
  1249. * overall time taken is about 1/10 second. (Again, I could crank
  1250. * this up to a larger time and _most_ people might be OK with it,
  1251. * but for the moment, I'm trying to err on the side of not
  1252. * stopping anyone from using the tools at all.)
  1253. */
  1254. .argon2_passes_auto = true,
  1255. .argon2_milliseconds = 100,
  1256. /*
  1257. * PuTTY's own Argon2 implementation is single-threaded. So we
  1258. * might as well set parallelism to 1, which requires that
  1259. * attackers' implementations must also be effectively
  1260. * single-threaded, and they don't get any benefit from using
  1261. * multiple cores on the same hash attempt. (Of course they can
  1262. * still use multiple cores for _separate_ hash attempts, but at
  1263. * least they don't get a speed advantage over us in computing
  1264. * even one hash.)
  1265. */
  1266. .argon2_parallelism = 1,
  1267. };
  1268. strbuf *ppk_save_sb(ssh2_userkey *key, const char *passphrase,
  1269. const ppk_save_parameters *params_orig)
  1270. {
  1271. strbuf *pub_blob, *priv_blob, *cipher_mac_keys_blob;
  1272. unsigned char *priv_blob_encrypted;
  1273. int priv_encrypted_len;
  1274. int cipherblk;
  1275. int i;
  1276. const char *cipherstr;
  1277. ptrlen cipherkey, cipheriv, mackey;
  1278. const struct ppk_cipher *ciphertype;
  1279. unsigned char priv_mac[32];
  1280. /*
  1281. * Fetch the key component blobs.
  1282. */
  1283. pub_blob = strbuf_new();
  1284. ssh_key_public_blob(key->key, BinarySink_UPCAST(pub_blob));
  1285. priv_blob = strbuf_new_nm();
  1286. ssh_key_private_blob(key->key, BinarySink_UPCAST(priv_blob));
  1287. /*
  1288. * Determine encryption details, and encrypt the private blob.
  1289. */
  1290. if (passphrase) {
  1291. cipherstr = "aes256-cbc";
  1292. cipherblk = 16;
  1293. ciphertype = &ppk_cipher_aes256_cbc;
  1294. } else {
  1295. cipherstr = "none";
  1296. cipherblk = 1;
  1297. ciphertype = &ppk_cipher_none;
  1298. }
  1299. priv_encrypted_len = priv_blob->len + cipherblk - 1;
  1300. priv_encrypted_len -= priv_encrypted_len % cipherblk;
  1301. priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);
  1302. memset(priv_blob_encrypted, 0, priv_encrypted_len);
  1303. memcpy(priv_blob_encrypted, priv_blob->u, priv_blob->len);
  1304. /* Create padding based on the SHA hash of the unpadded blob. This prevents
  1305. * too easy a known-plaintext attack on the last block. */
  1306. hash_simple(&ssh_sha1, ptrlen_from_strbuf(priv_blob), priv_mac);
  1307. assert(priv_encrypted_len - priv_blob->len < 20);
  1308. memcpy(priv_blob_encrypted + priv_blob->len, priv_mac,
  1309. priv_encrypted_len - priv_blob->len);
  1310. /* Copy the save parameters, so that when derive_keys chooses the
  1311. * number of Argon2 passes, it can write the result back to our
  1312. * copy for us to retrieve. */
  1313. ppk_save_parameters params = *params_orig;
  1314. strbuf *passphrase_salt = strbuf_new();
  1315. if (params.fmt_version == 3) {
  1316. /* Invent a salt for the password hash. */
  1317. if (params.salt)
  1318. put_data(passphrase_salt, params.salt, params.saltlen);
  1319. else
  1320. random_read(strbuf_append(passphrase_salt, 16), 16);
  1321. }
  1322. cipher_mac_keys_blob = strbuf_new();
  1323. ssh2_ppk_derive_keys(params.fmt_version, ciphertype,
  1324. ptrlen_from_asciz(passphrase ? passphrase : ""),
  1325. cipher_mac_keys_blob, &cipherkey, &cipheriv, &mackey,
  1326. ptrlen_from_strbuf(passphrase_salt), &params);
  1327. const ssh2_macalg *macalg = (params.fmt_version == 2 ?
  1328. &ssh_hmac_sha1 : &ssh_hmac_sha256);
  1329. /* Now create the MAC. */
  1330. {
  1331. strbuf *macdata;
  1332. macdata = strbuf_new_nm();
  1333. put_stringz(macdata, ssh_key_ssh_id(key->key));
  1334. put_stringz(macdata, cipherstr);
  1335. put_stringz(macdata, key->comment);
  1336. put_string(macdata, pub_blob->s, pub_blob->len);
  1337. put_string(macdata, priv_blob_encrypted, priv_encrypted_len);
  1338. mac_simple(macalg, mackey, ptrlen_from_strbuf(macdata), priv_mac);
  1339. strbuf_free(macdata);
  1340. }
  1341. if (passphrase) {
  1342. assert(cipherkey.len == 32);
  1343. aes256_encrypt_pubkey(cipherkey.ptr, cipheriv.ptr,
  1344. priv_blob_encrypted, priv_encrypted_len);
  1345. }
  1346. strbuf *out = strbuf_new_nm();
  1347. put_fmt(out, "PuTTY-User-Key-File-%u: %s\n",
  1348. params.fmt_version, ssh_key_ssh_id(key->key));
  1349. put_fmt(out, "Encryption: %s\n", cipherstr);
  1350. put_fmt(out, "Comment: %s\n", key->comment);
  1351. put_fmt(out, "Public-Lines: %d\n", base64_lines(pub_blob->len));
  1352. base64_encode_bs(BinarySink_UPCAST(out), ptrlen_from_strbuf(pub_blob), 64);
  1353. if (params.fmt_version == 3 && ciphertype->keylen != 0) {
  1354. put_fmt(out, "Key-Derivation: %s\n",
  1355. params.argon2_flavour == Argon2d ? "Argon2d" :
  1356. params.argon2_flavour == Argon2i ? "Argon2i" : "Argon2id");
  1357. put_fmt(out, "Argon2-Memory: %"PRIu32"\n", params.argon2_mem);
  1358. assert(!params.argon2_passes_auto);
  1359. put_fmt(out, "Argon2-Passes: %"PRIu32"\n", params.argon2_passes);
  1360. put_fmt(out, "Argon2-Parallelism: %"PRIu32"\n",
  1361. params.argon2_parallelism);
  1362. put_fmt(out, "Argon2-Salt: ");
  1363. for (size_t i = 0; i < passphrase_salt->len; i++)
  1364. put_fmt(out, "%02x", passphrase_salt->u[i]);
  1365. put_fmt(out, "\n");
  1366. }
  1367. put_fmt(out, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
  1368. base64_encode_bs(BinarySink_UPCAST(out),
  1369. make_ptrlen(priv_blob_encrypted, priv_encrypted_len), 64);
  1370. put_fmt(out, "Private-MAC: ");
  1371. for (i = 0; i < macalg->len; i++)
  1372. put_fmt(out, "%02x", priv_mac[i]);
  1373. put_fmt(out, "\n");
  1374. strbuf_free(cipher_mac_keys_blob);
  1375. strbuf_free(passphrase_salt);
  1376. strbuf_free(pub_blob);
  1377. strbuf_free(priv_blob);
  1378. smemclr(priv_blob_encrypted, priv_encrypted_len);
  1379. sfree(priv_blob_encrypted);
  1380. return out;
  1381. }
  1382. bool ppk_save_f(const Filename *filename, ssh2_userkey *key,
  1383. const char *passphrase, const ppk_save_parameters *params)
  1384. {
  1385. FILE *fp = f_open(filename, "wb", true);
  1386. if (!fp)
  1387. return false;
  1388. strbuf *buf = ppk_save_sb(key, passphrase, params);
  1389. bool toret = fwrite(buf->s, 1, buf->len, fp) == buf->len;
  1390. if (fclose(fp))
  1391. toret = false;
  1392. strbuf_free(buf);
  1393. return toret;
  1394. }
  1395. /* ----------------------------------------------------------------------
  1396. * Output public keys.
  1397. */
  1398. char *ssh1_pubkey_str(RSAKey *key)
  1399. {
  1400. char *buffer;
  1401. char *dec1, *dec2;
  1402. dec1 = mp_get_decimal(key->exponent);
  1403. dec2 = mp_get_decimal(key->modulus);
  1404. buffer = dupprintf("%"SIZEu" %s %s%s%s", mp_get_nbits(key->modulus),
  1405. dec1, dec2, key->comment ? " " : "",
  1406. key->comment ? key->comment : "");
  1407. sfree(dec1);
  1408. sfree(dec2);
  1409. return buffer;
  1410. }
  1411. void ssh1_write_pubkey(FILE *fp, RSAKey *key)
  1412. {
  1413. char *buffer = ssh1_pubkey_str(key);
  1414. fprintf(fp, "%s\n", buffer);
  1415. sfree(buffer);
  1416. }
  1417. static char *ssh2_pubkey_openssh_str_internal(const char *comment,
  1418. const void *v_pub_blob,
  1419. int pub_len)
  1420. {
  1421. const unsigned char *ssh2blob = (const unsigned char *)v_pub_blob;
  1422. ptrlen alg;
  1423. char *buffer, *p;
  1424. int i;
  1425. {
  1426. BinarySource src[1];
  1427. BinarySource_BARE_INIT(src, ssh2blob, pub_len);
  1428. alg = get_string(src);
  1429. if (get_err(src)) {
  1430. const char *replacement_str = "INVALID-ALGORITHM";
  1431. alg.ptr = replacement_str;
  1432. alg.len = strlen(replacement_str);
  1433. }
  1434. }
  1435. buffer = snewn(alg.len +
  1436. 4 * ((pub_len+2) / 3) +
  1437. (comment ? strlen(comment) : 0) + 3, char);
  1438. p = buffer + sprintf(buffer, "%.*s ", PTRLEN_PRINTF(alg));
  1439. i = 0;
  1440. while (i < pub_len) {
  1441. int n = (pub_len - i < 3 ? pub_len - i : 3);
  1442. base64_encode_atom(ssh2blob + i, n, p);
  1443. i += n;
  1444. p += 4;
  1445. }
  1446. if (comment) {
  1447. *p++ = ' ';
  1448. strcpy(p, comment);
  1449. } else
  1450. *p++ = '\0';
  1451. return buffer;
  1452. }
  1453. char *ssh2_pubkey_openssh_str(ssh2_userkey *key)
  1454. {
  1455. strbuf *blob;
  1456. char *ret;
  1457. blob = strbuf_new();
  1458. ssh_key_public_blob(key->key, BinarySink_UPCAST(blob));
  1459. ret = ssh2_pubkey_openssh_str_internal(
  1460. key->comment, blob->s, blob->len);
  1461. strbuf_free(blob);
  1462. return ret;
  1463. }
  1464. void ssh2_write_pubkey(FILE *fp, const char *comment,
  1465. const void *v_pub_blob, int pub_len,
  1466. int keytype)
  1467. {
  1468. unsigned char *pub_blob = (unsigned char *)v_pub_blob;
  1469. if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {
  1470. const char *p;
  1471. int i, column;
  1472. fprintf(fp, "---- BEGIN SSH2 PUBLIC KEY ----\n");
  1473. if (comment) {
  1474. fprintf(fp, "Comment: \"");
  1475. for (p = comment; *p; p++) {
  1476. if (*p == '\\' || *p == '\"')
  1477. fputc('\\', fp);
  1478. fputc(*p, fp);
  1479. }
  1480. fprintf(fp, "\"\n");
  1481. }
  1482. i = 0;
  1483. column = 0;
  1484. while (i < pub_len) {
  1485. char buf[5];
  1486. int n = (pub_len - i < 3 ? pub_len - i : 3);
  1487. base64_encode_atom(pub_blob + i, n, buf);
  1488. i += n;
  1489. buf[4] = '\0';
  1490. fputs(buf, fp);
  1491. if (++column >= 16) {
  1492. fputc('\n', fp);
  1493. column = 0;
  1494. }
  1495. }
  1496. if (column > 0)
  1497. fputc('\n', fp);
  1498. fprintf(fp, "---- END SSH2 PUBLIC KEY ----\n");
  1499. } else if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  1500. char *buffer = ssh2_pubkey_openssh_str_internal(comment,
  1501. v_pub_blob, pub_len);
  1502. fprintf(fp, "%s\n", buffer);
  1503. sfree(buffer);
  1504. } else {
  1505. unreachable("Bad key type in ssh2_write_pubkey");
  1506. }
  1507. }
  1508. /* ----------------------------------------------------------------------
  1509. * Utility functions to compute SSH-2 fingerprints in a uniform way.
  1510. */
  1511. static void ssh2_fingerprint_blob_md5(ptrlen blob, strbuf *sb)
  1512. {
  1513. unsigned char digest[16];
  1514. hash_simple(&ssh_md5, blob, digest);
  1515. for (unsigned i = 0; i < 16; i++)
  1516. put_fmt(sb, "%02x%s", digest[i], i==15 ? "" : ":");
  1517. }
  1518. static void ssh2_fingerprint_blob_sha256(ptrlen blob, strbuf *sb)
  1519. {
  1520. unsigned char digest[32];
  1521. hash_simple(&ssh_sha256, blob, digest);
  1522. put_datapl(sb, PTRLEN_LITERAL("SHA256:"));
  1523. for (unsigned i = 0; i < 32; i += 3) {
  1524. char buf[5];
  1525. unsigned len = 32-i;
  1526. if (len > 3)
  1527. len = 3;
  1528. base64_encode_atom(digest + i, len, buf);
  1529. put_data(sb, buf, 4);
  1530. }
  1531. strbuf_chomp(sb, '=');
  1532. }
  1533. char *ssh2_fingerprint_blob(ptrlen blob, FingerprintType fptype)
  1534. {
  1535. strbuf *sb = strbuf_new();
  1536. strbuf *tmp = NULL;
  1537. /*
  1538. * Identify the key algorithm, if possible.
  1539. *
  1540. * If we can't do that, then we have a seriously confused key
  1541. * blob, in which case we return only the hash.
  1542. */
  1543. BinarySource src[1];
  1544. BinarySource_BARE_INIT_PL(src, blob);
  1545. ptrlen algname = get_string(src);
  1546. if (!get_err(src)) {
  1547. const ssh_keyalg *alg = find_pubkey_alg_len(algname);
  1548. if (alg) {
  1549. int bits = ssh_key_public_bits(alg, blob);
  1550. put_fmt(sb, "%.*s %d ", PTRLEN_PRINTF(algname), bits);
  1551. if (!ssh_fptype_is_cert(fptype) && alg->is_certificate) {
  1552. ssh_key *key = ssh_key_new_pub(alg, blob);
  1553. if (key) {
  1554. tmp = strbuf_new();
  1555. ssh_key_public_blob(ssh_key_base_key(key),
  1556. BinarySink_UPCAST(tmp));
  1557. blob = ptrlen_from_strbuf(tmp);
  1558. ssh_key_free(key);
  1559. }
  1560. }
  1561. } else {
  1562. put_fmt(sb, "%.*s ", PTRLEN_PRINTF(algname));
  1563. }
  1564. }
  1565. switch (ssh_fptype_from_cert(fptype)) {
  1566. case SSH_FPTYPE_MD5:
  1567. ssh2_fingerprint_blob_md5(blob, sb);
  1568. break;
  1569. case SSH_FPTYPE_SHA256:
  1570. ssh2_fingerprint_blob_sha256(blob, sb);
  1571. break;
  1572. default:
  1573. unreachable("ssh_fptype_from_cert ruled out the other values");
  1574. }
  1575. if (tmp)
  1576. strbuf_free(tmp);
  1577. return strbuf_to_str(sb);
  1578. }
  1579. char *ssh2_double_fingerprint_blob(ptrlen blob, FingerprintType fptype)
  1580. {
  1581. if (ssh_fptype_is_cert(fptype))
  1582. fptype = ssh_fptype_from_cert(fptype);
  1583. char *fp = ssh2_fingerprint_blob(blob, fptype);
  1584. char *p = strrchr(fp, ' ');
  1585. char *hash = p ? p + 1 : fp;
  1586. char *fpc = ssh2_fingerprint_blob(blob, ssh_fptype_to_cert(fptype));
  1587. char *pc = strrchr(fpc, ' ');
  1588. char *hashc = pc ? pc + 1 : fpc;
  1589. if (strcmp(hash, hashc)) {
  1590. char *tmp = dupprintf("%s (with certificate: %s)", fp, hashc);
  1591. sfree(fp);
  1592. fp = tmp;
  1593. }
  1594. sfree(fpc);
  1595. return fp;
  1596. }
  1597. char **ssh2_all_fingerprints_for_blob(ptrlen blob)
  1598. {
  1599. char **fps = snewn(SSH_N_FPTYPES, char *);
  1600. for (unsigned i = 0; i < SSH_N_FPTYPES; i++)
  1601. fps[i] = ssh2_fingerprint_blob(blob, i);
  1602. return fps;
  1603. }
  1604. char *ssh2_fingerprint(ssh_key *data, FingerprintType fptype)
  1605. {
  1606. strbuf *blob = strbuf_new();
  1607. ssh_key_public_blob(data, BinarySink_UPCAST(blob));
  1608. char *ret = ssh2_fingerprint_blob(ptrlen_from_strbuf(blob), fptype);
  1609. strbuf_free(blob);
  1610. return ret;
  1611. }
  1612. char *ssh2_double_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_double_fingerprint_blob(ptrlen_from_strbuf(blob), fptype);
  1617. strbuf_free(blob);
  1618. return ret;
  1619. }
  1620. char **ssh2_all_fingerprints(ssh_key *data)
  1621. {
  1622. strbuf *blob = strbuf_new();
  1623. ssh_key_public_blob(data, BinarySink_UPCAST(blob));
  1624. char **ret = ssh2_all_fingerprints_for_blob(ptrlen_from_strbuf(blob));
  1625. strbuf_free(blob);
  1626. return ret;
  1627. }
  1628. void ssh2_free_all_fingerprints(char **fps)
  1629. {
  1630. for (unsigned i = 0; i < SSH_N_FPTYPES; i++)
  1631. sfree(fps[i]);
  1632. sfree(fps);
  1633. }
  1634. /* ----------------------------------------------------------------------
  1635. * Determine the type of a private key file.
  1636. */
  1637. static int key_type_s_internal(BinarySource *src)
  1638. {
  1639. static const ptrlen public_std_sig =
  1640. PTRLEN_DECL_LITERAL("---- BEGIN SSH2 PUBLIC KEY");
  1641. static const ptrlen putty2_sig =
  1642. PTRLEN_DECL_LITERAL("PuTTY-User-Key-File-");
  1643. static const ptrlen sshcom_sig =
  1644. PTRLEN_DECL_LITERAL("---- BEGIN SSH2 ENCRYPTED PRIVAT");
  1645. static const ptrlen openssh_new_sig =
  1646. PTRLEN_DECL_LITERAL("-----BEGIN OPENSSH PRIVATE KEY");
  1647. static const ptrlen openssh_sig =
  1648. PTRLEN_DECL_LITERAL("-----BEGIN ");
  1649. if (BinarySource_REWIND(src), expect_signature(src, rsa1_signature))
  1650. return SSH_KEYTYPE_SSH1;
  1651. if (BinarySource_REWIND(src), expect_signature(src, public_std_sig))
  1652. return SSH_KEYTYPE_SSH2_PUBLIC_RFC4716;
  1653. if (BinarySource_REWIND(src), expect_signature(src, putty2_sig))
  1654. return SSH_KEYTYPE_SSH2;
  1655. if (BinarySource_REWIND(src), expect_signature(src, openssh_new_sig))
  1656. return SSH_KEYTYPE_OPENSSH_NEW;
  1657. if (BinarySource_REWIND(src), expect_signature(src, openssh_sig))
  1658. return SSH_KEYTYPE_OPENSSH_PEM;
  1659. if (BinarySource_REWIND(src), expect_signature(src, sshcom_sig))
  1660. return SSH_KEYTYPE_SSHCOM;
  1661. BinarySource_REWIND(src);
  1662. if (get_chars(src, "0123456789").len > 0 && get_chars(src, " ").len == 1 &&
  1663. get_chars(src, "0123456789").len > 0 && get_chars(src, " ").len == 1 &&
  1664. get_chars(src, "0123456789").len > 0 &&
  1665. get_nonchars(src, " \n").len == 0)
  1666. return SSH_KEYTYPE_SSH1_PUBLIC;
  1667. BinarySource_REWIND(src);
  1668. if (find_pubkey_alg_len(get_nonchars(src, " \n")) > 0 &&
  1669. get_chars(src, " ").len == 1 &&
  1670. get_chars(src, "0123456789ABCDEFGHIJKLMNOPQRSTUV"
  1671. "WXYZabcdefghijklmnopqrstuvwxyz+/=").len > 0 &&
  1672. get_nonchars(src, " \n").len == 0)
  1673. return SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH;
  1674. return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */
  1675. }
  1676. int key_type_s(BinarySource *src)
  1677. {
  1678. int toret = key_type_s_internal(src);
  1679. BinarySource_REWIND(src);
  1680. return toret;
  1681. }
  1682. int key_type(const Filename *filename)
  1683. {
  1684. LoadedFile *lf = lf_new(1024);
  1685. if (lf_load(lf, filename) == LF_ERROR) {
  1686. lf_free(lf);
  1687. return SSH_KEYTYPE_UNOPENABLE;
  1688. }
  1689. int toret = key_type_s(BinarySource_UPCAST(lf));
  1690. lf_free(lf);
  1691. return toret;
  1692. }
  1693. /*
  1694. * Convert the type word to a string, for `wrong type' error
  1695. * messages.
  1696. */
  1697. const char *key_type_to_str(int type)
  1698. {
  1699. switch (type) {
  1700. case SSH_KEYTYPE_UNOPENABLE:
  1701. return "unable to open file";
  1702. case SSH_KEYTYPE_UNKNOWN:
  1703. return "not a recognised key file format";
  1704. case SSH_KEYTYPE_SSH1_PUBLIC:
  1705. return "SSH-1 public key";
  1706. case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716:
  1707. return "SSH-2 public key (RFC 4716 format)";
  1708. case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH:
  1709. return "SSH-2 public key (OpenSSH format)";
  1710. case SSH_KEYTYPE_SSH1:
  1711. return "SSH-1 private key";
  1712. case SSH_KEYTYPE_SSH2:
  1713. return "PuTTY SSH-2 private key";
  1714. case SSH_KEYTYPE_OPENSSH_PEM:
  1715. return "OpenSSH SSH-2 private key (old PEM format)";
  1716. case SSH_KEYTYPE_OPENSSH_NEW:
  1717. return "OpenSSH SSH-2 private key (new format)";
  1718. case SSH_KEYTYPE_SSHCOM:
  1719. return "ssh.com SSH-2 private key";
  1720. /*
  1721. * This function is called with a key type derived from
  1722. * looking at an actual key file, so the output-only type
  1723. * OPENSSH_AUTO should never get here, and is much an INTERNAL
  1724. * ERROR as a code we don't even understand.
  1725. */
  1726. case SSH_KEYTYPE_OPENSSH_AUTO:
  1727. unreachable("OPENSSH_AUTO should never reach key_type_to_str");
  1728. default:
  1729. unreachable("bad key type in key_type_to_str");
  1730. }
  1731. }