sshpubk.c 59 KB

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