sshpubk.c 61 KB

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