plink.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. /*
  2. * PLink - a Windows command-line (stdin/stdout) variant of PuTTY.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <assert.h>
  7. #include <stdarg.h>
  8. #include "putty.h"
  9. #include "ssh.h"
  10. #include "storage.h"
  11. #include "tree234.h"
  12. #include "security-api.h"
  13. void cmdline_error(const char *fmt, ...)
  14. {
  15. va_list ap;
  16. va_start(ap, fmt);
  17. console_print_error_msg_fmt_v("plink", fmt, ap);
  18. va_end(ap);
  19. exit(1);
  20. }
  21. static HANDLE inhandle, outhandle, errhandle;
  22. static struct handle *stdin_handle, *stdout_handle, *stderr_handle;
  23. static handle_sink stdout_hs, stderr_hs;
  24. static StripCtrlChars *stdout_scc, *stderr_scc;
  25. static BinarySink *stdout_bs, *stderr_bs;
  26. static DWORD orig_console_mode;
  27. static Backend *backend;
  28. static LogContext *logctx;
  29. static Conf *conf;
  30. static void plink_echoedit_update(Seat *seat, bool echo, bool edit)
  31. {
  32. /* Update stdin read mode to reflect changes in line discipline. */
  33. DWORD mode;
  34. mode = ENABLE_PROCESSED_INPUT;
  35. if (echo)
  36. mode = mode | ENABLE_ECHO_INPUT;
  37. else
  38. mode = mode & ~ENABLE_ECHO_INPUT;
  39. if (edit)
  40. mode = mode | ENABLE_LINE_INPUT;
  41. else
  42. mode = mode & ~ENABLE_LINE_INPUT;
  43. SetConsoleMode(inhandle, mode);
  44. }
  45. static size_t plink_output(
  46. Seat *seat, SeatOutputType type, const void *data, size_t len)
  47. {
  48. bool is_stderr = type != SEAT_OUTPUT_STDOUT;
  49. BinarySink *bs = is_stderr ? stderr_bs : stdout_bs;
  50. put_data(bs, data, len);
  51. return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
  52. }
  53. static bool plink_eof(Seat *seat)
  54. {
  55. handle_write_eof(stdout_handle);
  56. return false; /* do not respond to incoming EOF with outgoing */
  57. }
  58. static SeatPromptResult plink_get_userpass_input(Seat *seat, prompts_t *p)
  59. {
  60. /* Plink doesn't support Restart Session, so we can just have a
  61. * single static cmdline_get_passwd_input_state that's never reset */
  62. static cmdline_get_passwd_input_state cmdline_state =
  63. CMDLINE_GET_PASSWD_INPUT_STATE_INIT;
  64. SeatPromptResult spr;
  65. spr = cmdline_get_passwd_input(p, &cmdline_state, false);
  66. if (spr.kind == SPRK_INCOMPLETE)
  67. spr = console_get_userpass_input(p);
  68. return spr;
  69. }
  70. static bool plink_seat_interactive(Seat *seat)
  71. {
  72. return (!*conf_get_str_ambi(conf, CONF_remote_cmd, NULL) &&
  73. !*conf_get_str_ambi(conf, CONF_remote_cmd2, NULL) &&
  74. !*conf_get_str(conf, CONF_ssh_nc_host));
  75. }
  76. static const SeatVtable plink_seat_vt = {
  77. .output = plink_output,
  78. .eof = plink_eof,
  79. .sent = nullseat_sent,
  80. .banner = nullseat_banner_to_stderr,
  81. .get_userpass_input = plink_get_userpass_input,
  82. .notify_session_started = nullseat_notify_session_started,
  83. .notify_remote_exit = nullseat_notify_remote_exit,
  84. .notify_remote_disconnect = nullseat_notify_remote_disconnect,
  85. .connection_fatal = console_connection_fatal,
  86. .nonfatal = console_nonfatal,
  87. .update_specials_menu = nullseat_update_specials_menu,
  88. .get_ttymode = nullseat_get_ttymode,
  89. .set_busy_status = nullseat_set_busy_status,
  90. .confirm_ssh_host_key = console_confirm_ssh_host_key,
  91. .confirm_weak_crypto_primitive = console_confirm_weak_crypto_primitive,
  92. .confirm_weak_cached_hostkey = console_confirm_weak_cached_hostkey,
  93. .prompt_descriptions = console_prompt_descriptions,
  94. .is_utf8 = nullseat_is_never_utf8,
  95. .echoedit_update = plink_echoedit_update,
  96. .get_x_display = nullseat_get_x_display,
  97. .get_windowid = nullseat_get_windowid,
  98. .get_window_pixel_size = nullseat_get_window_pixel_size,
  99. .stripctrl_new = console_stripctrl_new,
  100. .set_trust_status = console_set_trust_status,
  101. .can_set_trust_status = console_can_set_trust_status,
  102. .has_mixed_input_stream = console_has_mixed_input_stream,
  103. .verbose = cmdline_seat_verbose,
  104. .interactive = plink_seat_interactive,
  105. .get_cursor_position = nullseat_get_cursor_position,
  106. };
  107. static Seat plink_seat[1] = {{ &plink_seat_vt }};
  108. static DWORD main_thread_id;
  109. /*
  110. * Short description of parameters.
  111. */
  112. static void usage(void)
  113. {
  114. printf("Plink: command-line connection utility\n");
  115. printf("%s\n", ver);
  116. printf("Usage: plink [options] [user@]host [command]\n");
  117. printf(" (\"host\" can also be a PuTTY saved session name)\n");
  118. printf("Options:\n");
  119. printf(" -V print version information and exit\n");
  120. printf(" -pgpfp print PGP key fingerprints and exit\n");
  121. printf(" -v show verbose messages\n");
  122. printf(" -load sessname Load settings from saved session\n");
  123. printf(" -ssh -telnet -rlogin -raw -serial\n");
  124. printf(" force use of a particular protocol\n");
  125. printf(" -ssh-connection\n");
  126. printf(" force use of the bare ssh-connection protocol\n");
  127. printf(" -P port connect to specified port\n");
  128. printf(" -l user connect with specified username\n");
  129. printf(" -batch disable all interactive prompts\n");
  130. printf(" -proxycmd command\n");
  131. printf(" use 'command' as local proxy\n");
  132. printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
  133. printf(" Specify the serial configuration (serial only)\n");
  134. printf("The following options only apply to SSH connections:\n");
  135. printf(" -pwfile file login with password read from specified file\n");
  136. printf(" -D [listen-IP:]listen-port\n");
  137. printf(" Dynamic SOCKS-based port forwarding\n");
  138. printf(" -L [listen-IP:]listen-port:host:port\n");
  139. printf(" Forward local port to remote address\n");
  140. printf(" -R [listen-IP:]listen-port:host:port\n");
  141. printf(" Forward remote port to local address\n");
  142. printf(" -X -x enable / disable X11 forwarding\n");
  143. printf(" -A -a enable / disable agent forwarding\n");
  144. printf(" -t -T enable / disable pty allocation\n");
  145. printf(" -1 -2 force use of particular SSH protocol version\n");
  146. printf(" -4 -6 force use of IPv4 or IPv6\n");
  147. printf(" -C enable compression\n");
  148. printf(" -i key private key file for user authentication\n");
  149. printf(" -noagent disable use of Pageant\n");
  150. printf(" -agent enable use of Pageant\n");
  151. printf(" -no-trivial-auth\n");
  152. printf(" disconnect if SSH authentication succeeds trivially\n");
  153. printf(" -noshare disable use of connection sharing\n");
  154. printf(" -share enable use of connection sharing\n");
  155. printf(" -hostkey keyid\n");
  156. printf(" manually specify a host key (may be repeated)\n");
  157. printf(" -sanitise-stderr, -sanitise-stdout, "
  158. "-no-sanitise-stderr, -no-sanitise-stdout\n");
  159. printf(" do/don't strip control chars from standard "
  160. "output/error\n");
  161. printf(" -no-antispoof omit anti-spoofing prompt after "
  162. "authentication\n");
  163. printf(" -m file read remote command(s) from file\n");
  164. printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
  165. printf(" -N don't start a shell/command (SSH-2 only)\n");
  166. printf(" -nc host:port\n");
  167. printf(" open tunnel in place of session (SSH-2 only)\n");
  168. printf(" -sshlog file\n");
  169. printf(" -sshrawlog file\n");
  170. printf(" log protocol details to a file\n");
  171. printf(" -logoverwrite\n");
  172. printf(" -logappend\n");
  173. printf(" control what happens when a log file already exists\n");
  174. printf(" -shareexists\n");
  175. printf(" test whether a connection-sharing upstream exists\n");
  176. }
  177. static void version(void)
  178. {
  179. char *buildinfo_text = buildinfo("\n");
  180. printf("plink: %s\n%s\n", ver, buildinfo_text);
  181. sfree(buildinfo_text);
  182. exit(0);
  183. }
  184. size_t stdin_gotdata(struct handle *h, const void *data, size_t len, int err)
  185. {
  186. if (err) {
  187. char buf[4096];
  188. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
  189. buf, lenof(buf), NULL);
  190. buf[lenof(buf)-1] = '\0';
  191. if (buf[strlen(buf)-1] == '\n')
  192. buf[strlen(buf)-1] = '\0';
  193. fprintf(stderr, "Unable to read from standard input: %s\n", buf);
  194. cleanup_exit(0);
  195. }
  196. noise_ultralight(NOISE_SOURCE_IOLEN, len);
  197. if (backend_connected(backend)) {
  198. if (len > 0) {
  199. backend_send(backend, data, len);
  200. return backend_sendbuffer(backend);
  201. } else {
  202. backend_special(backend, SS_EOF, 0);
  203. return 0;
  204. }
  205. } else
  206. return 0;
  207. }
  208. void stdouterr_sent(struct handle *h, size_t new_backlog, int err, bool close)
  209. {
  210. if (close) {
  211. CloseHandle(outhandle);
  212. CloseHandle(errhandle);
  213. outhandle = errhandle = INVALID_HANDLE_VALUE;
  214. }
  215. if (err) {
  216. char buf[4096];
  217. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
  218. buf, lenof(buf), NULL);
  219. buf[lenof(buf)-1] = '\0';
  220. if (buf[strlen(buf)-1] == '\n')
  221. buf[strlen(buf)-1] = '\0';
  222. fprintf(stderr, "Unable to write to standard %s: %s\n",
  223. (h == stdout_handle ? "output" : "error"), buf);
  224. cleanup_exit(0);
  225. }
  226. if (backend_connected(backend)) {
  227. backend_unthrottle(backend, (handle_backlog(stdout_handle) +
  228. handle_backlog(stderr_handle)));
  229. }
  230. }
  231. const bool share_can_be_downstream = true;
  232. const bool share_can_be_upstream = true;
  233. const unsigned cmdline_tooltype =
  234. TOOLTYPE_HOST_ARG |
  235. TOOLTYPE_HOST_ARG_CAN_BE_SESSION |
  236. TOOLTYPE_HOST_ARG_PROTOCOL_PREFIX |
  237. TOOLTYPE_HOST_ARG_FROM_LAUNCHABLE_LOAD;
  238. static bool sending;
  239. static bool plink_mainloop_pre(void *vctx, const HANDLE **extra_handles,
  240. size_t *n_extra_handles)
  241. {
  242. if (!sending && backend_sendok(backend)) {
  243. stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
  244. 0);
  245. sending = true;
  246. }
  247. return true;
  248. }
  249. static bool plink_mainloop_post(void *vctx, size_t extra_handle_index)
  250. {
  251. if (sending)
  252. handle_unthrottle(stdin_handle, backend_sendbuffer(backend));
  253. if (!backend_connected(backend) &&
  254. handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
  255. return false; /* we closed the connection */
  256. return true;
  257. }
  258. int main(int argc, char **argv)
  259. {
  260. int exitcode;
  261. bool errors;
  262. bool use_subsystem = false;
  263. bool just_test_share_exists = false;
  264. enum TriState sanitise_stdout = AUTO, sanitise_stderr = AUTO;
  265. const struct BackendVtable *vt;
  266. dll_hijacking_protection();
  267. enable_dit();
  268. /*
  269. * Initialise port and protocol to sensible defaults. (These
  270. * will be overridden by more or less anything.)
  271. */
  272. settings_set_default_protocol(PROT_SSH);
  273. settings_set_default_port(22);
  274. /*
  275. * Process the command line.
  276. */
  277. conf = conf_new();
  278. do_defaults(NULL, conf);
  279. settings_set_default_protocol(conf_get_int(conf, CONF_protocol));
  280. settings_set_default_port(conf_get_int(conf, CONF_port));
  281. errors = false;
  282. {
  283. /*
  284. * Override the default protocol if PLINK_PROTOCOL is set.
  285. */
  286. char *p = getenv("PLINK_PROTOCOL");
  287. if (p) {
  288. const struct BackendVtable *vt = backend_vt_from_name(p);
  289. if (vt) {
  290. settings_set_default_protocol(vt->protocol);
  291. settings_set_default_port(vt->default_port);
  292. conf_set_int(conf, CONF_protocol, vt->protocol);
  293. conf_set_int(conf, CONF_port, vt->default_port);
  294. }
  295. }
  296. }
  297. CmdlineArgList *arglist = cmdline_arg_list_from_GetCommandLineW();
  298. size_t arglistpos = 0;
  299. while (arglist->args[arglistpos]) {
  300. CmdlineArg *arg = arglist->args[arglistpos++];
  301. CmdlineArg *nextarg = arglist->args[arglistpos];
  302. const char *p = cmdline_arg_to_str(arg);
  303. int ret = cmdline_process_param(arg, nextarg, 1, conf);
  304. if (ret == -2) {
  305. fprintf(stderr,
  306. "plink: option \"%s\" requires an argument\n", p);
  307. errors = true;
  308. } else if (ret == 2) {
  309. arglistpos++;
  310. } else if (ret == 1) {
  311. continue;
  312. } else if (!strcmp(p, "-s")) {
  313. /* Save status to write to conf later. */
  314. use_subsystem = true;
  315. } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
  316. version();
  317. } else if (!strcmp(p, "--help")) {
  318. usage();
  319. exit(0);
  320. } else if (!strcmp(p, "-pgpfp")) {
  321. pgp_fingerprints();
  322. exit(0);
  323. } else if (!strcmp(p, "-shareexists")) {
  324. just_test_share_exists = true;
  325. } else if (!strcmp(p, "-sanitise-stdout") ||
  326. !strcmp(p, "-sanitize-stdout")) {
  327. sanitise_stdout = FORCE_ON;
  328. } else if (!strcmp(p, "-no-sanitise-stdout") ||
  329. !strcmp(p, "-no-sanitize-stdout")) {
  330. sanitise_stdout = FORCE_OFF;
  331. } else if (!strcmp(p, "-sanitise-stderr") ||
  332. !strcmp(p, "-sanitize-stderr")) {
  333. sanitise_stderr = FORCE_ON;
  334. } else if (!strcmp(p, "-no-sanitise-stderr") ||
  335. !strcmp(p, "-no-sanitize-stderr")) {
  336. sanitise_stderr = FORCE_OFF;
  337. } else if (!strcmp(p, "-no-antispoof")) {
  338. console_antispoof_prompt = false;
  339. } else if (*p != '-') {
  340. strbuf *cmdbuf = strbuf_new();
  341. while (arg) {
  342. if (cmdbuf->len > 0)
  343. put_byte(cmdbuf, ' '); /* add space separator */
  344. put_dataz(cmdbuf, cmdline_arg_to_utf8(arg));
  345. arg = arglist->args[arglistpos++];
  346. }
  347. conf_set_str(conf, CONF_remote_cmd, cmdbuf->s);
  348. conf_set_str(conf, CONF_remote_cmd2, "");
  349. conf_set_bool(conf, CONF_nopty, true); /* command => no tty */
  350. strbuf_free(cmdbuf);
  351. break; /* done with cmdline */
  352. } else {
  353. fprintf(stderr, "plink: unknown option \"%s\"\n", p);
  354. errors = true;
  355. }
  356. }
  357. if (errors)
  358. return 1;
  359. if (!cmdline_host_ok(conf)) {
  360. fprintf(stderr, "plink: no valid host name provided\n"
  361. "try \"plink --help\" for help\n");
  362. cmdline_arg_list_free(arglist);
  363. return 1;
  364. }
  365. prepare_session(conf);
  366. /*
  367. * Perform command-line overrides on session configuration.
  368. */
  369. cmdline_run_saved(conf);
  370. /*
  371. * Apply subsystem status.
  372. */
  373. if (use_subsystem)
  374. conf_set_bool(conf, CONF_ssh_subsys, true);
  375. /*
  376. * Select protocol. This is farmed out into a table in a
  377. * separate file to enable an ssh-free variant.
  378. */
  379. vt = backend_vt_from_proto(conf_get_int(conf, CONF_protocol));
  380. if (vt == NULL) {
  381. fprintf(stderr,
  382. "Internal fault: Unsupported protocol found\n");
  383. return 1;
  384. }
  385. if (vt->flags & BACKEND_NEEDS_TERMINAL) {
  386. fprintf(stderr,
  387. "Plink doesn't support %s, which needs terminal emulation\n",
  388. vt->displayname_lc);
  389. return 1;
  390. }
  391. sk_init();
  392. if (p_WSAEventSelect == NULL) {
  393. fprintf(stderr, "Plink requires WinSock 2\n");
  394. return 1;
  395. }
  396. /*
  397. * Plink doesn't provide any way to add forwardings after the
  398. * connection is set up, so if there are none now, we can safely set
  399. * the "simple" flag.
  400. */
  401. if (conf_get_int(conf, CONF_protocol) == PROT_SSH &&
  402. !conf_get_bool(conf, CONF_x11_forward) &&
  403. !conf_get_bool(conf, CONF_agentfwd) &&
  404. !conf_get_str_nthstrkey(conf, CONF_portfwd, 0))
  405. conf_set_bool(conf, CONF_ssh_simple, true);
  406. logctx = log_init(console_cli_logpolicy, conf);
  407. if (just_test_share_exists) {
  408. if (!vt->test_for_upstream) {
  409. fprintf(stderr, "Connection sharing not supported for this "
  410. "connection type (%s)'\n", vt->displayname_lc);
  411. return 1;
  412. }
  413. if (vt->test_for_upstream(conf_get_str(conf, CONF_host),
  414. conf_get_int(conf, CONF_port), conf))
  415. return 0;
  416. else
  417. return 1;
  418. }
  419. if (restricted_acl()) {
  420. lp_eventlog(console_cli_logpolicy,
  421. "Running with restricted process ACL");
  422. }
  423. inhandle = GetStdHandle(STD_INPUT_HANDLE);
  424. outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
  425. errhandle = GetStdHandle(STD_ERROR_HANDLE);
  426. /*
  427. * Turn off ECHO and LINE input modes. We don't care if this
  428. * call fails, because we know we aren't necessarily running in
  429. * a console.
  430. */
  431. GetConsoleMode(inhandle, &orig_console_mode);
  432. SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
  433. /*
  434. * Pass the output handles to the handle-handling subsystem.
  435. * (The input one we leave until we're through the
  436. * authentication process.)
  437. */
  438. stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
  439. stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
  440. handle_sink_init(&stdout_hs, stdout_handle);
  441. handle_sink_init(&stderr_hs, stderr_handle);
  442. stdout_bs = BinarySink_UPCAST(&stdout_hs);
  443. stderr_bs = BinarySink_UPCAST(&stderr_hs);
  444. /*
  445. * Decide whether to sanitise control sequences out of standard
  446. * output and standard error.
  447. *
  448. * If we weren't given a command-line override, we do this if (a)
  449. * the fd in question is pointing at a console, and (b) we aren't
  450. * trying to allocate a terminal as part of the session.
  451. *
  452. * (Rationale: the risk of control sequences is that they cause
  453. * confusion when sent to a local console, so if there isn't one,
  454. * no problem. Also, if we allocate a remote terminal, then we
  455. * sent a terminal type, i.e. we told it what kind of escape
  456. * sequences we _like_, i.e. we were expecting to receive some.)
  457. */
  458. if (sanitise_stdout == FORCE_ON ||
  459. (sanitise_stdout == AUTO && is_console_handle(outhandle) &&
  460. conf_get_bool(conf, CONF_nopty))) {
  461. stdout_scc = stripctrl_new(stdout_bs, true, L'\0');
  462. stdout_bs = BinarySink_UPCAST(stdout_scc);
  463. }
  464. if (sanitise_stderr == FORCE_ON ||
  465. (sanitise_stderr == AUTO && is_console_handle(errhandle) &&
  466. conf_get_bool(conf, CONF_nopty))) {
  467. stderr_scc = stripctrl_new(stderr_bs, true, L'\0');
  468. stderr_bs = BinarySink_UPCAST(stderr_scc);
  469. }
  470. /*
  471. * Start up the connection.
  472. */
  473. winselcli_setup(); /* ensure event object exists */
  474. {
  475. char *error, *realhost;
  476. /* nodelay is only useful if stdin is a character device (console) */
  477. bool nodelay = conf_get_bool(conf, CONF_tcp_nodelay) &&
  478. (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
  479. error = backend_init(vt, plink_seat, &backend, logctx, conf,
  480. conf_get_str(conf, CONF_host),
  481. conf_get_int(conf, CONF_port),
  482. &realhost, nodelay,
  483. conf_get_bool(conf, CONF_tcp_keepalives));
  484. if (error) {
  485. fprintf(stderr, "Unable to open connection:\n%s", error);
  486. sfree(error);
  487. return 1;
  488. }
  489. ldisc_create(conf, NULL, backend, plink_seat);
  490. sfree(realhost);
  491. }
  492. main_thread_id = GetCurrentThreadId();
  493. sending = false;
  494. cli_main_loop(plink_mainloop_pre, plink_mainloop_post, NULL);
  495. exitcode = backend_exitcode(backend);
  496. if (exitcode < 0) {
  497. fprintf(stderr, "Remote process exit code unavailable\n");
  498. exitcode = 1; /* this is an error condition */
  499. }
  500. cleanup_exit(exitcode);
  501. return 0; /* placate compiler warning */
  502. }