sshpubk.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613
  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 <stdlib.h>
  9. #include <assert.h>
  10. #include "putty.h"
  11. #include "mpint.h"
  12. #include "ssh.h"
  13. #include "misc.h"
  14. #define rsa_signature "SSH PRIVATE KEY FILE FORMAT 1.1\n"
  15. #define BASE64_TOINT(x) ( (x)-'A'<26 ? (x)-'A'+0 :\
  16. (x)-'a'<26 ? (x)-'a'+26 :\
  17. (x)-'0'<10 ? (x)-'0'+52 :\
  18. (x)=='+' ? 62 : \
  19. (x)=='/' ? 63 : 0 )
  20. static int key_type_fp(FILE *fp);
  21. static int rsa_ssh1_load_main(FILE * fp, RSAKey *key, bool pub_only,
  22. char **commentptr, const char *passphrase,
  23. const char **error)
  24. {
  25. strbuf *buf;
  26. int ciphertype;
  27. int ret = 0;
  28. ptrlen comment;
  29. BinarySource src[1];
  30. *error = NULL;
  31. /* Slurp the whole file (minus the header) into a buffer. */
  32. buf = strbuf_new();
  33. {
  34. int ch;
  35. while ((ch = fgetc(fp)) != EOF)
  36. put_byte(buf, ch);
  37. }
  38. fclose(fp);
  39. BinarySource_BARE_INIT(src, buf->u, buf->len);
  40. *error = "file format error";
  41. /*
  42. * A zero byte. (The signature includes a terminating NUL, which
  43. * we haven't gone past yet because we read it using fgets which
  44. * stopped after the \n.)
  45. */
  46. if (get_byte(src) != 0)
  47. goto end;
  48. /* One byte giving encryption type, and one reserved uint32. */
  49. ciphertype = get_byte(src);
  50. if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES)
  51. goto end;
  52. if (get_uint32(src) != 0)
  53. goto end; /* reserved field nonzero, panic! */
  54. /* Now the serious stuff. An ordinary SSH-1 public key. */
  55. get_rsa_ssh1_pub(src, key, RSA_SSH1_MODULUS_FIRST);
  56. /* Next, the comment field. */
  57. comment = get_string(src);
  58. if (commentptr)
  59. *commentptr = mkstr(comment);
  60. if (key)
  61. key->comment = mkstr(comment);
  62. if (pub_only) {
  63. ret = 1;
  64. goto end;
  65. }
  66. if (!key) {
  67. ret = ciphertype != 0;
  68. *error = NULL;
  69. goto end;
  70. }
  71. /*
  72. * Decrypt remainder of buffer.
  73. */
  74. if (ciphertype) {
  75. unsigned char keybuf[16];
  76. size_t enclen = buf->len - src->pos;
  77. if (enclen & 7)
  78. goto end;
  79. hash_simple(&ssh_md5, ptrlen_from_asciz(passphrase), keybuf);
  80. des3_decrypt_pubkey(keybuf, buf->u + src->pos, enclen);
  81. smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
  82. }
  83. /*
  84. * We are now in the secret part of the key. The first four
  85. * bytes should be of the form a, b, a, b.
  86. */
  87. {
  88. int b0a = get_byte(src);
  89. int b1a = get_byte(src);
  90. int b0b = get_byte(src);
  91. int b1b = get_byte(src);
  92. if (b0a != b0b || b1a != b1b) {
  93. *error = "wrong passphrase";
  94. ret = -1;
  95. goto end;
  96. }
  97. }
  98. /*
  99. * After that, we have one further bignum which is our
  100. * decryption exponent, and then the three auxiliary values
  101. * (iqmp, q, p).
  102. */
  103. get_rsa_ssh1_priv(src, key);
  104. key->iqmp = get_mp_ssh1(src);
  105. key->q = get_mp_ssh1(src);
  106. key->p = get_mp_ssh1(src);
  107. if (!rsa_verify(key)) {
  108. *error = "rsa_verify failed";
  109. freersakey(key);
  110. ret = 0;
  111. } else
  112. ret = 1;
  113. end:
  114. strbuf_free(buf);
  115. return ret;
  116. }
  117. int rsa_ssh1_loadkey(const Filename *filename, RSAKey *key,
  118. const char *passphrase, const char **errorstr)
  119. {
  120. FILE *fp;
  121. char buf[64];
  122. int ret = 0;
  123. const char *error = NULL;
  124. fp = f_open(filename, "rb", false);
  125. if (!fp) {
  126. error = "can't open file";
  127. goto end;
  128. }
  129. /*
  130. * Read the first line of the file and see if it's a v1 private
  131. * key file.
  132. */
  133. if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
  134. /*
  135. * This routine will take care of calling fclose() for us.
  136. */
  137. ret = rsa_ssh1_load_main(fp, key, false, NULL, passphrase, &error);
  138. fp = NULL;
  139. goto end;
  140. }
  141. /*
  142. * Otherwise, we have nothing. Return empty-handed.
  143. */
  144. error = "not an SSH-1 RSA file";
  145. end:
  146. if (fp)
  147. fclose(fp);
  148. if ((ret != 1) && errorstr)
  149. *errorstr = error;
  150. return ret;
  151. }
  152. /*
  153. * See whether an RSA key is encrypted. Return its comment field as
  154. * well.
  155. */
  156. bool rsa_ssh1_encrypted(const Filename *filename, char **comment)
  157. {
  158. FILE *fp;
  159. char buf[64];
  160. fp = f_open(filename, "rb", false);
  161. if (!fp)
  162. return false; /* doesn't even exist */
  163. /*
  164. * Read the first line of the file and see if it's a v1 private
  165. * key file.
  166. */
  167. if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
  168. const char *dummy;
  169. /*
  170. * This routine will take care of calling fclose() for us.
  171. */
  172. return rsa_ssh1_load_main(fp, NULL, false, comment, NULL, &dummy) == 1;
  173. }
  174. fclose(fp);
  175. return false; /* wasn't the right kind of file */
  176. }
  177. /*
  178. * Read the public part of an SSH-1 RSA key from a file (public or
  179. * private), and generate its public blob in exponent-first order.
  180. */
  181. int rsa_ssh1_loadpub(const Filename *filename, BinarySink *bs,
  182. char **commentptr, const char **errorstr)
  183. {
  184. FILE *fp;
  185. char buf[64];
  186. RSAKey key;
  187. int ret;
  188. const char *error = NULL;
  189. /* Default return if we fail. */
  190. ret = 0;
  191. fp = f_open(filename, "rb", false);
  192. if (!fp) {
  193. error = "can't open file";
  194. goto end;
  195. }
  196. /*
  197. * Read the first line of the file and see if it's a v1 private
  198. * key file.
  199. */
  200. if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
  201. memset(&key, 0, sizeof(key));
  202. if (rsa_ssh1_load_main(fp, &key, true, commentptr, NULL, &error)) {
  203. rsa_ssh1_public_blob(bs, &key, RSA_SSH1_EXPONENT_FIRST);
  204. freersakey(&key);
  205. ret = 1;
  206. }
  207. fp = NULL; /* rsa_ssh1_load_main unconditionally closes fp */
  208. } else {
  209. /*
  210. * Try interpreting the file as an SSH-1 public key.
  211. */
  212. char *line, *p, *bitsp, *expp, *modp, *commentp;
  213. rewind(fp);
  214. line = chomp(fgetline(fp));
  215. p = line;
  216. bitsp = p;
  217. p += strspn(p, "0123456789");
  218. if (*p != ' ')
  219. goto not_public_either;
  220. *p++ = '\0';
  221. expp = p;
  222. p += strspn(p, "0123456789");
  223. if (*p != ' ')
  224. goto not_public_either;
  225. *p++ = '\0';
  226. modp = p;
  227. p += strspn(p, "0123456789");
  228. if (*p) {
  229. if (*p != ' ')
  230. goto not_public_either;
  231. *p++ = '\0';
  232. commentp = p;
  233. } else {
  234. commentp = NULL;
  235. }
  236. memset(&key, 0, sizeof(key));
  237. key.exponent = mp_from_decimal(expp);
  238. key.modulus = mp_from_decimal(modp);
  239. if (atoi(bitsp) != mp_get_nbits(key.modulus)) {
  240. mp_free(key.exponent);
  241. mp_free(key.modulus);
  242. sfree(line);
  243. error = "key bit count does not match in SSH-1 public key file";
  244. goto end;
  245. }
  246. if (commentptr)
  247. *commentptr = commentp ? dupstr(commentp) : NULL;
  248. rsa_ssh1_public_blob(bs, &key, RSA_SSH1_EXPONENT_FIRST);
  249. freersakey(&key);
  250. sfree(line);
  251. fclose(fp);
  252. return 1;
  253. not_public_either:
  254. sfree(line);
  255. error = "not an SSH-1 RSA file";
  256. }
  257. end:
  258. if (fp)
  259. fclose(fp);
  260. if ((ret != 1) && errorstr)
  261. *errorstr = error;
  262. return ret;
  263. }
  264. /*
  265. * Save an RSA key file. Return true on success.
  266. */
  267. bool rsa_ssh1_savekey(const Filename *filename, RSAKey *key,
  268. char *passphrase)
  269. {
  270. strbuf *buf = strbuf_new();
  271. int estart;
  272. FILE *fp;
  273. /*
  274. * The public part of the key.
  275. */
  276. put_data(buf, rsa_signature, sizeof(rsa_signature));
  277. put_byte(buf, passphrase ? SSH_CIPHER_3DES : 0); /* encryption type */
  278. put_uint32(buf, 0); /* reserved */
  279. rsa_ssh1_public_blob(BinarySink_UPCAST(buf), key,
  280. RSA_SSH1_MODULUS_FIRST);
  281. put_stringz(buf, NULLTOEMPTY(key->comment));
  282. /*
  283. * The encrypted portion starts here.
  284. */
  285. estart = buf->len;
  286. /*
  287. * Two bytes, then the same two bytes repeated.
  288. */
  289. {
  290. unsigned char b0 = random_byte();
  291. unsigned char b1 = random_byte();
  292. put_byte(buf, b0);
  293. put_byte(buf, b1);
  294. put_byte(buf, b0);
  295. put_byte(buf, b1);
  296. }
  297. /*
  298. * Four more bignums: the decryption exponent, then iqmp, then
  299. * q, then p.
  300. */
  301. put_mp_ssh1(buf, key->private_exponent);
  302. put_mp_ssh1(buf, key->iqmp);
  303. put_mp_ssh1(buf, key->q);
  304. put_mp_ssh1(buf, key->p);
  305. /*
  306. * Now write zeros until the encrypted portion is a multiple of
  307. * 8 bytes.
  308. */
  309. put_padding(buf, (estart - buf->len) & 7, 0);
  310. /*
  311. * Now encrypt the encrypted portion.
  312. */
  313. if (passphrase) {
  314. unsigned char keybuf[16];
  315. ssh_hash *h = ssh_hash_new(&ssh_md5);
  316. put_data(h, passphrase, strlen(passphrase));
  317. ssh_hash_final(h, keybuf);
  318. des3_encrypt_pubkey(keybuf, buf->u + estart, buf->len - estart);
  319. smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
  320. }
  321. /*
  322. * Done. Write the result to the file.
  323. */
  324. fp = f_open(filename, "wb", true);
  325. if (fp) {
  326. bool ret = (fwrite(buf->u, 1, buf->len, fp) == (size_t) (buf->len));
  327. if (fclose(fp))
  328. ret = false;
  329. return ret;
  330. } else
  331. return false;
  332. }
  333. /* ----------------------------------------------------------------------
  334. * SSH-2 private key load/store functions.
  335. */
  336. /*
  337. * PuTTY's own format for SSH-2 keys is as follows:
  338. *
  339. * The file is text. Lines are terminated by CRLF, although CR-only
  340. * and LF-only are tolerated on input.
  341. *
  342. * The first line says "PuTTY-User-Key-File-2: " plus the name of the
  343. * algorithm ("ssh-dss", "ssh-rsa" etc).
  344. *
  345. * The next line says "Encryption: " plus an encryption type.
  346. * Currently the only supported encryption types are "aes256-cbc"
  347. * and "none".
  348. *
  349. * The next line says "Comment: " plus the comment string.
  350. *
  351. * Next there is a line saying "Public-Lines: " plus a number N.
  352. * The following N lines contain a base64 encoding of the public
  353. * part of the key. This is encoded as the standard SSH-2 public key
  354. * blob (with no initial length): so for RSA, for example, it will
  355. * read
  356. *
  357. * string "ssh-rsa"
  358. * mpint exponent
  359. * mpint modulus
  360. *
  361. * Next, there is a line saying "Private-Lines: " plus a number N,
  362. * and then N lines containing the (potentially encrypted) private
  363. * part of the key. For the key type "ssh-rsa", this will be
  364. * composed of
  365. *
  366. * mpint private_exponent
  367. * mpint p (the larger of the two primes)
  368. * mpint q (the smaller prime)
  369. * mpint iqmp (the inverse of q modulo p)
  370. * data padding (to reach a multiple of the cipher block size)
  371. *
  372. * And for "ssh-dss", it will be composed of
  373. *
  374. * mpint x (the private key parameter)
  375. * [ string hash 20-byte hash of mpints p || q || g only in old format ]
  376. *
  377. * Finally, there is a line saying "Private-MAC: " plus a hex
  378. * representation of a HMAC-SHA-1 of:
  379. *
  380. * string name of algorithm ("ssh-dss", "ssh-rsa")
  381. * string encryption type
  382. * string comment
  383. * string public-blob
  384. * string private-plaintext (the plaintext version of the
  385. * private part, including the final
  386. * padding)
  387. *
  388. * The key to the MAC is itself a SHA-1 hash of:
  389. *
  390. * data "putty-private-key-file-mac-key"
  391. * data passphrase
  392. *
  393. * (An empty passphrase is used for unencrypted keys.)
  394. *
  395. * If the key is encrypted, the encryption key is derived from the
  396. * passphrase by means of a succession of SHA-1 hashes. Each hash
  397. * is the hash of:
  398. *
  399. * uint32 sequence-number
  400. * data passphrase
  401. *
  402. * where the sequence-number increases from zero. As many of these
  403. * hashes are used as necessary.
  404. *
  405. * For backwards compatibility with snapshots between 0.51 and
  406. * 0.52, we also support the older key file format, which begins
  407. * with "PuTTY-User-Key-File-1" (version number differs). In this
  408. * format the Private-MAC: field only covers the private-plaintext
  409. * field and nothing else (and without the 4-byte string length on
  410. * the front too). Moreover, the Private-MAC: field can be replaced
  411. * with a Private-Hash: field which is a plain SHA-1 hash instead of
  412. * an HMAC (this was generated for unencrypted keys).
  413. */
  414. static bool read_header(FILE * fp, char *header)
  415. {
  416. int len = 39;
  417. int c;
  418. while (1) {
  419. c = fgetc(fp);
  420. if (c == '\n' || c == '\r' || c == EOF)
  421. return false; /* failure */
  422. if (c == ':') {
  423. c = fgetc(fp);
  424. if (c != ' ')
  425. return false;
  426. *header = '\0';
  427. return true; /* success! */
  428. }
  429. if (len == 0)
  430. return false; /* failure */
  431. *header++ = c;
  432. len--;
  433. }
  434. return false; /* failure */
  435. }
  436. static char *read_body(FILE * fp)
  437. {
  438. char *text;
  439. int len;
  440. int size;
  441. int c;
  442. size = 128;
  443. text = snewn(size, char);
  444. len = 0;
  445. text[len] = '\0';
  446. while (1) {
  447. c = fgetc(fp);
  448. if (c == '\r' || c == '\n' || c == EOF) {
  449. if (c != EOF) {
  450. c = fgetc(fp);
  451. if (c != '\r' && c != '\n')
  452. ungetc(c, fp);
  453. }
  454. return text;
  455. }
  456. if (len + 1 >= size) {
  457. size += 128;
  458. text = sresize(text, size, char);
  459. }
  460. text[len++] = c;
  461. text[len] = '\0';
  462. }
  463. }
  464. static bool read_blob(FILE *fp, int nlines, BinarySink *bs)
  465. {
  466. unsigned char *blob;
  467. char *line;
  468. int linelen;
  469. int i, j, k;
  470. /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
  471. blob = snewn(48 * nlines, unsigned char);
  472. for (i = 0; i < nlines; i++) {
  473. line = read_body(fp);
  474. if (!line) {
  475. sfree(blob);
  476. return false;
  477. }
  478. linelen = strlen(line);
  479. if (linelen % 4 != 0 || linelen > 64) {
  480. sfree(blob);
  481. sfree(line);
  482. return false;
  483. }
  484. for (j = 0; j < linelen; j += 4) {
  485. unsigned char decoded[3];
  486. k = base64_decode_atom(line + j, decoded);
  487. if (!k) {
  488. sfree(line);
  489. sfree(blob);
  490. return false;
  491. }
  492. put_data(bs, decoded, k);
  493. }
  494. sfree(line);
  495. }
  496. return true;
  497. }
  498. /*
  499. * Magic error return value for when the passphrase is wrong.
  500. */
  501. ssh2_userkey ssh2_wrong_passphrase = { NULL, NULL };
  502. const ssh_keyalg *find_pubkey_alg_len(ptrlen name)
  503. {
  504. if (ptrlen_eq_string(name, "ssh-rsa"))
  505. return &ssh_rsa;
  506. else if (ptrlen_eq_string(name, "ssh-dss"))
  507. return &ssh_dss;
  508. else if (ptrlen_eq_string(name, "ecdsa-sha2-nistp256"))
  509. return &ssh_ecdsa_nistp256;
  510. else if (ptrlen_eq_string(name, "ecdsa-sha2-nistp384"))
  511. return &ssh_ecdsa_nistp384;
  512. else if (ptrlen_eq_string(name, "ecdsa-sha2-nistp521"))
  513. return &ssh_ecdsa_nistp521;
  514. else if (ptrlen_eq_string(name, "ssh-ed25519"))
  515. return &ssh_ecdsa_ed25519;
  516. else
  517. return NULL;
  518. }
  519. const ssh_keyalg *find_pubkey_alg(const char *name)
  520. {
  521. return find_pubkey_alg_len(ptrlen_from_asciz(name));
  522. }
  523. static void ssh2_ppk_derivekey(ptrlen passphrase, uint8_t *key)
  524. {
  525. ssh_hash *h;
  526. h = ssh_hash_new(&ssh_sha1);
  527. put_uint32(h, 0);
  528. put_datapl(h, passphrase);
  529. ssh_hash_final(h, key + 0);
  530. h = ssh_hash_new(&ssh_sha1);
  531. put_uint32(h, 1);
  532. put_datapl(h, passphrase);
  533. ssh_hash_final(h, key + 20);
  534. }
  535. ssh2_userkey *ssh2_load_userkey(
  536. const Filename *filename, const char *passphrase, const char **errorstr)
  537. {
  538. FILE *fp;
  539. char header[40], *b, *encryption, *comment, *mac;
  540. const ssh_keyalg *alg;
  541. ssh2_userkey *ret;
  542. int cipher, cipherblk;
  543. strbuf *public_blob, *private_blob;
  544. int i;
  545. bool is_mac, old_fmt;
  546. int passlen = passphrase ? strlen(passphrase) : 0;
  547. const char *error = NULL;
  548. ret = NULL; /* return NULL for most errors */
  549. encryption = comment = mac = NULL;
  550. public_blob = private_blob = NULL;
  551. fp = f_open(filename, "rb", false);
  552. if (!fp) {
  553. error = "can't open file";
  554. goto error;
  555. }
  556. /* Read the first header line which contains the key type. */
  557. if (!read_header(fp, header)) {
  558. error = "no header line found in key file";
  559. goto error;
  560. }
  561. if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {
  562. old_fmt = false;
  563. } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {
  564. /* this is an old key file; warn and then continue */
  565. old_keyfile_warning();
  566. old_fmt = true;
  567. } else if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) {
  568. /* this is a key file FROM THE FUTURE; refuse it, but with a
  569. * more specific error message than the generic one below */
  570. error = "PuTTY key format too new";
  571. goto error;
  572. } else {
  573. error = "not a PuTTY SSH-2 private key";
  574. goto error;
  575. }
  576. error = "file format error";
  577. if ((b = read_body(fp)) == NULL)
  578. goto error;
  579. /* Select key algorithm structure. */
  580. alg = find_pubkey_alg(b);
  581. if (!alg) {
  582. sfree(b);
  583. goto error;
  584. }
  585. sfree(b);
  586. /* Read the Encryption header line. */
  587. if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
  588. goto error;
  589. if ((encryption = read_body(fp)) == NULL)
  590. goto error;
  591. if (!strcmp(encryption, "aes256-cbc")) {
  592. cipher = 1;
  593. cipherblk = 16;
  594. } else if (!strcmp(encryption, "none")) {
  595. cipher = 0;
  596. cipherblk = 1;
  597. } else {
  598. goto error;
  599. }
  600. /* Read the Comment header line. */
  601. if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
  602. goto error;
  603. if ((comment = read_body(fp)) == NULL)
  604. goto error;
  605. /* Read the Public-Lines header line and the public blob. */
  606. if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
  607. goto error;
  608. if ((b = read_body(fp)) == NULL)
  609. goto error;
  610. i = atoi(b);
  611. sfree(b);
  612. public_blob = strbuf_new();
  613. if (!read_blob(fp, i, BinarySink_UPCAST(public_blob)))
  614. goto error;
  615. /* Read the Private-Lines header line and the Private blob. */
  616. if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))
  617. goto error;
  618. if ((b = read_body(fp)) == NULL)
  619. goto error;
  620. i = atoi(b);
  621. sfree(b);
  622. private_blob = strbuf_new();
  623. if (!read_blob(fp, i, BinarySink_UPCAST(private_blob)))
  624. goto error;
  625. /* Read the Private-MAC or Private-Hash header line. */
  626. if (!read_header(fp, header))
  627. goto error;
  628. if (0 == strcmp(header, "Private-MAC")) {
  629. if ((mac = read_body(fp)) == NULL)
  630. goto error;
  631. is_mac = true;
  632. } else if (0 == strcmp(header, "Private-Hash") && old_fmt) {
  633. if ((mac = read_body(fp)) == NULL)
  634. goto error;
  635. is_mac = false;
  636. } else
  637. goto error;
  638. fclose(fp);
  639. fp = NULL;
  640. /*
  641. * Decrypt the private blob.
  642. */
  643. if (cipher) {
  644. unsigned char key[40];
  645. if (!passphrase)
  646. goto error;
  647. if (private_blob->len % cipherblk)
  648. goto error;
  649. ssh2_ppk_derivekey(ptrlen_from_asciz(passphrase), key);
  650. aes256_decrypt_pubkey(key, private_blob->u, private_blob->len);
  651. }
  652. /*
  653. * Verify the MAC.
  654. */
  655. {
  656. char realmac[41];
  657. unsigned char binary[20];
  658. strbuf *macdata;
  659. bool free_macdata;
  660. if (old_fmt) {
  661. /* MAC (or hash) only covers the private blob. */
  662. macdata = private_blob;
  663. free_macdata = false;
  664. } else {
  665. macdata = strbuf_new();
  666. put_stringz(macdata, alg->ssh_id);
  667. put_stringz(macdata, encryption);
  668. put_stringz(macdata, comment);
  669. put_string(macdata, public_blob->s,
  670. public_blob->len);
  671. put_string(macdata, private_blob->s,
  672. private_blob->len);
  673. free_macdata = true;
  674. }
  675. if (is_mac) {
  676. ssh_hash *hash;
  677. ssh2_mac *mac;
  678. unsigned char mackey[20];
  679. char header[] = "putty-private-key-file-mac-key";
  680. hash = ssh_hash_new(&ssh_sha1);
  681. put_data(hash, header, sizeof(header)-1);
  682. if (cipher && passphrase)
  683. put_data(hash, passphrase, passlen);
  684. ssh_hash_final(hash, mackey);
  685. mac = ssh2_mac_new(&ssh_hmac_sha1, NULL);
  686. ssh2_mac_setkey(mac, make_ptrlen(mackey, 20));
  687. ssh2_mac_start(mac);
  688. put_data(mac, macdata->s, macdata->len);
  689. ssh2_mac_genresult(mac, binary);
  690. ssh2_mac_free(mac);
  691. smemclr(mackey, sizeof(mackey));
  692. } else {
  693. hash_simple(&ssh_sha1, ptrlen_from_strbuf(macdata), binary);
  694. }
  695. if (free_macdata)
  696. strbuf_free(macdata);
  697. for (i = 0; i < 20; i++)
  698. sprintf(realmac + 2 * i, "%02x", binary[i]);
  699. if (strcmp(mac, realmac)) {
  700. /* An incorrect MAC is an unconditional Error if the key is
  701. * unencrypted. Otherwise, it means Wrong Passphrase. */
  702. if (cipher) {
  703. error = "wrong passphrase";
  704. ret = SSH2_WRONG_PASSPHRASE;
  705. } else {
  706. error = "MAC failed";
  707. ret = NULL;
  708. }
  709. goto error;
  710. }
  711. }
  712. sfree(mac);
  713. mac = NULL;
  714. /*
  715. * Create and return the key.
  716. */
  717. ret = snew(ssh2_userkey);
  718. ret->comment = comment;
  719. ret->key = ssh_key_new_priv(
  720. alg, ptrlen_from_strbuf(public_blob),
  721. ptrlen_from_strbuf(private_blob));
  722. if (!ret->key) {
  723. sfree(ret);
  724. ret = NULL;
  725. error = "createkey failed";
  726. goto error;
  727. }
  728. strbuf_free(public_blob);
  729. strbuf_free(private_blob);
  730. sfree(encryption);
  731. if (errorstr)
  732. *errorstr = NULL;
  733. return ret;
  734. /*
  735. * Error processing.
  736. */
  737. error:
  738. if (fp)
  739. fclose(fp);
  740. if (comment)
  741. sfree(comment);
  742. if (encryption)
  743. sfree(encryption);
  744. if (mac)
  745. sfree(mac);
  746. if (public_blob)
  747. strbuf_free(public_blob);
  748. if (private_blob)
  749. strbuf_free(private_blob);
  750. if (errorstr)
  751. *errorstr = error;
  752. return ret;
  753. }
  754. bool rfc4716_loadpub(FILE *fp, char **algorithm,
  755. BinarySink *bs,
  756. char **commentptr, const char **errorstr)
  757. {
  758. const char *error;
  759. char *line, *colon, *value;
  760. char *comment = NULL;
  761. unsigned char *pubblob = NULL;
  762. int pubbloblen, pubblobsize;
  763. char base64in[4];
  764. unsigned char base64out[3];
  765. int base64bytes;
  766. int alglen;
  767. line = chomp(fgetline(fp));
  768. if (!line || 0 != strcmp(line, "---- BEGIN SSH2 PUBLIC KEY ----")) {
  769. error = "invalid begin line in SSH-2 public key file";
  770. goto error;
  771. }
  772. sfree(line); line = NULL;
  773. while (1) {
  774. line = chomp(fgetline(fp));
  775. if (!line) {
  776. error = "truncated SSH-2 public key file";
  777. goto error;
  778. }
  779. colon = strstr(line, ": ");
  780. if (!colon)
  781. break;
  782. *colon = '\0';
  783. value = colon + 2;
  784. if (!strcmp(line, "Comment")) {
  785. char *p, *q;
  786. /* Remove containing double quotes, if present */
  787. p = value;
  788. if (*p == '"' && p[strlen(p)-1] == '"') {
  789. p[strlen(p)-1] = '\0';
  790. p++;
  791. }
  792. /* Remove \-escaping, not in RFC4716 but seen in the wild
  793. * in practice. */
  794. for (q = line; *p; p++) {
  795. if (*p == '\\' && p[1])
  796. p++;
  797. *q++ = *p;
  798. }
  799. *q = '\0';
  800. sfree(comment); /* *just* in case of multiple Comment headers */
  801. comment = dupstr(line);
  802. } else if (!strcmp(line, "Subject") ||
  803. !strncmp(line, "x-", 2)) {
  804. /* Headers we recognise and ignore. Do nothing. */
  805. } else {
  806. error = "unrecognised header in SSH-2 public key file";
  807. goto error;
  808. }
  809. sfree(line); line = NULL;
  810. }
  811. /*
  812. * Now line contains the initial line of base64 data. Loop round
  813. * while it still does contain base64.
  814. */
  815. pubblobsize = 4096;
  816. pubblob = snewn(pubblobsize, unsigned char);
  817. pubbloblen = 0;
  818. base64bytes = 0;
  819. while (line && line[0] != '-') {
  820. char *p;
  821. for (p = line; *p; p++) {
  822. base64in[base64bytes++] = *p;
  823. if (base64bytes == 4) {
  824. int n = base64_decode_atom(base64in, base64out);
  825. if (pubbloblen + n > pubblobsize) {
  826. pubblobsize = (pubbloblen + n) * 5 / 4 + 1024;
  827. pubblob = sresize(pubblob, pubblobsize, unsigned char);
  828. }
  829. memcpy(pubblob + pubbloblen, base64out, n);
  830. pubbloblen += n;
  831. base64bytes = 0;
  832. }
  833. }
  834. sfree(line); line = NULL;
  835. line = chomp(fgetline(fp));
  836. }
  837. /*
  838. * Finally, check the END line makes sense.
  839. */
  840. if (!line || 0 != strcmp(line, "---- END SSH2 PUBLIC KEY ----")) {
  841. error = "invalid end line in SSH-2 public key file";
  842. goto error;
  843. }
  844. sfree(line); line = NULL;
  845. /*
  846. * OK, we now have a public blob and optionally a comment. We must
  847. * return the key algorithm string too, so look for that at the
  848. * start of the public blob.
  849. */
  850. if (pubbloblen < 4) {
  851. error = "not enough data in SSH-2 public key file";
  852. goto error;
  853. }
  854. alglen = toint(GET_32BIT(pubblob));
  855. if (alglen < 0 || alglen > pubbloblen-4) {
  856. error = "invalid algorithm prefix in SSH-2 public key file";
  857. goto error;
  858. }
  859. if (algorithm)
  860. *algorithm = dupprintf("%.*s", alglen, pubblob+4);
  861. if (commentptr)
  862. *commentptr = comment;
  863. else
  864. sfree(comment);
  865. put_data(bs, pubblob, pubbloblen);
  866. sfree(pubblob);
  867. return true;
  868. error:
  869. sfree(line);
  870. sfree(comment);
  871. sfree(pubblob);
  872. if (errorstr)
  873. *errorstr = error;
  874. return false;
  875. }
  876. bool openssh_loadpub(FILE *fp, char **algorithm,
  877. BinarySink *bs,
  878. char **commentptr, const char **errorstr)
  879. {
  880. const char *error;
  881. char *line, *base64;
  882. char *comment = NULL;
  883. unsigned char *pubblob = NULL;
  884. int pubbloblen, pubblobsize;
  885. int alglen;
  886. line = chomp(fgetline(fp));
  887. base64 = strchr(line, ' ');
  888. if (!base64) {
  889. error = "no key blob in OpenSSH public key file";
  890. goto error;
  891. }
  892. *base64++ = '\0';
  893. comment = strchr(base64, ' ');
  894. if (comment) {
  895. *comment++ = '\0';
  896. comment = dupstr(comment);
  897. }
  898. pubblobsize = strlen(base64) / 4 * 3;
  899. pubblob = snewn(pubblobsize, unsigned char);
  900. pubbloblen = 0;
  901. while (!memchr(base64, '\0', 4)) {
  902. assert(pubbloblen + 3 <= pubblobsize);
  903. pubbloblen += base64_decode_atom(base64, pubblob + pubbloblen);
  904. base64 += 4;
  905. }
  906. if (*base64) {
  907. error = "invalid length for base64 data in OpenSSH public key file";
  908. goto error;
  909. }
  910. /*
  911. * Sanity check: the first word on the line should be the key
  912. * algorithm, and should match the encoded string at the start of
  913. * the public blob.
  914. */
  915. alglen = strlen(line);
  916. if (pubbloblen < alglen + 4 ||
  917. GET_32BIT(pubblob) != alglen ||
  918. 0 != memcmp(pubblob + 4, line, alglen)) {
  919. error = "key algorithms do not match in OpenSSH public key file";
  920. goto error;
  921. }
  922. /*
  923. * Done.
  924. */
  925. if (algorithm)
  926. *algorithm = dupstr(line);
  927. if (commentptr)
  928. *commentptr = comment;
  929. else
  930. sfree(comment);
  931. sfree(line);
  932. put_data(bs, pubblob, pubbloblen);
  933. sfree(pubblob);
  934. return true;
  935. error:
  936. sfree(line);
  937. sfree(comment);
  938. sfree(pubblob);
  939. if (errorstr)
  940. *errorstr = error;
  941. return false;
  942. }
  943. bool ssh2_userkey_loadpub(const Filename *filename, char **algorithm,
  944. BinarySink *bs,
  945. char **commentptr, const char **errorstr)
  946. {
  947. FILE *fp;
  948. char header[40], *b;
  949. const ssh_keyalg *alg;
  950. int type, i;
  951. const char *error = NULL;
  952. char *comment = NULL;
  953. fp = f_open(filename, "rb", false);
  954. if (!fp) {
  955. error = "can't open file";
  956. goto error;
  957. }
  958. /* Initially, check if this is a public-only key file. Sometimes
  959. * we'll be asked to read a public blob from one of those. */
  960. type = key_type_fp(fp);
  961. if (type == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {
  962. bool ret = rfc4716_loadpub(fp, algorithm, bs, commentptr, errorstr);
  963. fclose(fp);
  964. return ret;
  965. } else if (type == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  966. bool ret = openssh_loadpub(fp, algorithm, bs, commentptr, errorstr);
  967. fclose(fp);
  968. return ret;
  969. } else if (type != SSH_KEYTYPE_SSH2) {
  970. error = "not a PuTTY SSH-2 private key";
  971. goto error;
  972. }
  973. /* Read the first header line which contains the key type. */
  974. if (!read_header(fp, header)
  975. || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
  976. 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
  977. if (0 == strncmp(header, "PuTTY-User-Key-File-", 20))
  978. error = "PuTTY key format too new";
  979. else
  980. error = "not a PuTTY SSH-2 private key";
  981. goto error;
  982. }
  983. error = "file format error";
  984. if ((b = read_body(fp)) == NULL)
  985. goto error;
  986. /* Select key algorithm structure. */
  987. alg = find_pubkey_alg(b);
  988. sfree(b);
  989. if (!alg) {
  990. goto error;
  991. }
  992. /* Read the Encryption header line. */
  993. if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
  994. goto error;
  995. if ((b = read_body(fp)) == NULL)
  996. goto error;
  997. sfree(b); /* we don't care */
  998. /* Read the Comment header line. */
  999. if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
  1000. goto error;
  1001. if ((comment = read_body(fp)) == NULL)
  1002. goto error;
  1003. if (commentptr)
  1004. *commentptr = comment;
  1005. else
  1006. sfree(comment);
  1007. /* Read the Public-Lines header line and the public blob. */
  1008. if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
  1009. goto error;
  1010. if ((b = read_body(fp)) == NULL)
  1011. goto error;
  1012. i = atoi(b);
  1013. sfree(b);
  1014. if (!read_blob(fp, i, bs))
  1015. goto error;
  1016. fclose(fp);
  1017. if (algorithm)
  1018. *algorithm = dupstr(alg->ssh_id);
  1019. return true;
  1020. /*
  1021. * Error processing.
  1022. */
  1023. error:
  1024. if (fp)
  1025. fclose(fp);
  1026. if (errorstr)
  1027. *errorstr = error;
  1028. if (comment && commentptr) {
  1029. sfree(comment);
  1030. *commentptr = NULL;
  1031. }
  1032. return false;
  1033. }
  1034. bool ssh2_userkey_encrypted(const Filename *filename, char **commentptr)
  1035. {
  1036. FILE *fp;
  1037. char header[40], *b, *comment;
  1038. bool ret;
  1039. if (commentptr)
  1040. *commentptr = NULL;
  1041. fp = f_open(filename, "rb", false);
  1042. if (!fp)
  1043. return false;
  1044. if (!read_header(fp, header)
  1045. || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
  1046. 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
  1047. fclose(fp);
  1048. return false;
  1049. }
  1050. if ((b = read_body(fp)) == NULL) {
  1051. fclose(fp);
  1052. return false;
  1053. }
  1054. sfree(b); /* we don't care about key type here */
  1055. /* Read the Encryption header line. */
  1056. if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
  1057. fclose(fp);
  1058. return false;
  1059. }
  1060. if ((b = read_body(fp)) == NULL) {
  1061. fclose(fp);
  1062. return false;
  1063. }
  1064. /* Read the Comment header line. */
  1065. if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
  1066. fclose(fp);
  1067. sfree(b);
  1068. return true;
  1069. }
  1070. if ((comment = read_body(fp)) == NULL) {
  1071. fclose(fp);
  1072. sfree(b);
  1073. return true;
  1074. }
  1075. if (commentptr)
  1076. *commentptr = comment;
  1077. else
  1078. sfree(comment);
  1079. fclose(fp);
  1080. if (!strcmp(b, "aes256-cbc"))
  1081. ret = true;
  1082. else
  1083. ret = false;
  1084. sfree(b);
  1085. return ret;
  1086. }
  1087. int base64_lines(int datalen)
  1088. {
  1089. /* When encoding, we use 64 chars/line, which equals 48 real chars. */
  1090. return (datalen + 47) / 48;
  1091. }
  1092. void base64_encode(FILE *fp, const unsigned char *data, int datalen, int cpl)
  1093. {
  1094. int linelen = 0;
  1095. char out[4];
  1096. int n, i;
  1097. while (datalen > 0) {
  1098. n = (datalen < 3 ? datalen : 3);
  1099. base64_encode_atom(data, n, out);
  1100. data += n;
  1101. datalen -= n;
  1102. for (i = 0; i < 4; i++) {
  1103. if (linelen >= cpl) {
  1104. linelen = 0;
  1105. fputc('\n', fp);
  1106. }
  1107. fputc(out[i], fp);
  1108. linelen++;
  1109. }
  1110. }
  1111. fputc('\n', fp);
  1112. }
  1113. bool ssh2_save_userkey(
  1114. const Filename *filename, ssh2_userkey *key, char *passphrase)
  1115. {
  1116. FILE *fp;
  1117. strbuf *pub_blob, *priv_blob;
  1118. unsigned char *priv_blob_encrypted;
  1119. int priv_encrypted_len;
  1120. int cipherblk;
  1121. int i;
  1122. const char *cipherstr;
  1123. unsigned char priv_mac[20];
  1124. /*
  1125. * Fetch the key component blobs.
  1126. */
  1127. pub_blob = strbuf_new();
  1128. ssh_key_public_blob(key->key, BinarySink_UPCAST(pub_blob));
  1129. priv_blob = strbuf_new();
  1130. ssh_key_private_blob(key->key, BinarySink_UPCAST(priv_blob));
  1131. /*
  1132. * Determine encryption details, and encrypt the private blob.
  1133. */
  1134. if (passphrase) {
  1135. cipherstr = "aes256-cbc";
  1136. cipherblk = 16;
  1137. } else {
  1138. cipherstr = "none";
  1139. cipherblk = 1;
  1140. }
  1141. priv_encrypted_len = priv_blob->len + cipherblk - 1;
  1142. priv_encrypted_len -= priv_encrypted_len % cipherblk;
  1143. priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);
  1144. memset(priv_blob_encrypted, 0, priv_encrypted_len);
  1145. memcpy(priv_blob_encrypted, priv_blob->u, priv_blob->len);
  1146. /* Create padding based on the SHA hash of the unpadded blob. This prevents
  1147. * too easy a known-plaintext attack on the last block. */
  1148. hash_simple(&ssh_sha1, ptrlen_from_strbuf(priv_blob), priv_mac);
  1149. assert(priv_encrypted_len - priv_blob->len < 20);
  1150. memcpy(priv_blob_encrypted + priv_blob->len, priv_mac,
  1151. priv_encrypted_len - priv_blob->len);
  1152. /* Now create the MAC. */
  1153. {
  1154. strbuf *macdata;
  1155. unsigned char mackey[20];
  1156. char header[] = "putty-private-key-file-mac-key";
  1157. macdata = strbuf_new();
  1158. put_stringz(macdata, ssh_key_ssh_id(key->key));
  1159. put_stringz(macdata, cipherstr);
  1160. put_stringz(macdata, key->comment);
  1161. put_string(macdata, pub_blob->s, pub_blob->len);
  1162. put_string(macdata, priv_blob_encrypted, priv_encrypted_len);
  1163. ssh_hash *h = ssh_hash_new(&ssh_sha1);
  1164. put_data(h, header, sizeof(header)-1);
  1165. if (passphrase)
  1166. put_data(h, passphrase, strlen(passphrase));
  1167. ssh_hash_final(h, mackey);
  1168. mac_simple(&ssh_hmac_sha1, make_ptrlen(mackey, 20),
  1169. ptrlen_from_strbuf(macdata), priv_mac);
  1170. strbuf_free(macdata);
  1171. smemclr(mackey, sizeof(mackey));
  1172. }
  1173. if (passphrase) {
  1174. unsigned char key[40];
  1175. ssh2_ppk_derivekey(ptrlen_from_asciz(passphrase), key);
  1176. aes256_encrypt_pubkey(key, priv_blob_encrypted, priv_encrypted_len);
  1177. smemclr(key, sizeof(key));
  1178. }
  1179. fp = f_open(filename, "w", true);
  1180. if (!fp) {
  1181. strbuf_free(pub_blob);
  1182. strbuf_free(priv_blob);
  1183. smemclr(priv_blob_encrypted, priv_encrypted_len);
  1184. sfree(priv_blob_encrypted);
  1185. return false;
  1186. }
  1187. fprintf(fp, "PuTTY-User-Key-File-2: %s\n", ssh_key_ssh_id(key->key));
  1188. fprintf(fp, "Encryption: %s\n", cipherstr);
  1189. fprintf(fp, "Comment: %s\n", key->comment);
  1190. fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob->len));
  1191. base64_encode(fp, pub_blob->u, pub_blob->len, 64);
  1192. fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
  1193. base64_encode(fp, priv_blob_encrypted, priv_encrypted_len, 64);
  1194. fprintf(fp, "Private-MAC: ");
  1195. for (i = 0; i < 20; i++)
  1196. fprintf(fp, "%02x", priv_mac[i]);
  1197. fprintf(fp, "\n");
  1198. fclose(fp);
  1199. strbuf_free(pub_blob);
  1200. strbuf_free(priv_blob);
  1201. smemclr(priv_blob_encrypted, priv_encrypted_len);
  1202. sfree(priv_blob_encrypted);
  1203. return true;
  1204. }
  1205. /* ----------------------------------------------------------------------
  1206. * Output public keys.
  1207. */
  1208. char *ssh1_pubkey_str(RSAKey *key)
  1209. {
  1210. char *buffer;
  1211. char *dec1, *dec2;
  1212. dec1 = mp_get_decimal(key->exponent);
  1213. dec2 = mp_get_decimal(key->modulus);
  1214. buffer = dupprintf("%zd %s %s%s%s", mp_get_nbits(key->modulus), dec1, dec2,
  1215. key->comment ? " " : "",
  1216. key->comment ? key->comment : "");
  1217. sfree(dec1);
  1218. sfree(dec2);
  1219. return buffer;
  1220. }
  1221. void ssh1_write_pubkey(FILE *fp, RSAKey *key)
  1222. {
  1223. char *buffer = ssh1_pubkey_str(key);
  1224. fprintf(fp, "%s\n", buffer);
  1225. sfree(buffer);
  1226. }
  1227. static char *ssh2_pubkey_openssh_str_internal(const char *comment,
  1228. const void *v_pub_blob,
  1229. int pub_len)
  1230. {
  1231. const unsigned char *ssh2blob = (const unsigned char *)v_pub_blob;
  1232. ptrlen alg;
  1233. char *buffer, *p;
  1234. int i;
  1235. {
  1236. BinarySource src[1];
  1237. BinarySource_BARE_INIT(src, ssh2blob, pub_len);
  1238. alg = get_string(src);
  1239. if (get_err(src)) {
  1240. const char *replacement_str = "INVALID-ALGORITHM";
  1241. alg.ptr = replacement_str;
  1242. alg.len = strlen(replacement_str);
  1243. }
  1244. }
  1245. buffer = snewn(alg.len +
  1246. 4 * ((pub_len+2) / 3) +
  1247. (comment ? strlen(comment) : 0) + 3, char);
  1248. p = buffer + sprintf(buffer, "%.*s ", PTRLEN_PRINTF(alg));
  1249. i = 0;
  1250. while (i < pub_len) {
  1251. int n = (pub_len - i < 3 ? pub_len - i : 3);
  1252. base64_encode_atom(ssh2blob + i, n, p);
  1253. i += n;
  1254. p += 4;
  1255. }
  1256. if (comment) {
  1257. *p++ = ' ';
  1258. strcpy(p, comment);
  1259. } else
  1260. *p++ = '\0';
  1261. return buffer;
  1262. }
  1263. char *ssh2_pubkey_openssh_str(ssh2_userkey *key)
  1264. {
  1265. strbuf *blob;
  1266. char *ret;
  1267. blob = strbuf_new();
  1268. ssh_key_public_blob(key->key, BinarySink_UPCAST(blob));
  1269. ret = ssh2_pubkey_openssh_str_internal(
  1270. key->comment, blob->s, blob->len);
  1271. strbuf_free(blob);
  1272. return ret;
  1273. }
  1274. void ssh2_write_pubkey(FILE *fp, const char *comment,
  1275. const void *v_pub_blob, int pub_len,
  1276. int keytype)
  1277. {
  1278. unsigned char *pub_blob = (unsigned char *)v_pub_blob;
  1279. if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {
  1280. const char *p;
  1281. int i, column;
  1282. fprintf(fp, "---- BEGIN SSH2 PUBLIC KEY ----\n");
  1283. if (comment) {
  1284. fprintf(fp, "Comment: \"");
  1285. for (p = comment; *p; p++) {
  1286. if (*p == '\\' || *p == '\"')
  1287. fputc('\\', fp);
  1288. fputc(*p, fp);
  1289. }
  1290. fprintf(fp, "\"\n");
  1291. }
  1292. i = 0;
  1293. column = 0;
  1294. while (i < pub_len) {
  1295. char buf[5];
  1296. int n = (pub_len - i < 3 ? pub_len - i : 3);
  1297. base64_encode_atom(pub_blob + i, n, buf);
  1298. i += n;
  1299. buf[4] = '\0';
  1300. fputs(buf, fp);
  1301. if (++column >= 16) {
  1302. fputc('\n', fp);
  1303. column = 0;
  1304. }
  1305. }
  1306. if (column > 0)
  1307. fputc('\n', fp);
  1308. fprintf(fp, "---- END SSH2 PUBLIC KEY ----\n");
  1309. } else if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  1310. char *buffer = ssh2_pubkey_openssh_str_internal(comment,
  1311. v_pub_blob, pub_len);
  1312. fprintf(fp, "%s\n", buffer);
  1313. sfree(buffer);
  1314. } else {
  1315. unreachable("Bad key type in ssh2_write_pubkey");
  1316. }
  1317. }
  1318. /* ----------------------------------------------------------------------
  1319. * Utility functions to compute SSH-2 fingerprints in a uniform way.
  1320. */
  1321. char *ssh2_fingerprint_blob(const void *blob, int bloblen)
  1322. {
  1323. unsigned char digest[16];
  1324. char fingerprint_str[16*3];
  1325. ptrlen algname;
  1326. const ssh_keyalg *alg;
  1327. int i;
  1328. BinarySource src[1];
  1329. /*
  1330. * The fingerprint hash itself is always just the MD5 of the blob.
  1331. */
  1332. hash_simple(&ssh_md5, make_ptrlen(blob, bloblen), digest);
  1333. for (i = 0; i < 16; i++)
  1334. sprintf(fingerprint_str + i*3, "%02x%s", digest[i], i==15 ? "" : ":");
  1335. /*
  1336. * Identify the key algorithm, if possible.
  1337. */
  1338. BinarySource_BARE_INIT(src, blob, bloblen);
  1339. algname = get_string(src);
  1340. if (!get_err(src)) {
  1341. alg = find_pubkey_alg_len(algname);
  1342. if (alg) {
  1343. int bits = ssh_key_public_bits(alg, make_ptrlen(blob, bloblen));
  1344. return dupprintf("%.*s %d %s", PTRLEN_PRINTF(algname),
  1345. bits, fingerprint_str);
  1346. } else {
  1347. return dupprintf("%.*s %s", PTRLEN_PRINTF(algname),
  1348. fingerprint_str);
  1349. }
  1350. } else {
  1351. /*
  1352. * No algorithm available (which means a seriously confused
  1353. * key blob, but there we go). Return only the hash.
  1354. */
  1355. return dupstr(fingerprint_str);
  1356. }
  1357. }
  1358. char *ssh2_fingerprint(ssh_key *data)
  1359. {
  1360. strbuf *blob = strbuf_new();
  1361. ssh_key_public_blob(data, BinarySink_UPCAST(blob));
  1362. char *ret = ssh2_fingerprint_blob(blob->s, blob->len);
  1363. strbuf_free(blob);
  1364. return ret;
  1365. }
  1366. /* ----------------------------------------------------------------------
  1367. * Determine the type of a private key file.
  1368. */
  1369. static int key_type_fp(FILE *fp)
  1370. {
  1371. char buf[1024];
  1372. const char public_std_sig[] = "---- BEGIN SSH2 PUBLIC KEY";
  1373. const char putty2_sig[] = "PuTTY-User-Key-File-";
  1374. const char sshcom_sig[] = "---- BEGIN SSH2 ENCRYPTED PRIVAT";
  1375. const char openssh_new_sig[] = "-----BEGIN OPENSSH PRIVATE KEY";
  1376. const char openssh_sig[] = "-----BEGIN ";
  1377. int i;
  1378. char *p;
  1379. i = fread(buf, 1, sizeof(buf)-1, fp);
  1380. rewind(fp);
  1381. if (i < 0)
  1382. return SSH_KEYTYPE_UNOPENABLE;
  1383. if (i < 32)
  1384. return SSH_KEYTYPE_UNKNOWN;
  1385. assert(i > 0 && i < sizeof(buf));
  1386. buf[i] = '\0';
  1387. if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1))
  1388. return SSH_KEYTYPE_SSH1;
  1389. if (!memcmp(buf, public_std_sig, sizeof(public_std_sig)-1))
  1390. return SSH_KEYTYPE_SSH2_PUBLIC_RFC4716;
  1391. if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1))
  1392. return SSH_KEYTYPE_SSH2;
  1393. if (!memcmp(buf, openssh_new_sig, sizeof(openssh_new_sig)-1))
  1394. return SSH_KEYTYPE_OPENSSH_NEW;
  1395. if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1))
  1396. return SSH_KEYTYPE_OPENSSH_PEM;
  1397. if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1))
  1398. return SSH_KEYTYPE_SSHCOM;
  1399. if ((p = buf + strspn(buf, "0123456789"), *p == ' ') &&
  1400. (p = p+1 + strspn(p+1, "0123456789"), *p == ' ') &&
  1401. (p = p+1 + strspn(p+1, "0123456789"), *p == ' ' || *p == '\n' || !*p))
  1402. return SSH_KEYTYPE_SSH1_PUBLIC;
  1403. if ((p = buf + strcspn(buf, " "),
  1404. find_pubkey_alg_len(make_ptrlen(buf, p-buf))) &&
  1405. (p = p+1 + strspn(p+1, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij"
  1406. "klmnopqrstuvwxyz+/="),
  1407. *p == ' ' || *p == '\n' || !*p))
  1408. return SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH;
  1409. return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */
  1410. }
  1411. int key_type(const Filename *filename)
  1412. {
  1413. FILE *fp;
  1414. int ret;
  1415. fp = f_open(filename, "r", false);
  1416. if (!fp)
  1417. return SSH_KEYTYPE_UNOPENABLE;
  1418. ret = key_type_fp(fp);
  1419. fclose(fp);
  1420. return ret;
  1421. }
  1422. /*
  1423. * Convert the type word to a string, for `wrong type' error
  1424. * messages.
  1425. */
  1426. const char *key_type_to_str(int type)
  1427. {
  1428. switch (type) {
  1429. case SSH_KEYTYPE_UNOPENABLE: return "unable to open file"; break;
  1430. case SSH_KEYTYPE_UNKNOWN: return "not a recognised key file format"; break;
  1431. case SSH_KEYTYPE_SSH1_PUBLIC: return "SSH-1 public key"; break;
  1432. case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716: return "SSH-2 public key (RFC 4716 format)"; break;
  1433. case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH: return "SSH-2 public key (OpenSSH format)"; break;
  1434. case SSH_KEYTYPE_SSH1: return "SSH-1 private key"; break;
  1435. case SSH_KEYTYPE_SSH2: return "PuTTY SSH-2 private key"; break;
  1436. case SSH_KEYTYPE_OPENSSH_PEM: return "OpenSSH SSH-2 private key (old PEM format)"; break;
  1437. case SSH_KEYTYPE_OPENSSH_NEW: return "OpenSSH SSH-2 private key (new format)"; break;
  1438. case SSH_KEYTYPE_SSHCOM: return "ssh.com SSH-2 private key"; break;
  1439. /*
  1440. * This function is called with a key type derived from
  1441. * looking at an actual key file, so the output-only type
  1442. * OPENSSH_AUTO should never get here, and is much an INTERNAL
  1443. * ERROR as a code we don't even understand.
  1444. */
  1445. case SSH_KEYTYPE_OPENSSH_AUTO: return "INTERNAL ERROR (OPENSSH_AUTO)"; break;
  1446. default: return "INTERNAL ERROR"; break;
  1447. }
  1448. }