1
0

sshpubk.c 58 KB

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