sshpubk.c 61 KB

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