1
0

sshpubk.c 61 KB

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