plink.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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(conf, CONF_remote_cmd) &&
  73. !*conf_get_str(conf, CONF_remote_cmd2) &&
  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. exit(1);
  177. }
  178. static void version(void)
  179. {
  180. char *buildinfo_text = buildinfo("\n");
  181. printf("plink: %s\n%s\n", ver, buildinfo_text);
  182. sfree(buildinfo_text);
  183. exit(0);
  184. }
  185. size_t stdin_gotdata(struct handle *h, const void *data, size_t len, int err)
  186. {
  187. if (err) {
  188. char buf[4096];
  189. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
  190. buf, lenof(buf), NULL);
  191. buf[lenof(buf)-1] = '\0';
  192. if (buf[strlen(buf)-1] == '\n')
  193. buf[strlen(buf)-1] = '\0';
  194. fprintf(stderr, "Unable to read from standard input: %s\n", buf);
  195. cleanup_exit(0);
  196. }
  197. noise_ultralight(NOISE_SOURCE_IOLEN, len);
  198. if (backend_connected(backend)) {
  199. if (len > 0) {
  200. backend_send(backend, data, len);
  201. return backend_sendbuffer(backend);
  202. } else {
  203. backend_special(backend, SS_EOF, 0);
  204. return 0;
  205. }
  206. } else
  207. return 0;
  208. }
  209. void stdouterr_sent(struct handle *h, size_t new_backlog, int err, bool close)
  210. {
  211. if (close) {
  212. CloseHandle(outhandle);
  213. CloseHandle(errhandle);
  214. outhandle = errhandle = INVALID_HANDLE_VALUE;
  215. }
  216. if (err) {
  217. char buf[4096];
  218. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
  219. buf, lenof(buf), NULL);
  220. buf[lenof(buf)-1] = '\0';
  221. if (buf[strlen(buf)-1] == '\n')
  222. buf[strlen(buf)-1] = '\0';
  223. fprintf(stderr, "Unable to write to standard %s: %s\n",
  224. (h == stdout_handle ? "output" : "error"), buf);
  225. cleanup_exit(0);
  226. }
  227. if (backend_connected(backend)) {
  228. backend_unthrottle(backend, (handle_backlog(stdout_handle) +
  229. handle_backlog(stderr_handle)));
  230. }
  231. }
  232. const bool share_can_be_downstream = true;
  233. const bool share_can_be_upstream = true;
  234. const unsigned cmdline_tooltype =
  235. TOOLTYPE_HOST_ARG |
  236. TOOLTYPE_HOST_ARG_CAN_BE_SESSION |
  237. TOOLTYPE_HOST_ARG_PROTOCOL_PREFIX |
  238. TOOLTYPE_HOST_ARG_FROM_LAUNCHABLE_LOAD;
  239. static bool sending;
  240. static bool plink_mainloop_pre(void *vctx, const HANDLE **extra_handles,
  241. size_t *n_extra_handles)
  242. {
  243. if (!sending && backend_sendok(backend)) {
  244. stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
  245. 0);
  246. sending = true;
  247. }
  248. return true;
  249. }
  250. static bool plink_mainloop_post(void *vctx, size_t extra_handle_index)
  251. {
  252. if (sending)
  253. handle_unthrottle(stdin_handle, backend_sendbuffer(backend));
  254. if (!backend_connected(backend) &&
  255. handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
  256. return false; /* we closed the connection */
  257. return true;
  258. }
  259. int main(int argc, char **argv)
  260. {
  261. int exitcode;
  262. bool errors;
  263. bool use_subsystem = false;
  264. bool just_test_share_exists = false;
  265. enum TriState sanitise_stdout = AUTO, sanitise_stderr = AUTO;
  266. const struct BackendVtable *vt;
  267. dll_hijacking_protection();
  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. while (--argc) {
  298. char *p = *++argv;
  299. int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
  300. 1, conf);
  301. if (ret == -2) {
  302. fprintf(stderr,
  303. "plink: option \"%s\" requires an argument\n", p);
  304. errors = true;
  305. } else if (ret == 2) {
  306. --argc, ++argv;
  307. } else if (ret == 1) {
  308. continue;
  309. } else if (!strcmp(p, "-s")) {
  310. /* Save status to write to conf later. */
  311. use_subsystem = true;
  312. } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
  313. version();
  314. } else if (!strcmp(p, "--help")) {
  315. usage();
  316. } else if (!strcmp(p, "-pgpfp")) {
  317. pgp_fingerprints();
  318. exit(1);
  319. } else if (!strcmp(p, "-shareexists")) {
  320. just_test_share_exists = true;
  321. } else if (!strcmp(p, "-sanitise-stdout") ||
  322. !strcmp(p, "-sanitize-stdout")) {
  323. sanitise_stdout = FORCE_ON;
  324. } else if (!strcmp(p, "-no-sanitise-stdout") ||
  325. !strcmp(p, "-no-sanitize-stdout")) {
  326. sanitise_stdout = FORCE_OFF;
  327. } else if (!strcmp(p, "-sanitise-stderr") ||
  328. !strcmp(p, "-sanitize-stderr")) {
  329. sanitise_stderr = FORCE_ON;
  330. } else if (!strcmp(p, "-no-sanitise-stderr") ||
  331. !strcmp(p, "-no-sanitize-stderr")) {
  332. sanitise_stderr = FORCE_OFF;
  333. } else if (!strcmp(p, "-no-antispoof")) {
  334. console_antispoof_prompt = false;
  335. } else if (*p != '-') {
  336. strbuf *cmdbuf = strbuf_new();
  337. while (argc > 0) {
  338. if (cmdbuf->len > 0)
  339. put_byte(cmdbuf, ' '); /* add space separator */
  340. put_dataz(cmdbuf, p);
  341. if (--argc > 0)
  342. p = *++argv;
  343. }
  344. conf_set_str(conf, CONF_remote_cmd, cmdbuf->s);
  345. conf_set_str(conf, CONF_remote_cmd2, "");
  346. conf_set_bool(conf, CONF_nopty, true); /* command => no tty */
  347. strbuf_free(cmdbuf);
  348. break; /* done with cmdline */
  349. } else {
  350. fprintf(stderr, "plink: unknown option \"%s\"\n", p);
  351. errors = true;
  352. }
  353. }
  354. if (errors)
  355. return 1;
  356. if (!cmdline_host_ok(conf)) {
  357. usage();
  358. }
  359. prepare_session(conf);
  360. /*
  361. * Perform command-line overrides on session configuration.
  362. */
  363. cmdline_run_saved(conf);
  364. /*
  365. * Apply subsystem status.
  366. */
  367. if (use_subsystem)
  368. conf_set_bool(conf, CONF_ssh_subsys, true);
  369. /*
  370. * Select protocol. This is farmed out into a table in a
  371. * separate file to enable an ssh-free variant.
  372. */
  373. vt = backend_vt_from_proto(conf_get_int(conf, CONF_protocol));
  374. if (vt == NULL) {
  375. fprintf(stderr,
  376. "Internal fault: Unsupported protocol found\n");
  377. return 1;
  378. }
  379. if (vt->flags & BACKEND_NEEDS_TERMINAL) {
  380. fprintf(stderr,
  381. "Plink doesn't support %s, which needs terminal emulation\n",
  382. vt->displayname_lc);
  383. return 1;
  384. }
  385. sk_init();
  386. if (p_WSAEventSelect == NULL) {
  387. fprintf(stderr, "Plink requires WinSock 2\n");
  388. return 1;
  389. }
  390. /*
  391. * Plink doesn't provide any way to add forwardings after the
  392. * connection is set up, so if there are none now, we can safely set
  393. * the "simple" flag.
  394. */
  395. if (conf_get_int(conf, CONF_protocol) == PROT_SSH &&
  396. !conf_get_bool(conf, CONF_x11_forward) &&
  397. !conf_get_bool(conf, CONF_agentfwd) &&
  398. !conf_get_str_nthstrkey(conf, CONF_portfwd, 0))
  399. conf_set_bool(conf, CONF_ssh_simple, true);
  400. logctx = log_init(console_cli_logpolicy, conf);
  401. if (just_test_share_exists) {
  402. if (!vt->test_for_upstream) {
  403. fprintf(stderr, "Connection sharing not supported for this "
  404. "connection type (%s)'\n", vt->displayname_lc);
  405. return 1;
  406. }
  407. if (vt->test_for_upstream(conf_get_str(conf, CONF_host),
  408. conf_get_int(conf, CONF_port), conf))
  409. return 0;
  410. else
  411. return 1;
  412. }
  413. if (restricted_acl()) {
  414. lp_eventlog(console_cli_logpolicy,
  415. "Running with restricted process ACL");
  416. }
  417. inhandle = GetStdHandle(STD_INPUT_HANDLE);
  418. outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
  419. errhandle = GetStdHandle(STD_ERROR_HANDLE);
  420. /*
  421. * Turn off ECHO and LINE input modes. We don't care if this
  422. * call fails, because we know we aren't necessarily running in
  423. * a console.
  424. */
  425. GetConsoleMode(inhandle, &orig_console_mode);
  426. SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
  427. /*
  428. * Pass the output handles to the handle-handling subsystem.
  429. * (The input one we leave until we're through the
  430. * authentication process.)
  431. */
  432. stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
  433. stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
  434. handle_sink_init(&stdout_hs, stdout_handle);
  435. handle_sink_init(&stderr_hs, stderr_handle);
  436. stdout_bs = BinarySink_UPCAST(&stdout_hs);
  437. stderr_bs = BinarySink_UPCAST(&stderr_hs);
  438. /*
  439. * Decide whether to sanitise control sequences out of standard
  440. * output and standard error.
  441. *
  442. * If we weren't given a command-line override, we do this if (a)
  443. * the fd in question is pointing at a console, and (b) we aren't
  444. * trying to allocate a terminal as part of the session.
  445. *
  446. * (Rationale: the risk of control sequences is that they cause
  447. * confusion when sent to a local console, so if there isn't one,
  448. * no problem. Also, if we allocate a remote terminal, then we
  449. * sent a terminal type, i.e. we told it what kind of escape
  450. * sequences we _like_, i.e. we were expecting to receive some.)
  451. */
  452. if (sanitise_stdout == FORCE_ON ||
  453. (sanitise_stdout == AUTO && is_console_handle(outhandle) &&
  454. conf_get_bool(conf, CONF_nopty))) {
  455. stdout_scc = stripctrl_new(stdout_bs, true, L'\0');
  456. stdout_bs = BinarySink_UPCAST(stdout_scc);
  457. }
  458. if (sanitise_stderr == FORCE_ON ||
  459. (sanitise_stderr == AUTO && is_console_handle(errhandle) &&
  460. conf_get_bool(conf, CONF_nopty))) {
  461. stderr_scc = stripctrl_new(stderr_bs, true, L'\0');
  462. stderr_bs = BinarySink_UPCAST(stderr_scc);
  463. }
  464. /*
  465. * Start up the connection.
  466. */
  467. winselcli_setup(); /* ensure event object exists */
  468. {
  469. char *error, *realhost;
  470. /* nodelay is only useful if stdin is a character device (console) */
  471. bool nodelay = conf_get_bool(conf, CONF_tcp_nodelay) &&
  472. (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
  473. error = backend_init(vt, plink_seat, &backend, logctx, conf,
  474. conf_get_str(conf, CONF_host),
  475. conf_get_int(conf, CONF_port),
  476. &realhost, nodelay,
  477. conf_get_bool(conf, CONF_tcp_keepalives));
  478. if (error) {
  479. fprintf(stderr, "Unable to open connection:\n%s", error);
  480. sfree(error);
  481. return 1;
  482. }
  483. ldisc_create(conf, NULL, backend, plink_seat);
  484. sfree(realhost);
  485. }
  486. main_thread_id = GetCurrentThreadId();
  487. sending = false;
  488. cli_main_loop(plink_mainloop_pre, plink_mainloop_post, NULL);
  489. exitcode = backend_exitcode(backend);
  490. if (exitcode < 0) {
  491. fprintf(stderr, "Remote process exit code unavailable\n");
  492. exitcode = 1; /* this is an error condition */
  493. }
  494. cleanup_exit(exitcode);
  495. return 0; /* placate compiler warning */
  496. }