sshpubk.c 61 KB

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