sshpubk.c 57 KB

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