uxpgnt.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. /*
  2. * Unix Pageant, more or less similar to ssh-agent.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <errno.h>
  7. #include <assert.h>
  8. #include <signal.h>
  9. #include <ctype.h>
  10. #include <sys/types.h>
  11. #include <sys/wait.h>
  12. #include <fcntl.h>
  13. #include <unistd.h>
  14. #define PUTTY_DO_GLOBALS /* actually _define_ globals */
  15. #include "putty.h"
  16. #include "ssh.h"
  17. #include "misc.h"
  18. #include "pageant.h"
  19. SockAddr unix_sock_addr(const char *path);
  20. Socket new_unix_listener(SockAddr listenaddr, Plug plug);
  21. void fatalbox(const char *p, ...)
  22. {
  23. va_list ap;
  24. fprintf(stderr, "FATAL ERROR: ");
  25. va_start(ap, p);
  26. vfprintf(stderr, p, ap);
  27. va_end(ap);
  28. fputc('\n', stderr);
  29. exit(1);
  30. }
  31. void modalfatalbox(const char *p, ...)
  32. {
  33. va_list ap;
  34. fprintf(stderr, "FATAL ERROR: ");
  35. va_start(ap, p);
  36. vfprintf(stderr, p, ap);
  37. va_end(ap);
  38. fputc('\n', stderr);
  39. exit(1);
  40. }
  41. void nonfatal(const char *p, ...)
  42. {
  43. va_list ap;
  44. fprintf(stderr, "ERROR: ");
  45. va_start(ap, p);
  46. vfprintf(stderr, p, ap);
  47. va_end(ap);
  48. fputc('\n', stderr);
  49. }
  50. void connection_fatal(void *frontend, const char *p, ...)
  51. {
  52. va_list ap;
  53. fprintf(stderr, "FATAL ERROR: ");
  54. va_start(ap, p);
  55. vfprintf(stderr, p, ap);
  56. va_end(ap);
  57. fputc('\n', stderr);
  58. exit(1);
  59. }
  60. void cmdline_error(const char *p, ...)
  61. {
  62. va_list ap;
  63. fprintf(stderr, "pageant: ");
  64. va_start(ap, p);
  65. vfprintf(stderr, p, ap);
  66. va_end(ap);
  67. fputc('\n', stderr);
  68. exit(1);
  69. }
  70. FILE *pageant_logfp = NULL;
  71. void pageant_log(void *ctx, const char *fmt, va_list ap)
  72. {
  73. if (!pageant_logfp)
  74. return;
  75. fprintf(pageant_logfp, "pageant: ");
  76. vfprintf(pageant_logfp, fmt, ap);
  77. fprintf(pageant_logfp, "\n");
  78. }
  79. /*
  80. * In Pageant our selects are synchronous, so these functions are
  81. * empty stubs.
  82. */
  83. uxsel_id *uxsel_input_add(int fd, int rwx) { return NULL; }
  84. void uxsel_input_remove(uxsel_id *id) { }
  85. /*
  86. * More stubs.
  87. */
  88. void random_save_seed(void) {}
  89. void random_destroy_seed(void) {}
  90. void noise_ultralight(unsigned long data) {}
  91. char *platform_default_s(const char *name) { return NULL; }
  92. int platform_default_i(const char *name, int def) { return def; }
  93. FontSpec *platform_default_fontspec(const char *name) { return fontspec_new(""); }
  94. Filename *platform_default_filename(const char *name) { return filename_from_str(""); }
  95. char *x_get_default(const char *key) { return NULL; }
  96. void log_eventlog(void *handle, const char *event) {}
  97. int from_backend(void *frontend, int is_stderr, const char *data, int datalen)
  98. { assert(!"only here to satisfy notional call from backend_socket_log"); }
  99. /*
  100. * Short description of parameters.
  101. */
  102. static void usage(void)
  103. {
  104. printf("Pageant: SSH agent\n");
  105. printf("%s\n", ver);
  106. printf("Usage: pageant <lifetime> [key files]\n");
  107. printf(" pageant [key files] --exec <command> [args]\n");
  108. printf(" pageant -a [key files]\n");
  109. printf(" pageant -d [key identifiers]\n");
  110. printf(" pageant --public [key identifiers]\n");
  111. printf(" pageant --public-openssh [key identifiers]\n");
  112. printf(" pageant -l\n");
  113. printf(" pageant -D\n");
  114. printf("Lifetime options, for running Pageant as an agent:\n");
  115. printf(" -X run with the lifetime of the X server\n");
  116. printf(" -T run with the lifetime of the controlling tty\n");
  117. printf(" --permanent run permanently\n");
  118. printf(" --debug run in debugging mode, without forking\n");
  119. printf(" --exec <command> run with the lifetime of that command\n");
  120. printf("Client options, for talking to an existing agent:\n");
  121. printf(" -a add key(s) to the existing agent\n");
  122. printf(" -l list currently loaded key fingerprints and comments\n");
  123. printf(" --public print public keys in RFC 4716 format\n");
  124. printf(" --public-openssh print public keys in OpenSSH format\n");
  125. printf(" -d delete key(s) from the agent\n");
  126. printf(" -D delete all keys from the agent\n");
  127. printf("Other options:\n");
  128. printf(" -v verbose mode (in agent mode)\n");
  129. exit(1);
  130. }
  131. static void version(void)
  132. {
  133. printf("pageant: %s\n", ver);
  134. exit(1);
  135. }
  136. void keylist_update(void)
  137. {
  138. /* Nothing needs doing in Unix Pageant */
  139. }
  140. #define PAGEANT_DIR_PREFIX "/tmp/pageant"
  141. const char *const appname = "Pageant";
  142. static int time_to_die = FALSE;
  143. /* Stub functions to permit linking against x11fwd.c. These never get
  144. * used, because in LIFE_X11 mode we connect to the X server using a
  145. * straightforward Socket and don't try to create an ersatz SSH
  146. * forwarding too. */
  147. int sshfwd_write(struct ssh_channel *c, char *data, int len) { return 0; }
  148. void sshfwd_write_eof(struct ssh_channel *c) { }
  149. void sshfwd_unclean_close(struct ssh_channel *c, const char *err) { }
  150. void sshfwd_unthrottle(struct ssh_channel *c, int bufsize) {}
  151. Conf *sshfwd_get_conf(struct ssh_channel *c) { return NULL; }
  152. void sshfwd_x11_sharing_handover(struct ssh_channel *c,
  153. void *share_cs, void *share_chan,
  154. const char *peer_addr, int peer_port,
  155. int endian, int protomajor, int protominor,
  156. const void *initial_data, int initial_len) {}
  157. void sshfwd_x11_is_local(struct ssh_channel *c) {}
  158. /*
  159. * These functions are part of the plug for our connection to the X
  160. * display, so they do get called. They needn't actually do anything,
  161. * except that x11_closing has to signal back to the main loop that
  162. * it's time to terminate.
  163. */
  164. static void x11_log(Plug p, int type, SockAddr addr, int port,
  165. const char *error_msg, int error_code) {}
  166. static int x11_receive(Plug plug, int urgent, char *data, int len) {return 0;}
  167. static void x11_sent(Plug plug, int bufsize) {}
  168. static int x11_closing(Plug plug, const char *error_msg, int error_code,
  169. int calling_back)
  170. {
  171. time_to_die = TRUE;
  172. return 1;
  173. }
  174. struct X11Connection {
  175. const struct plug_function_table *fn;
  176. };
  177. char *socketname;
  178. static enum { SHELL_AUTO, SHELL_SH, SHELL_CSH } shell_type = SHELL_AUTO;
  179. void pageant_print_env(int pid)
  180. {
  181. if (shell_type == SHELL_AUTO) {
  182. /* Same policy as OpenSSH: if $SHELL ends in "csh" then assume
  183. * it's csh-shaped. */
  184. const char *shell = getenv("SHELL");
  185. if (shell && strlen(shell) >= 3 &&
  186. !strcmp(shell + strlen(shell) - 3, "csh"))
  187. shell_type = SHELL_CSH;
  188. else
  189. shell_type = SHELL_SH;
  190. }
  191. /*
  192. * These shell snippets could usefully pay some attention to
  193. * escaping of interesting characters. I don't think it causes a
  194. * problem at the moment, because the pathnames we use are so
  195. * utterly boring, but it's a lurking bug waiting to happen once
  196. * a bit more flexibility turns up.
  197. */
  198. switch (shell_type) {
  199. case SHELL_SH:
  200. printf("SSH_AUTH_SOCK=%s; export SSH_AUTH_SOCK;\n"
  201. "SSH_AGENT_PID=%d; export SSH_AGENT_PID;\n",
  202. socketname, pid);
  203. break;
  204. case SHELL_CSH:
  205. printf("setenv SSH_AUTH_SOCK %s;\n"
  206. "setenv SSH_AGENT_PID %d;\n",
  207. socketname, pid);
  208. break;
  209. case SHELL_AUTO:
  210. assert(0 && "Can't get here");
  211. break;
  212. }
  213. }
  214. void pageant_fork_and_print_env(int retain_tty)
  215. {
  216. pid_t pid = fork();
  217. if (pid == -1) {
  218. perror("fork");
  219. exit(1);
  220. } else if (pid != 0) {
  221. pageant_print_env(pid);
  222. exit(0);
  223. }
  224. /*
  225. * Having forked off, we now daemonise ourselves as best we can.
  226. * It's good practice in general to setsid() ourself out of any
  227. * process group we didn't want to be part of, and to chdir("/")
  228. * to avoid holding any directories open that we don't need in
  229. * case someone wants to umount them; also, we should definitely
  230. * close standard output (because it will very likely be pointing
  231. * at a pipe from which some parent process is trying to read our
  232. * environment variable dump, so if we hold open another copy of
  233. * it then that process will never finish reading). We close
  234. * standard input too on general principles, but not standard
  235. * error, since we might need to shout a panicky error message
  236. * down that one.
  237. */
  238. if (chdir("/") < 0) {
  239. /* should there be an error condition, nothing we can do about
  240. * it anyway */
  241. }
  242. close(0);
  243. close(1);
  244. if (retain_tty) {
  245. /* Get out of our previous process group, to avoid being
  246. * blasted by passing signals. But keep our controlling tty,
  247. * so we can keep checking to see if we still have one. */
  248. setpgrp();
  249. } else {
  250. /* Do that, but also leave our entire session and detach from
  251. * the controlling tty (if any). */
  252. setsid();
  253. }
  254. }
  255. int signalpipe[2];
  256. void sigchld(int signum)
  257. {
  258. if (write(signalpipe[1], "x", 1) <= 0)
  259. /* not much we can do about it */;
  260. }
  261. #define TTY_LIFE_POLL_INTERVAL (TICKSPERSEC * 30)
  262. void *dummy_timer_ctx;
  263. static void tty_life_timer(void *ctx, unsigned long now)
  264. {
  265. schedule_timer(TTY_LIFE_POLL_INTERVAL, tty_life_timer, &dummy_timer_ctx);
  266. }
  267. typedef enum {
  268. KEYACT_AGENT_LOAD,
  269. KEYACT_CLIENT_ADD,
  270. KEYACT_CLIENT_DEL,
  271. KEYACT_CLIENT_DEL_ALL,
  272. KEYACT_CLIENT_LIST,
  273. KEYACT_CLIENT_PUBLIC_OPENSSH,
  274. KEYACT_CLIENT_PUBLIC
  275. } keyact;
  276. struct cmdline_key_action {
  277. struct cmdline_key_action *next;
  278. keyact action;
  279. const char *filename;
  280. };
  281. int is_agent_action(keyact action)
  282. {
  283. return action == KEYACT_AGENT_LOAD;
  284. }
  285. struct cmdline_key_action *keyact_head = NULL, *keyact_tail = NULL;
  286. void add_keyact(keyact action, const char *filename)
  287. {
  288. struct cmdline_key_action *a = snew(struct cmdline_key_action);
  289. a->action = action;
  290. a->filename = filename;
  291. a->next = NULL;
  292. if (keyact_tail)
  293. keyact_tail->next = a;
  294. else
  295. keyact_head = a;
  296. keyact_tail = a;
  297. }
  298. int have_controlling_tty(void)
  299. {
  300. int fd = open("/dev/tty", O_RDONLY);
  301. if (fd < 0) {
  302. if (errno != ENXIO) {
  303. perror("/dev/tty: open");
  304. exit(1);
  305. }
  306. return FALSE;
  307. } else {
  308. close(fd);
  309. return TRUE;
  310. }
  311. }
  312. char **exec_args = NULL;
  313. enum {
  314. LIFE_UNSPEC, LIFE_X11, LIFE_TTY, LIFE_DEBUG, LIFE_PERM, LIFE_EXEC
  315. } life = LIFE_UNSPEC;
  316. const char *display = NULL;
  317. static char *askpass(const char *comment)
  318. {
  319. if (have_controlling_tty()) {
  320. int ret;
  321. prompts_t *p = new_prompts(NULL);
  322. p->to_server = FALSE;
  323. p->name = dupstr("Pageant passphrase prompt");
  324. add_prompt(p,
  325. dupprintf("Enter passphrase to load key '%s': ", comment),
  326. FALSE);
  327. ret = console_get_userpass_input(p, NULL, 0);
  328. assert(ret >= 0);
  329. if (!ret) {
  330. perror("pageant: unable to read passphrase");
  331. free_prompts(p);
  332. return NULL;
  333. } else {
  334. char *passphrase = dupstr(p->prompts[0]->result);
  335. free_prompts(p);
  336. return passphrase;
  337. }
  338. } else if (display) {
  339. char *prompt, *passphrase;
  340. int success;
  341. /* in gtkask.c */
  342. char *gtk_askpass_main(const char *display, const char *wintitle,
  343. const char *prompt, int *success);
  344. prompt = dupprintf("Enter passphrase to load key '%s': ", comment);
  345. passphrase = gtk_askpass_main(display,
  346. "Pageant passphrase prompt",
  347. prompt, &success);
  348. sfree(prompt);
  349. if (!success) {
  350. /* return value is error message */
  351. fprintf(stderr, "%s\n", passphrase);
  352. sfree(passphrase);
  353. passphrase = NULL;
  354. }
  355. return passphrase;
  356. } else {
  357. fprintf(stderr, "no way to read a passphrase without tty or "
  358. "X display\n");
  359. return NULL;
  360. }
  361. }
  362. static int unix_add_keyfile(const char *filename_str)
  363. {
  364. Filename *filename = filename_from_str(filename_str);
  365. int status, ret;
  366. char *err;
  367. ret = TRUE;
  368. /*
  369. * Try without a passphrase.
  370. */
  371. status = pageant_add_keyfile(filename, NULL, &err);
  372. if (status == PAGEANT_ACTION_OK) {
  373. goto cleanup;
  374. } else if (status == PAGEANT_ACTION_FAILURE) {
  375. fprintf(stderr, "pageant: %s: %s\n", filename_str, err);
  376. ret = FALSE;
  377. goto cleanup;
  378. }
  379. /*
  380. * And now try prompting for a passphrase.
  381. */
  382. while (1) {
  383. char *passphrase = askpass(err);
  384. sfree(err);
  385. err = NULL;
  386. if (!passphrase)
  387. break;
  388. status = pageant_add_keyfile(filename, passphrase, &err);
  389. smemclr(passphrase, strlen(passphrase));
  390. sfree(passphrase);
  391. passphrase = NULL;
  392. if (status == PAGEANT_ACTION_OK) {
  393. goto cleanup;
  394. } else if (status == PAGEANT_ACTION_FAILURE) {
  395. fprintf(stderr, "pageant: %s: %s\n", filename_str, err);
  396. ret = FALSE;
  397. goto cleanup;
  398. }
  399. }
  400. cleanup:
  401. sfree(err);
  402. filename_free(filename);
  403. return ret;
  404. }
  405. void key_list_callback(void *ctx, const char *fingerprint,
  406. const char *comment, struct pageant_pubkey *key)
  407. {
  408. printf("%s %s\n", fingerprint, comment);
  409. }
  410. struct key_find_ctx {
  411. const char *string;
  412. int match_fp, match_comment;
  413. struct pageant_pubkey *found;
  414. int nfound;
  415. };
  416. int match_fingerprint_string(const char *string, const char *fingerprint)
  417. {
  418. const char *hash;
  419. /* Find the hash in the fingerprint string. It'll be the word at the end. */
  420. hash = strrchr(fingerprint, ' ');
  421. assert(hash);
  422. hash++;
  423. /* Now see if the search string is a prefix of the full hash,
  424. * neglecting colons and case differences. */
  425. while (1) {
  426. while (*string == ':') string++;
  427. while (*hash == ':') hash++;
  428. if (!*string)
  429. return TRUE;
  430. if (tolower((unsigned char)*string) != tolower((unsigned char)*hash))
  431. return FALSE;
  432. string++;
  433. hash++;
  434. }
  435. }
  436. void key_find_callback(void *vctx, const char *fingerprint,
  437. const char *comment, struct pageant_pubkey *key)
  438. {
  439. struct key_find_ctx *ctx = (struct key_find_ctx *)vctx;
  440. if ((ctx->match_comment && !strcmp(ctx->string, comment)) ||
  441. (ctx->match_fp && match_fingerprint_string(ctx->string, fingerprint)))
  442. {
  443. if (!ctx->found)
  444. ctx->found = pageant_pubkey_copy(key);
  445. ctx->nfound++;
  446. }
  447. }
  448. struct pageant_pubkey *find_key(const char *string, char **retstr)
  449. {
  450. struct key_find_ctx actx, *ctx = &actx;
  451. struct pageant_pubkey key_in, *key_ret;
  452. int try_file = TRUE, try_fp = TRUE, try_comment = TRUE;
  453. int file_errors = FALSE;
  454. /*
  455. * Trim off disambiguating prefixes telling us how to interpret
  456. * the provided string.
  457. */
  458. if (!strncmp(string, "file:", 5)) {
  459. string += 5;
  460. try_fp = try_comment = FALSE;
  461. file_errors = TRUE; /* also report failure to load the file */
  462. } else if (!strncmp(string, "comment:", 8)) {
  463. string += 8;
  464. try_file = try_fp = FALSE;
  465. } else if (!strncmp(string, "fp:", 3)) {
  466. string += 3;
  467. try_file = try_comment = FALSE;
  468. } else if (!strncmp(string, "fingerprint:", 12)) {
  469. string += 12;
  470. try_file = try_comment = FALSE;
  471. }
  472. /*
  473. * Try interpreting the string as a key file name.
  474. */
  475. if (try_file) {
  476. Filename *fn = filename_from_str(string);
  477. int keytype = key_type(fn);
  478. if (keytype == SSH_KEYTYPE_SSH1 ||
  479. keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
  480. const char *error;
  481. if (!rsakey_pubblob(fn, &key_in.blob, &key_in.bloblen,
  482. NULL, &error)) {
  483. if (file_errors) {
  484. *retstr = dupprintf("unable to load file '%s': %s",
  485. string, error);
  486. filename_free(fn);
  487. return NULL;
  488. }
  489. }
  490. /*
  491. * If we've successfully loaded the file, stop here - we
  492. * already have a key blob and need not go to the agent to
  493. * list things.
  494. */
  495. key_in.ssh_version = 1;
  496. key_ret = pageant_pubkey_copy(&key_in);
  497. sfree(key_in.blob);
  498. filename_free(fn);
  499. return key_ret;
  500. } else if (keytype == SSH_KEYTYPE_SSH2 ||
  501. keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
  502. keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  503. const char *error;
  504. if ((key_in.blob = ssh2_userkey_loadpub(fn, NULL,
  505. &key_in.bloblen,
  506. NULL, &error)) == NULL) {
  507. if (file_errors) {
  508. *retstr = dupprintf("unable to load file '%s': %s",
  509. string, error);
  510. filename_free(fn);
  511. return NULL;
  512. }
  513. }
  514. /*
  515. * If we've successfully loaded the file, stop here - we
  516. * already have a key blob and need not go to the agent to
  517. * list things.
  518. */
  519. key_in.ssh_version = 2;
  520. key_ret = pageant_pubkey_copy(&key_in);
  521. sfree(key_in.blob);
  522. filename_free(fn);
  523. return key_ret;
  524. } else {
  525. if (file_errors) {
  526. *retstr = dupprintf("unable to load key file '%s': %s",
  527. string, key_type_to_str(keytype));
  528. filename_free(fn);
  529. return NULL;
  530. }
  531. }
  532. filename_free(fn);
  533. }
  534. /*
  535. * Failing that, go through the keys in the agent, and match
  536. * against fingerprints and comments as appropriate.
  537. */
  538. ctx->string = string;
  539. ctx->match_fp = try_fp;
  540. ctx->match_comment = try_comment;
  541. ctx->found = NULL;
  542. ctx->nfound = 0;
  543. if (pageant_enum_keys(key_find_callback, ctx, retstr) ==
  544. PAGEANT_ACTION_FAILURE)
  545. return NULL;
  546. if (ctx->nfound == 0) {
  547. *retstr = dupstr("no key matched");
  548. assert(!ctx->found);
  549. return NULL;
  550. } else if (ctx->nfound > 1) {
  551. *retstr = dupstr("multiple keys matched");
  552. assert(ctx->found);
  553. pageant_pubkey_free(ctx->found);
  554. return NULL;
  555. }
  556. assert(ctx->found);
  557. return ctx->found;
  558. }
  559. void run_client(void)
  560. {
  561. const struct cmdline_key_action *act;
  562. struct pageant_pubkey *key;
  563. int errors = FALSE;
  564. char *retstr;
  565. if (!agent_exists()) {
  566. fprintf(stderr, "pageant: no agent running to talk to\n");
  567. exit(1);
  568. }
  569. for (act = keyact_head; act; act = act->next) {
  570. switch (act->action) {
  571. case KEYACT_CLIENT_ADD:
  572. if (!unix_add_keyfile(act->filename))
  573. errors = TRUE;
  574. break;
  575. case KEYACT_CLIENT_LIST:
  576. if (pageant_enum_keys(key_list_callback, NULL, &retstr) ==
  577. PAGEANT_ACTION_FAILURE) {
  578. fprintf(stderr, "pageant: listing keys: %s\n", retstr);
  579. sfree(retstr);
  580. errors = TRUE;
  581. }
  582. break;
  583. case KEYACT_CLIENT_DEL:
  584. key = NULL;
  585. if (!(key = find_key(act->filename, &retstr)) ||
  586. pageant_delete_key(key, &retstr) == PAGEANT_ACTION_FAILURE) {
  587. fprintf(stderr, "pageant: deleting key '%s': %s\n",
  588. act->filename, retstr);
  589. sfree(retstr);
  590. errors = TRUE;
  591. }
  592. if (key)
  593. pageant_pubkey_free(key);
  594. break;
  595. case KEYACT_CLIENT_PUBLIC_OPENSSH:
  596. case KEYACT_CLIENT_PUBLIC:
  597. key = NULL;
  598. if (!(key = find_key(act->filename, &retstr))) {
  599. fprintf(stderr, "pageant: finding key '%s': %s\n",
  600. act->filename, retstr);
  601. sfree(retstr);
  602. errors = TRUE;
  603. } else {
  604. FILE *fp = stdout; /* FIXME: add a -o option? */
  605. if (key->ssh_version == 1) {
  606. struct RSAKey rkey;
  607. memset(&rkey, 0, sizeof(rkey));
  608. rkey.comment = dupstr(key->comment);
  609. makekey(key->blob, key->bloblen, &rkey, NULL, 0);
  610. ssh1_write_pubkey(fp, &rkey);
  611. freersakey(&rkey);
  612. } else {
  613. ssh2_write_pubkey(fp, key->comment, key->blob,key->bloblen,
  614. (act->action == KEYACT_CLIENT_PUBLIC ?
  615. SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 :
  616. SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH));
  617. }
  618. pageant_pubkey_free(key);
  619. }
  620. break;
  621. case KEYACT_CLIENT_DEL_ALL:
  622. if (pageant_delete_all_keys(&retstr) == PAGEANT_ACTION_FAILURE) {
  623. fprintf(stderr, "pageant: deleting all keys: %s\n", retstr);
  624. sfree(retstr);
  625. errors = TRUE;
  626. }
  627. break;
  628. default:
  629. assert(0 && "Invalid client action found");
  630. }
  631. }
  632. if (errors)
  633. exit(1);
  634. }
  635. void run_agent(void)
  636. {
  637. const char *err;
  638. char *username, *socketdir;
  639. struct pageant_listen_state *pl;
  640. Socket sock;
  641. unsigned long now;
  642. int *fdlist;
  643. int fd;
  644. int i, fdcount, fdsize, fdstate;
  645. int termination_pid = -1;
  646. int errors = FALSE;
  647. Conf *conf;
  648. const struct cmdline_key_action *act;
  649. fdlist = NULL;
  650. fdcount = fdsize = 0;
  651. pageant_init();
  652. /*
  653. * Start by loading any keys provided on the command line.
  654. */
  655. for (act = keyact_head; act; act = act->next) {
  656. assert(act->action == KEYACT_AGENT_LOAD);
  657. if (!unix_add_keyfile(act->filename))
  658. errors = TRUE;
  659. }
  660. if (errors)
  661. exit(1);
  662. /*
  663. * Set up a listening socket and run Pageant on it.
  664. */
  665. username = get_username();
  666. socketdir = dupprintf("%s.%s", PAGEANT_DIR_PREFIX, username);
  667. sfree(username);
  668. assert(*socketdir == '/');
  669. if ((err = make_dir_and_check_ours(socketdir)) != NULL) {
  670. fprintf(stderr, "pageant: %s: %s\n", socketdir, err);
  671. exit(1);
  672. }
  673. socketname = dupprintf("%s/pageant.%d", socketdir, (int)getpid());
  674. pl = pageant_listener_new();
  675. sock = new_unix_listener(unix_sock_addr(socketname), (Plug)pl);
  676. if ((err = sk_socket_error(sock)) != NULL) {
  677. fprintf(stderr, "pageant: %s: %s\n", socketname, err);
  678. exit(1);
  679. }
  680. pageant_listener_got_socket(pl, sock);
  681. conf = conf_new();
  682. conf_set_int(conf, CONF_proxy_type, PROXY_NONE);
  683. /*
  684. * Lifetime preparations.
  685. */
  686. signalpipe[0] = signalpipe[1] = -1;
  687. if (life == LIFE_X11) {
  688. struct X11Display *disp;
  689. void *greeting;
  690. int greetinglen;
  691. Socket s;
  692. struct X11Connection *conn;
  693. static const struct plug_function_table fn_table = {
  694. x11_log,
  695. x11_closing,
  696. x11_receive,
  697. x11_sent,
  698. NULL
  699. };
  700. if (!display) {
  701. fprintf(stderr, "pageant: no DISPLAY for -X mode\n");
  702. exit(1);
  703. }
  704. disp = x11_setup_display(display, conf);
  705. conn = snew(struct X11Connection);
  706. conn->fn = &fn_table;
  707. s = new_connection(sk_addr_dup(disp->addr),
  708. disp->realhost, disp->port,
  709. 0, 1, 0, 0, (Plug)conn, conf);
  710. if ((err = sk_socket_error(s)) != NULL) {
  711. fprintf(stderr, "pageant: unable to connect to X server: %s", err);
  712. exit(1);
  713. }
  714. greeting = x11_make_greeting('B', 11, 0, disp->localauthproto,
  715. disp->localauthdata,
  716. disp->localauthdatalen,
  717. NULL, 0, &greetinglen);
  718. sk_write(s, greeting, greetinglen);
  719. smemclr(greeting, greetinglen);
  720. sfree(greeting);
  721. pageant_fork_and_print_env(FALSE);
  722. } else if (life == LIFE_TTY) {
  723. schedule_timer(TTY_LIFE_POLL_INTERVAL,
  724. tty_life_timer, &dummy_timer_ctx);
  725. pageant_fork_and_print_env(TRUE);
  726. } else if (life == LIFE_PERM) {
  727. pageant_fork_and_print_env(FALSE);
  728. } else if (life == LIFE_DEBUG) {
  729. pageant_print_env(getpid());
  730. pageant_logfp = stdout;
  731. } else if (life == LIFE_EXEC) {
  732. pid_t agentpid, pid;
  733. agentpid = getpid();
  734. /*
  735. * Set up the pipe we'll use to tell us about SIGCHLD.
  736. */
  737. if (pipe(signalpipe) < 0) {
  738. perror("pipe");
  739. exit(1);
  740. }
  741. putty_signal(SIGCHLD, sigchld);
  742. pid = fork();
  743. if (pid < 0) {
  744. perror("fork");
  745. exit(1);
  746. } else if (pid == 0) {
  747. setenv("SSH_AUTH_SOCK", socketname, TRUE);
  748. setenv("SSH_AGENT_PID", dupprintf("%d", (int)agentpid), TRUE);
  749. execvp(exec_args[0], exec_args);
  750. perror("exec");
  751. _exit(127);
  752. } else {
  753. termination_pid = pid;
  754. }
  755. }
  756. /*
  757. * Now we've decided on our logging arrangements, pass them on to
  758. * pageant.c.
  759. */
  760. pageant_listener_set_logfn(pl, NULL, pageant_logfp ? pageant_log : NULL);
  761. now = GETTICKCOUNT();
  762. while (!time_to_die) {
  763. fd_set rset, wset, xset;
  764. int maxfd;
  765. int rwx;
  766. int ret;
  767. unsigned long next;
  768. FD_ZERO(&rset);
  769. FD_ZERO(&wset);
  770. FD_ZERO(&xset);
  771. maxfd = 0;
  772. if (signalpipe[0] >= 0) {
  773. FD_SET_MAX(signalpipe[0], maxfd, rset);
  774. }
  775. /* Count the currently active fds. */
  776. i = 0;
  777. for (fd = first_fd(&fdstate, &rwx); fd >= 0;
  778. fd = next_fd(&fdstate, &rwx)) i++;
  779. /* Expand the fdlist buffer if necessary. */
  780. if (i > fdsize) {
  781. fdsize = i + 16;
  782. fdlist = sresize(fdlist, fdsize, int);
  783. }
  784. /*
  785. * Add all currently open fds to the select sets, and store
  786. * them in fdlist as well.
  787. */
  788. fdcount = 0;
  789. for (fd = first_fd(&fdstate, &rwx); fd >= 0;
  790. fd = next_fd(&fdstate, &rwx)) {
  791. fdlist[fdcount++] = fd;
  792. if (rwx & 1)
  793. FD_SET_MAX(fd, maxfd, rset);
  794. if (rwx & 2)
  795. FD_SET_MAX(fd, maxfd, wset);
  796. if (rwx & 4)
  797. FD_SET_MAX(fd, maxfd, xset);
  798. }
  799. if (toplevel_callback_pending()) {
  800. struct timeval tv;
  801. tv.tv_sec = 0;
  802. tv.tv_usec = 0;
  803. ret = select(maxfd, &rset, &wset, &xset, &tv);
  804. } else if (run_timers(now, &next)) {
  805. unsigned long then;
  806. long ticks;
  807. struct timeval tv;
  808. then = now;
  809. now = GETTICKCOUNT();
  810. if (now - then > next - then)
  811. ticks = 0;
  812. else
  813. ticks = next - now;
  814. tv.tv_sec = ticks / 1000;
  815. tv.tv_usec = ticks % 1000 * 1000;
  816. ret = select(maxfd, &rset, &wset, &xset, &tv);
  817. if (ret == 0)
  818. now = next;
  819. else
  820. now = GETTICKCOUNT();
  821. } else {
  822. ret = select(maxfd, &rset, &wset, &xset, NULL);
  823. }
  824. if (ret < 0 && errno == EINTR)
  825. continue;
  826. if (ret < 0) {
  827. perror("select");
  828. exit(1);
  829. }
  830. if (life == LIFE_TTY) {
  831. /*
  832. * Every time we wake up (whether it was due to tty_timer
  833. * elapsing or for any other reason), poll to see if we
  834. * still have a controlling terminal. If we don't, then
  835. * our containing tty session has ended, so it's time to
  836. * clean up and leave.
  837. */
  838. if (!have_controlling_tty()) {
  839. time_to_die = TRUE;
  840. break;
  841. }
  842. }
  843. for (i = 0; i < fdcount; i++) {
  844. fd = fdlist[i];
  845. /*
  846. * We must process exceptional notifications before
  847. * ordinary readability ones, or we may go straight
  848. * past the urgent marker.
  849. */
  850. if (FD_ISSET(fd, &xset))
  851. select_result(fd, 4);
  852. if (FD_ISSET(fd, &rset))
  853. select_result(fd, 1);
  854. if (FD_ISSET(fd, &wset))
  855. select_result(fd, 2);
  856. }
  857. if (signalpipe[0] >= 0 && FD_ISSET(signalpipe[0], &rset)) {
  858. char c[1];
  859. if (read(signalpipe[0], c, 1) <= 0)
  860. /* ignore error */;
  861. /* ignore its value; it'll be `x' */
  862. while (1) {
  863. int status;
  864. pid_t pid;
  865. pid = waitpid(-1, &status, WNOHANG);
  866. if (pid <= 0)
  867. break;
  868. if (pid == termination_pid)
  869. time_to_die = TRUE;
  870. }
  871. }
  872. run_toplevel_callbacks();
  873. }
  874. /*
  875. * When we come here, we're terminating, and should clean up our
  876. * Unix socket file if possible.
  877. */
  878. if (unlink(socketname) < 0) {
  879. fprintf(stderr, "pageant: %s: %s\n", socketname, strerror(errno));
  880. exit(1);
  881. }
  882. }
  883. int main(int argc, char **argv)
  884. {
  885. int doing_opts = TRUE;
  886. keyact curr_keyact = KEYACT_AGENT_LOAD;
  887. /*
  888. * Process the command line.
  889. */
  890. while (--argc > 0) {
  891. char *p = *++argv;
  892. if (*p == '-' && doing_opts) {
  893. if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
  894. version();
  895. } else if (!strcmp(p, "--help")) {
  896. usage();
  897. exit(0);
  898. } else if (!strcmp(p, "-v")) {
  899. pageant_logfp = stderr;
  900. } else if (!strcmp(p, "-a")) {
  901. curr_keyact = KEYACT_CLIENT_ADD;
  902. } else if (!strcmp(p, "-d")) {
  903. curr_keyact = KEYACT_CLIENT_DEL;
  904. } else if (!strcmp(p, "-s")) {
  905. shell_type = SHELL_SH;
  906. } else if (!strcmp(p, "-c")) {
  907. shell_type = SHELL_CSH;
  908. } else if (!strcmp(p, "-D")) {
  909. add_keyact(KEYACT_CLIENT_DEL_ALL, NULL);
  910. } else if (!strcmp(p, "-l")) {
  911. add_keyact(KEYACT_CLIENT_LIST, NULL);
  912. } else if (!strcmp(p, "--public")) {
  913. curr_keyact = KEYACT_CLIENT_PUBLIC;
  914. } else if (!strcmp(p, "--public-openssh")) {
  915. curr_keyact = KEYACT_CLIENT_PUBLIC_OPENSSH;
  916. } else if (!strcmp(p, "-X")) {
  917. life = LIFE_X11;
  918. } else if (!strcmp(p, "-T")) {
  919. life = LIFE_TTY;
  920. } else if (!strcmp(p, "--debug")) {
  921. life = LIFE_DEBUG;
  922. } else if (!strcmp(p, "--permanent")) {
  923. life = LIFE_PERM;
  924. } else if (!strcmp(p, "--exec")) {
  925. life = LIFE_EXEC;
  926. /* Now all subsequent arguments go to the exec command. */
  927. if (--argc > 0) {
  928. exec_args = ++argv;
  929. argc = 0; /* force end of option processing */
  930. } else {
  931. fprintf(stderr, "pageant: expected a command "
  932. "after --exec\n");
  933. exit(1);
  934. }
  935. } else if (!strcmp(p, "--")) {
  936. doing_opts = FALSE;
  937. }
  938. } else {
  939. /*
  940. * Non-option arguments (apart from those after --exec,
  941. * which are treated specially above) are interpreted as
  942. * the names of private key files to either add or delete
  943. * from an agent.
  944. */
  945. add_keyact(curr_keyact, p);
  946. }
  947. }
  948. if (life == LIFE_EXEC && !exec_args) {
  949. fprintf(stderr, "pageant: expected a command with --exec\n");
  950. exit(1);
  951. }
  952. /*
  953. * Block SIGPIPE, so that we'll get EPIPE individually on
  954. * particular network connections that go wrong.
  955. */
  956. putty_signal(SIGPIPE, SIG_IGN);
  957. sk_init();
  958. uxsel_init();
  959. if (!display) {
  960. display = getenv("DISPLAY");
  961. if (display && !*display)
  962. display = NULL;
  963. }
  964. /*
  965. * Now distinguish our two main running modes. Either we're
  966. * actually starting up an agent, in which case we should have a
  967. * lifetime mode, and no key actions of KEYACT_CLIENT_* type; or
  968. * else we're contacting an existing agent to add or remove keys,
  969. * in which case we should have no lifetime mode, and no key
  970. * actions of KEYACT_AGENT_* type.
  971. */
  972. {
  973. int has_agent_actions = FALSE;
  974. int has_client_actions = FALSE;
  975. int has_lifetime = FALSE;
  976. const struct cmdline_key_action *act;
  977. for (act = keyact_head; act; act = act->next) {
  978. if (is_agent_action(act->action))
  979. has_agent_actions = TRUE;
  980. else
  981. has_client_actions = TRUE;
  982. }
  983. if (life != LIFE_UNSPEC)
  984. has_lifetime = TRUE;
  985. if (has_lifetime && has_client_actions) {
  986. fprintf(stderr, "pageant: client key actions (-a, -d, -D, -l, -L)"
  987. " do not go with an agent lifetime option\n");
  988. exit(1);
  989. }
  990. if (!has_lifetime && has_agent_actions) {
  991. fprintf(stderr, "pageant: expected an agent lifetime option with"
  992. " bare key file arguments\n");
  993. exit(1);
  994. }
  995. if (!has_lifetime && !has_client_actions) {
  996. fprintf(stderr, "pageant: expected an agent lifetime option"
  997. " or a client key action\n");
  998. exit(1);
  999. }
  1000. if (has_lifetime) {
  1001. run_agent();
  1002. } else if (has_client_actions) {
  1003. run_client();
  1004. }
  1005. }
  1006. return 0;
  1007. }