sshpubk.c 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  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,
  503. &ssh_rsa_sha512,
  504. &ssh_dss,
  505. &ssh_ecdsa_nistp256,
  506. &ssh_ecdsa_nistp384,
  507. &ssh_ecdsa_nistp521,
  508. &ssh_ecdsa_ed25519,
  509. &ssh_ecdsa_ed448,
  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. static void base64_encode_s(BinarySink *bs, const unsigned char *data,
  1252. int datalen, int cpl)
  1253. {
  1254. int linelen = 0;
  1255. char out[4];
  1256. int n, i;
  1257. while (datalen > 0) {
  1258. n = (datalen < 3 ? datalen : 3);
  1259. base64_encode_atom(data, n, out);
  1260. data += n;
  1261. datalen -= n;
  1262. for (i = 0; i < 4; i++) {
  1263. if (linelen >= cpl) {
  1264. linelen = 0;
  1265. put_byte(bs, '\n');
  1266. }
  1267. put_byte(bs, out[i]);
  1268. linelen++;
  1269. }
  1270. }
  1271. put_byte(bs, '\n');
  1272. }
  1273. void base64_encode(FILE *fp, const unsigned char *data, int datalen, int cpl)
  1274. {
  1275. stdio_sink ss;
  1276. stdio_sink_init(&ss, fp);
  1277. base64_encode_s(BinarySink_UPCAST(&ss), data, datalen, cpl);
  1278. }
  1279. const ppk_save_parameters ppk_save_default_parameters = {
  1280. // WINSCP
  1281. /*.fmt_version =*/ 3,
  1282. /*
  1283. * The Argon2 spec recommends the hybrid variant Argon2id, where
  1284. * you don't have a good reason to go with the pure Argon2d or
  1285. * Argon2i.
  1286. */
  1287. /*.argon2_flavour =*/ Argon2id,
  1288. /*
  1289. * Memory requirement for hashing a password: I don't want to set
  1290. * this to some truly huge thing like a gigabyte, because for all
  1291. * I know people might perfectly reasonably be running PuTTY on
  1292. * machines that don't _have_ a gigabyte spare to hash a private
  1293. * key passphrase in the legitimate use cases.
  1294. *
  1295. * I've picked 8 MB as an amount of memory that isn't unreasonable
  1296. * to expect a desktop client machine to have, but is also large
  1297. * compared to the memory requirements of the PPK v2 password hash
  1298. * (which was plain SHA-1), so it still imposes a limit on
  1299. * parallel attacks on someone's key file.
  1300. */
  1301. /*.argon2_mem =*/ 8192, /* require 8 Mb memory */
  1302. /*
  1303. * Automatically scale the number of Argon2 passes so that the
  1304. * overall time taken is about 1/10 second. (Again, I could crank
  1305. * this up to a larger time and _most_ people might be OK with it,
  1306. * but for the moment, I'm trying to err on the side of not
  1307. * stopping anyone from using the tools at all.)
  1308. */
  1309. /*.argon2_passes_auto =*/ true,
  1310. /*.argon2_milliseconds =*/ 100,
  1311. /*
  1312. * PuTTY's own Argon2 implementation is single-threaded. So we
  1313. * might as well set parallelism to 1, which requires that
  1314. * attackers' implementations must also be effectively
  1315. * single-threaded, and they don't get any benefit from using
  1316. * multiple cores on the same hash attempt. (Of course they can
  1317. * still use multiple cores for _separate_ hash attempts, but at
  1318. * least they don't get a speed advantage over us in computing
  1319. * even one hash.)
  1320. */
  1321. /*.argon2_parallelism =*/ 1,
  1322. NULL, 0, // WINSCP
  1323. };
  1324. strbuf *ppk_save_sb(ssh2_userkey *key, const char *passphrase,
  1325. const ppk_save_parameters *params_orig)
  1326. {
  1327. strbuf *pub_blob, *priv_blob, *cipher_mac_keys_blob;
  1328. unsigned char *priv_blob_encrypted;
  1329. int priv_encrypted_len;
  1330. int cipherblk;
  1331. int i;
  1332. const char *cipherstr;
  1333. ptrlen cipherkey, cipheriv, mackey;
  1334. const struct ppk_cipher *ciphertype;
  1335. unsigned char priv_mac[32];
  1336. /*
  1337. * Fetch the key component blobs.
  1338. */
  1339. pub_blob = strbuf_new();
  1340. ssh_key_public_blob(key->key, BinarySink_UPCAST(pub_blob));
  1341. priv_blob = strbuf_new_nm();
  1342. ssh_key_private_blob(key->key, BinarySink_UPCAST(priv_blob));
  1343. /*
  1344. * Determine encryption details, and encrypt the private blob.
  1345. */
  1346. if (passphrase) {
  1347. cipherstr = "aes256-cbc";
  1348. cipherblk = 16;
  1349. ciphertype = &ppk_cipher_aes256_cbc;
  1350. } else {
  1351. cipherstr = "none";
  1352. cipherblk = 1;
  1353. ciphertype = &ppk_cipher_none;
  1354. }
  1355. priv_encrypted_len = priv_blob->len + cipherblk - 1;
  1356. priv_encrypted_len -= priv_encrypted_len % cipherblk;
  1357. priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);
  1358. memset(priv_blob_encrypted, 0, priv_encrypted_len);
  1359. memcpy(priv_blob_encrypted, priv_blob->u, priv_blob->len);
  1360. /* Create padding based on the SHA hash of the unpadded blob. This prevents
  1361. * too easy a known-plaintext attack on the last block. */
  1362. hash_simple(&ssh_sha1, ptrlen_from_strbuf(priv_blob), priv_mac);
  1363. assert(priv_encrypted_len - priv_blob->len < 20);
  1364. memcpy(priv_blob_encrypted + priv_blob->len, priv_mac,
  1365. priv_encrypted_len - priv_blob->len);
  1366. /* Copy the save parameters, so that when derive_keys chooses the
  1367. * number of Argon2 passes, it can write the result back to our
  1368. * copy for us to retrieve. */
  1369. { // WINSCP
  1370. ppk_save_parameters params = *params_orig;
  1371. strbuf *passphrase_salt = strbuf_new();
  1372. if (params.fmt_version == 3) {
  1373. /* Invent a salt for the password hash. */
  1374. if (params.salt)
  1375. put_data(passphrase_salt, params.salt, params.saltlen);
  1376. else
  1377. random_read(strbuf_append(passphrase_salt, 16), 16);
  1378. }
  1379. cipher_mac_keys_blob = strbuf_new();
  1380. ssh2_ppk_derive_keys(params.fmt_version, ciphertype,
  1381. ptrlen_from_asciz(passphrase ? passphrase : ""),
  1382. cipher_mac_keys_blob, &cipherkey, &cipheriv, &mackey,
  1383. ptrlen_from_strbuf(passphrase_salt), &params);
  1384. { // WINSCP
  1385. const ssh2_macalg *macalg = (params.fmt_version == 2 ?
  1386. &ssh_hmac_sha1 : &ssh_hmac_sha256);
  1387. /* Now create the MAC. */
  1388. {
  1389. strbuf *macdata;
  1390. macdata = strbuf_new_nm();
  1391. put_stringz(macdata, ssh_key_ssh_id(key->key));
  1392. put_stringz(macdata, cipherstr);
  1393. put_stringz(macdata, key->comment);
  1394. put_string(macdata, pub_blob->s, pub_blob->len);
  1395. put_string(macdata, priv_blob_encrypted, priv_encrypted_len);
  1396. mac_simple(macalg, mackey, ptrlen_from_strbuf(macdata), priv_mac);
  1397. strbuf_free(macdata);
  1398. }
  1399. if (passphrase) {
  1400. assert(cipherkey.len == 32);
  1401. aes256_encrypt_pubkey(cipherkey.ptr, cipheriv.ptr,
  1402. priv_blob_encrypted, priv_encrypted_len);
  1403. }
  1404. { // WINSCP
  1405. strbuf *out = strbuf_new_nm();
  1406. strbuf_catf(out, "PuTTY-User-Key-File-%u: %s\n",
  1407. params.fmt_version, ssh_key_ssh_id(key->key));
  1408. strbuf_catf(out, "Encryption: %s\n", cipherstr);
  1409. strbuf_catf(out, "Comment: %s\n", key->comment);
  1410. strbuf_catf(out, "Public-Lines: %d\n", base64_lines(pub_blob->len));
  1411. base64_encode_s(BinarySink_UPCAST(out), pub_blob->u, pub_blob->len, 64);
  1412. if (params.fmt_version == 3 && ciphertype->keylen != 0) {
  1413. strbuf_catf(out, "Key-Derivation: %s\n",
  1414. params.argon2_flavour == Argon2d ? "Argon2d" :
  1415. params.argon2_flavour == Argon2i ? "Argon2i" : "Argon2id");
  1416. strbuf_catf(out, "Argon2-Memory: %"PRIu32"\n", params.argon2_mem);
  1417. assert(!params.argon2_passes_auto);
  1418. strbuf_catf(out, "Argon2-Passes: %"PRIu32"\n", params.argon2_passes);
  1419. strbuf_catf(out, "Argon2-Parallelism: %"PRIu32"\n",
  1420. params.argon2_parallelism);
  1421. strbuf_catf(out, "Argon2-Salt: ");
  1422. { // WINSCP
  1423. size_t i;
  1424. for (i = 0; i < passphrase_salt->len; i++)
  1425. strbuf_catf(out, "%02x", passphrase_salt->u[i]);
  1426. } // WINSCP
  1427. strbuf_catf(out, "\n");
  1428. }
  1429. strbuf_catf(out, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
  1430. base64_encode_s(BinarySink_UPCAST(out),
  1431. priv_blob_encrypted, priv_encrypted_len, 64);
  1432. strbuf_catf(out, "Private-MAC: ");
  1433. for (i = 0; i < macalg->len; i++)
  1434. strbuf_catf(out, "%02x", priv_mac[i]);
  1435. strbuf_catf(out, "\n");
  1436. strbuf_free(cipher_mac_keys_blob);
  1437. strbuf_free(passphrase_salt);
  1438. strbuf_free(pub_blob);
  1439. strbuf_free(priv_blob);
  1440. smemclr(priv_blob_encrypted, priv_encrypted_len);
  1441. sfree(priv_blob_encrypted);
  1442. return out;
  1443. } // WINSCP
  1444. } // WINSCP
  1445. } // WINSCP
  1446. }
  1447. bool ppk_save_f(const Filename *filename, ssh2_userkey *key,
  1448. const char *passphrase, const ppk_save_parameters *params)
  1449. {
  1450. FILE *fp = f_open(filename, "wb", true);
  1451. if (!fp)
  1452. return false;
  1453. { // WINSCP
  1454. strbuf *buf = ppk_save_sb(key, passphrase, params);
  1455. bool toret = fwrite(buf->s, 1, buf->len, fp) == buf->len;
  1456. if (fclose(fp))
  1457. toret = false;
  1458. strbuf_free(buf);
  1459. return toret;
  1460. } // WINSCP
  1461. }
  1462. /* ----------------------------------------------------------------------
  1463. * Output public keys.
  1464. */
  1465. char *ssh1_pubkey_str(RSAKey *key)
  1466. {
  1467. char *buffer;
  1468. char *dec1, *dec2;
  1469. dec1 = mp_get_decimal(key->exponent);
  1470. dec2 = mp_get_decimal(key->modulus);
  1471. buffer = dupprintf("%"SIZEu" %s %s%s%s", mp_get_nbits(key->modulus),
  1472. dec1, dec2, key->comment ? " " : "",
  1473. key->comment ? key->comment : "");
  1474. sfree(dec1);
  1475. sfree(dec2);
  1476. return buffer;
  1477. }
  1478. void ssh1_write_pubkey(FILE *fp, RSAKey *key)
  1479. {
  1480. char *buffer = ssh1_pubkey_str(key);
  1481. fprintf(fp, "%s\n", buffer);
  1482. sfree(buffer);
  1483. }
  1484. static char *ssh2_pubkey_openssh_str_internal(const char *comment,
  1485. const void *v_pub_blob,
  1486. int pub_len)
  1487. {
  1488. const unsigned char *ssh2blob = (const unsigned char *)v_pub_blob;
  1489. ptrlen alg;
  1490. char *buffer, *p;
  1491. int i;
  1492. {
  1493. BinarySource src[1];
  1494. BinarySource_BARE_INIT(src, ssh2blob, pub_len);
  1495. alg = get_string(src);
  1496. if (get_err(src)) {
  1497. const char *replacement_str = "INVALID-ALGORITHM";
  1498. alg.ptr = replacement_str;
  1499. alg.len = strlen(replacement_str);
  1500. }
  1501. }
  1502. buffer = snewn(alg.len +
  1503. 4 * ((pub_len+2) / 3) +
  1504. (comment ? strlen(comment) : 0) + 3, char);
  1505. p = buffer + sprintf(buffer, "%.*s ", PTRLEN_PRINTF(alg));
  1506. i = 0;
  1507. while (i < pub_len) {
  1508. int n = (pub_len - i < 3 ? pub_len - i : 3);
  1509. base64_encode_atom(ssh2blob + i, n, p);
  1510. i += n;
  1511. p += 4;
  1512. }
  1513. if (comment) {
  1514. *p++ = ' ';
  1515. strcpy(p, comment);
  1516. } else
  1517. *p++ = '\0';
  1518. return buffer;
  1519. }
  1520. char *ssh2_pubkey_openssh_str(ssh2_userkey *key)
  1521. {
  1522. strbuf *blob;
  1523. char *ret;
  1524. blob = strbuf_new();
  1525. ssh_key_public_blob(key->key, BinarySink_UPCAST(blob));
  1526. ret = ssh2_pubkey_openssh_str_internal(
  1527. key->comment, blob->s, blob->len);
  1528. strbuf_free(blob);
  1529. return ret;
  1530. }
  1531. void ssh2_write_pubkey(FILE *fp, const char *comment,
  1532. const void *v_pub_blob, int pub_len,
  1533. int keytype)
  1534. {
  1535. unsigned char *pub_blob = (unsigned char *)v_pub_blob;
  1536. if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {
  1537. const char *p;
  1538. int i, column;
  1539. fprintf(fp, "---- BEGIN SSH2 PUBLIC KEY ----\n");
  1540. if (comment) {
  1541. fprintf(fp, "Comment: \"");
  1542. for (p = comment; *p; p++) {
  1543. if (*p == '\\' || *p == '\"')
  1544. fputc('\\', fp);
  1545. fputc(*p, fp);
  1546. }
  1547. fprintf(fp, "\"\n");
  1548. }
  1549. i = 0;
  1550. column = 0;
  1551. while (i < pub_len) {
  1552. char buf[5];
  1553. int n = (pub_len - i < 3 ? pub_len - i : 3);
  1554. base64_encode_atom(pub_blob + i, n, buf);
  1555. i += n;
  1556. buf[4] = '\0';
  1557. fputs(buf, fp);
  1558. if (++column >= 16) {
  1559. fputc('\n', fp);
  1560. column = 0;
  1561. }
  1562. }
  1563. if (column > 0)
  1564. fputc('\n', fp);
  1565. fprintf(fp, "---- END SSH2 PUBLIC KEY ----\n");
  1566. } else if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  1567. char *buffer = ssh2_pubkey_openssh_str_internal(comment,
  1568. v_pub_blob, pub_len);
  1569. fprintf(fp, "%s\n", buffer);
  1570. sfree(buffer);
  1571. } else {
  1572. unreachable("Bad key type in ssh2_write_pubkey");
  1573. }
  1574. }
  1575. /* ----------------------------------------------------------------------
  1576. * Utility functions to compute SSH-2 fingerprints in a uniform way.
  1577. */
  1578. static void ssh2_fingerprint_blob_md5(ptrlen blob, strbuf *sb)
  1579. {
  1580. unsigned char digest[16];
  1581. unsigned i; // WINSCP
  1582. hash_simple(&ssh_md5, blob, digest);
  1583. for (i = 0; i < 16; i++)
  1584. strbuf_catf(sb, "%02x%s", digest[i], i==15 ? "" : ":");
  1585. }
  1586. static void ssh2_fingerprint_blob_sha256(ptrlen blob, strbuf *sb)
  1587. {
  1588. unsigned char digest[32];
  1589. hash_simple(&ssh_sha256, blob, digest);
  1590. put_datapl(sb, PTRLEN_LITERAL("SHA256:"));
  1591. { // WINSCP
  1592. unsigned i;
  1593. for (i = 0; i < 32; i += 3) {
  1594. char buf[5];
  1595. unsigned len = 32-i;
  1596. if (len > 3)
  1597. len = 3;
  1598. base64_encode_atom(digest + i, len, buf);
  1599. put_data(sb, buf, 4);
  1600. }
  1601. strbuf_chomp(sb, '=');
  1602. } // WINSCP
  1603. }
  1604. char *ssh2_fingerprint_blob(ptrlen blob, FingerprintType fptype)
  1605. {
  1606. strbuf *sb = strbuf_new();
  1607. /*
  1608. * Identify the key algorithm, if possible.
  1609. *
  1610. * If we can't do that, then we have a seriously confused key
  1611. * blob, in which case we return only the hash.
  1612. */
  1613. BinarySource src[1];
  1614. BinarySource_BARE_INIT_PL(src, blob);
  1615. { // WINSCP
  1616. ptrlen algname = get_string(src);
  1617. if (!get_err(src)) {
  1618. const ssh_keyalg *alg = find_pubkey_alg_len(algname);
  1619. if (alg) {
  1620. int bits = ssh_key_public_bits(alg, blob);
  1621. strbuf_catf(sb, "%.*s %d ", PTRLEN_PRINTF(algname), bits);
  1622. } else {
  1623. strbuf_catf(sb, "%.*s ", PTRLEN_PRINTF(algname));
  1624. }
  1625. }
  1626. } // WINSCP
  1627. switch (fptype) {
  1628. case SSH_FPTYPE_MD5:
  1629. ssh2_fingerprint_blob_md5(blob, sb);
  1630. break;
  1631. case SSH_FPTYPE_SHA256:
  1632. ssh2_fingerprint_blob_sha256(blob, sb);
  1633. break;
  1634. }
  1635. return strbuf_to_str(sb);
  1636. }
  1637. char **ssh2_all_fingerprints_for_blob(ptrlen blob)
  1638. {
  1639. char **fps = snewn(SSH_N_FPTYPES, char *);
  1640. unsigned i; // WINSCP
  1641. for (i = 0; i < SSH_N_FPTYPES; i++)
  1642. fps[i] = ssh2_fingerprint_blob(blob, i);
  1643. return fps;
  1644. }
  1645. char *ssh2_fingerprint(ssh_key *data, FingerprintType fptype)
  1646. {
  1647. strbuf *blob = strbuf_new();
  1648. char *ret; //MPEXT
  1649. ssh_key_public_blob(data, BinarySink_UPCAST(blob));
  1650. ret = ssh2_fingerprint_blob(ptrlen_from_strbuf(blob), fptype);
  1651. strbuf_free(blob);
  1652. return ret;
  1653. }
  1654. char **ssh2_all_fingerprints(ssh_key *data)
  1655. {
  1656. strbuf *blob = strbuf_new();
  1657. ssh_key_public_blob(data, BinarySink_UPCAST(blob));
  1658. { // WINSCP
  1659. char **ret = ssh2_all_fingerprints_for_blob(ptrlen_from_strbuf(blob));
  1660. strbuf_free(blob);
  1661. return ret;
  1662. } // WINSCP
  1663. }
  1664. void ssh2_free_all_fingerprints(char **fps)
  1665. {
  1666. unsigned i; // WINSCP
  1667. for (i = 0; i < SSH_N_FPTYPES; i++)
  1668. sfree(fps[i]);
  1669. sfree(fps);
  1670. }
  1671. /* ----------------------------------------------------------------------
  1672. * Determine the type of a private key file.
  1673. */
  1674. static int key_type_s_internal(BinarySource *src)
  1675. {
  1676. static const ptrlen public_std_sig =
  1677. PTRLEN_DECL_LITERAL("---- BEGIN SSH2 PUBLIC KEY");
  1678. static const ptrlen putty2_sig =
  1679. PTRLEN_DECL_LITERAL("PuTTY-User-Key-File-");
  1680. static const ptrlen sshcom_sig =
  1681. PTRLEN_DECL_LITERAL("---- BEGIN SSH2 ENCRYPTED PRIVAT");
  1682. static const ptrlen openssh_new_sig =
  1683. PTRLEN_DECL_LITERAL("-----BEGIN OPENSSH PRIVATE KEY");
  1684. static const ptrlen openssh_sig =
  1685. PTRLEN_DECL_LITERAL("-----BEGIN ");
  1686. if (BinarySource_REWIND(src), expect_signature(src, rsa1_signature))
  1687. return SSH_KEYTYPE_SSH1;
  1688. if (BinarySource_REWIND(src), expect_signature(src, public_std_sig))
  1689. return SSH_KEYTYPE_SSH2_PUBLIC_RFC4716;
  1690. if (BinarySource_REWIND(src), expect_signature(src, putty2_sig))
  1691. return SSH_KEYTYPE_SSH2;
  1692. if (BinarySource_REWIND(src), expect_signature(src, openssh_new_sig))
  1693. return SSH_KEYTYPE_OPENSSH_NEW;
  1694. if (BinarySource_REWIND(src), expect_signature(src, openssh_sig))
  1695. return SSH_KEYTYPE_OPENSSH_PEM;
  1696. if (BinarySource_REWIND(src), expect_signature(src, sshcom_sig))
  1697. return SSH_KEYTYPE_SSHCOM;
  1698. BinarySource_REWIND(src);
  1699. if (get_chars(src, "0123456789").len > 0 && get_chars(src, " ").len == 1 &&
  1700. get_chars(src, "0123456789").len > 0 && get_chars(src, " ").len == 1 &&
  1701. get_chars(src, "0123456789").len > 0 &&
  1702. get_nonchars(src, " \n").len == 0)
  1703. return SSH_KEYTYPE_SSH1_PUBLIC;
  1704. BinarySource_REWIND(src);
  1705. if (find_pubkey_alg_len(get_nonchars(src, " \n")) > 0 &&
  1706. get_chars(src, " ").len == 1 &&
  1707. get_chars(src, "0123456789ABCDEFGHIJKLMNOPQRSTUV"
  1708. "WXYZabcdefghijklmnopqrstuvwxyz+/=").len > 0 &&
  1709. get_nonchars(src, " \n").len == 0)
  1710. return SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH;
  1711. return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */
  1712. }
  1713. int key_type_s(BinarySource *src)
  1714. {
  1715. int toret = key_type_s_internal(src);
  1716. BinarySource_REWIND(src);
  1717. return toret;
  1718. }
  1719. int key_type(const Filename *filename)
  1720. {
  1721. LoadedFile *lf = lf_new(1024);
  1722. if (lf_load(lf, filename) == LF_ERROR) {
  1723. lf_free(lf);
  1724. return SSH_KEYTYPE_UNOPENABLE;
  1725. }
  1726. { // WINSCP
  1727. int toret = key_type_s(BinarySource_UPCAST(lf));
  1728. lf_free(lf);
  1729. return toret;
  1730. } // WINSCP
  1731. }
  1732. /*
  1733. * Convert the type word to a string, for `wrong type' error
  1734. * messages.
  1735. */
  1736. const char *key_type_to_str(int type)
  1737. {
  1738. switch (type) {
  1739. case SSH_KEYTYPE_UNOPENABLE:
  1740. return "unable to open file";
  1741. case SSH_KEYTYPE_UNKNOWN:
  1742. return "not a recognised key file format";
  1743. case SSH_KEYTYPE_SSH1_PUBLIC:
  1744. return "SSH-1 public key";
  1745. case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716:
  1746. return "SSH-2 public key (RFC 4716 format)";
  1747. case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH:
  1748. return "SSH-2 public key (OpenSSH format)";
  1749. case SSH_KEYTYPE_SSH1:
  1750. return "SSH-1 private key";
  1751. case SSH_KEYTYPE_SSH2:
  1752. return "PuTTY SSH-2 private key";
  1753. case SSH_KEYTYPE_OPENSSH_PEM:
  1754. return "OpenSSH SSH-2 private key (old PEM format)";
  1755. case SSH_KEYTYPE_OPENSSH_NEW:
  1756. return "OpenSSH SSH-2 private key (new format)";
  1757. case SSH_KEYTYPE_SSHCOM:
  1758. return "ssh.com SSH-2 private key";
  1759. /*
  1760. * This function is called with a key type derived from
  1761. * looking at an actual key file, so the output-only type
  1762. * OPENSSH_AUTO should never get here, and is much an INTERNAL
  1763. * ERROR as a code we don't even understand.
  1764. */
  1765. case SSH_KEYTYPE_OPENSSH_AUTO:
  1766. unreachable("OPENSSH_AUTO should never reach key_type_to_str");
  1767. default:
  1768. unreachable("bad key type in key_type_to_str");
  1769. }
  1770. }
  1771. key_components *key_components_new(void)
  1772. {
  1773. key_components *kc = snew(key_components);
  1774. kc->ncomponents = 0;
  1775. kc->componentsize = 0;
  1776. kc->components = NULL;
  1777. return kc;
  1778. }
  1779. void key_components_add_text(key_components *kc,
  1780. const char *name, const char *value)
  1781. {
  1782. sgrowarray(kc->components, kc->componentsize, kc->ncomponents);
  1783. { // WINSCP
  1784. size_t n = kc->ncomponents++;
  1785. kc->components[n].name = dupstr(name);
  1786. kc->components[n].is_mp_int = false;
  1787. kc->components[n].text = dupstr(value);
  1788. } // WINSCP
  1789. }
  1790. void key_components_add_mp(key_components *kc,
  1791. const char *name, mp_int *value)
  1792. {
  1793. sgrowarray(kc->components, kc->componentsize, kc->ncomponents);
  1794. { // WINSCP
  1795. size_t n = kc->ncomponents++;
  1796. kc->components[n].name = dupstr(name);
  1797. kc->components[n].is_mp_int = true;
  1798. kc->components[n].mp = mp_copy(value);
  1799. } // WINSCP
  1800. }
  1801. void key_components_free(key_components *kc)
  1802. {
  1803. { // WINSCP
  1804. size_t i;
  1805. for (i = 0; i < kc->ncomponents; i++) {
  1806. sfree(kc->components[i].name);
  1807. if (kc->components[i].is_mp_int) {
  1808. mp_free(kc->components[i].mp);
  1809. } else {
  1810. smemclr(kc->components[i].text, strlen(kc->components[i].text));
  1811. sfree(kc->components[i].text);
  1812. }
  1813. }
  1814. sfree(kc->components);
  1815. sfree(kc);
  1816. } // WINSCP
  1817. }