1 /* $OpenBSD: clientloop.c,v 1.258 2014/02/02 03:44:31 djm Exp $ */
2 /*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * The main loop for the interactive session (client side).
7 *
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
13 *
14 *
15 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
19 * are met:
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 *
37 *
38 * SSH2 support added by Markus Friedl.
39 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
40 *
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
43 * are met:
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
51 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
52 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
53 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
54 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
55 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
56 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
57 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
58 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
59 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
60 */
61
62 #include "includes.h"
63 __RCSID("$FreeBSD$");
64
65 #include <sys/types.h>
66 #include <sys/ioctl.h>
67 #include <sys/param.h>
68 #ifdef HAVE_SYS_STAT_H
69 # include <sys/stat.h>
70 #endif
71 #ifdef HAVE_SYS_TIME_H
72 # include <sys/time.h>
73 #endif
74 #include <sys/socket.h>
75
76 #include <ctype.h>
77 #include <errno.h>
78 #ifdef HAVE_PATHS_H
79 #include <paths.h>
80 #endif
81 #include <signal.h>
82 #include <stdarg.h>
83 #include <stdio.h>
84 #include <stdlib.h>
85 #include <string.h>
86 #include <termios.h>
87 #include <pwd.h>
88 #include <unistd.h>
89
90 #include "openbsd-compat/sys-queue.h"
91 #include "xmalloc.h"
92 #include "ssh.h"
93 #include "ssh1.h"
94 #include "ssh2.h"
95 #include "packet.h"
96 #include "buffer.h"
97 #include "compat.h"
98 #include "channels.h"
99 #include "dispatch.h"
100 #include "key.h"
101 #include "cipher.h"
102 #include "kex.h"
103 #include "log.h"
104 #include "readconf.h"
105 #include "clientloop.h"
106 #include "sshconnect.h"
107 #include "authfd.h"
108 #include "atomicio.h"
109 #include "sshpty.h"
110 #include "misc.h"
111 #include "match.h"
112 #include "msg.h"
113 #include "roaming.h"
114
115 /* import options */
116 extern Options options;
117
118 /* Flag indicating that stdin should be redirected from /dev/null. */
119 extern int stdin_null_flag;
120
121 /* Flag indicating that no shell has been requested */
122 extern int no_shell_flag;
123
124 /* Control socket */
125 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
126
127 /*
128 * Name of the host we are connecting to. This is the name given on the
129 * command line, or the HostName specified for the user-supplied name in a
130 * configuration file.
131 */
132 extern char *host;
133
134 /*
135 * Flag to indicate that we have received a window change signal which has
136 * not yet been processed. This will cause a message indicating the new
137 * window size to be sent to the server a little later. This is volatile
138 * because this is updated in a signal handler.
139 */
140 static volatile sig_atomic_t received_window_change_signal = 0;
141 static volatile sig_atomic_t received_signal = 0;
142
143 /* Flag indicating whether the user's terminal is in non-blocking mode. */
144 static int in_non_blocking_mode = 0;
145
146 /* Time when backgrounded control master using ControlPersist should exit */
147 static time_t control_persist_exit_time = 0;
148
149 /* Common data for the client loop code. */
150 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
151 static int escape_char1; /* Escape character. (proto1 only) */
152 static int escape_pending1; /* Last character was an escape (proto1 only) */
153 static int last_was_cr; /* Last character was a newline. */
154 static int exit_status; /* Used to store the command exit status. */
155 static int stdin_eof; /* EOF has been encountered on stderr. */
156 static Buffer stdin_buffer; /* Buffer for stdin data. */
157 static Buffer stdout_buffer; /* Buffer for stdout data. */
158 static Buffer stderr_buffer; /* Buffer for stderr data. */
159 static u_int buffer_high; /* Soft max buffer size. */
160 static int connection_in; /* Connection to server (input). */
161 static int connection_out; /* Connection to server (output). */
162 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
163 static int session_closed; /* In SSH2: login session closed. */
164 static int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
165
166 static void client_init_dispatch(void);
167 int session_ident = -1;
168
169 int session_resumed = 0;
170
171 /* Track escape per proto2 channel */
172 struct escape_filter_ctx {
173 int escape_pending;
174 int escape_char;
175 };
176
177 /* Context for channel confirmation replies */
178 struct channel_reply_ctx {
179 const char *request_type;
180 int id;
181 enum confirm_action action;
182 };
183
184 /* Global request success/failure callbacks */
185 struct global_confirm {
186 TAILQ_ENTRY(global_confirm) entry;
187 global_confirm_cb *cb;
188 void *ctx;
189 int ref_count;
190 };
191 TAILQ_HEAD(global_confirms, global_confirm);
192 static struct global_confirms global_confirms =
193 TAILQ_HEAD_INITIALIZER(global_confirms);
194
195 /*XXX*/
196 extern Kex *xxx_kex;
197
198 void ssh_process_session2_setup(int, int, int, Buffer *);
199
200 /* Restores stdin to blocking mode. */
201
202 static void
leave_non_blocking(void)203 leave_non_blocking(void)
204 {
205 if (in_non_blocking_mode) {
206 unset_nonblock(fileno(stdin));
207 in_non_blocking_mode = 0;
208 }
209 }
210
211 /* Puts stdin terminal in non-blocking mode. */
212
213 static void
enter_non_blocking(void)214 enter_non_blocking(void)
215 {
216 in_non_blocking_mode = 1;
217 set_nonblock(fileno(stdin));
218 }
219
220 /*
221 * Signal handler for the window change signal (SIGWINCH). This just sets a
222 * flag indicating that the window has changed.
223 */
224 /*ARGSUSED */
225 static void
window_change_handler(int sig)226 window_change_handler(int sig)
227 {
228 received_window_change_signal = 1;
229 signal(SIGWINCH, window_change_handler);
230 }
231
232 /*
233 * Signal handler for signals that cause the program to terminate. These
234 * signals must be trapped to restore terminal modes.
235 */
236 /*ARGSUSED */
237 static void
signal_handler(int sig)238 signal_handler(int sig)
239 {
240 received_signal = sig;
241 quit_pending = 1;
242 }
243
244 /*
245 * Returns current time in seconds from Jan 1, 1970 with the maximum
246 * available resolution.
247 */
248
249 static double
get_current_time(void)250 get_current_time(void)
251 {
252 struct timeval tv;
253 gettimeofday(&tv, NULL);
254 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
255 }
256
257 /*
258 * Sets control_persist_exit_time to the absolute time when the
259 * backgrounded control master should exit due to expiry of the
260 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
261 * control master process, or if there is no ControlPersist timeout.
262 */
263 static void
set_control_persist_exit_time(void)264 set_control_persist_exit_time(void)
265 {
266 if (muxserver_sock == -1 || !options.control_persist
267 || options.control_persist_timeout == 0) {
268 /* not using a ControlPersist timeout */
269 control_persist_exit_time = 0;
270 } else if (channel_still_open()) {
271 /* some client connections are still open */
272 if (control_persist_exit_time > 0)
273 debug2("%s: cancel scheduled exit", __func__);
274 control_persist_exit_time = 0;
275 } else if (control_persist_exit_time <= 0) {
276 /* a client connection has recently closed */
277 control_persist_exit_time = monotime() +
278 (time_t)options.control_persist_timeout;
279 debug2("%s: schedule exit in %d seconds", __func__,
280 options.control_persist_timeout);
281 }
282 /* else we are already counting down to the timeout */
283 }
284
285 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
286 static int
client_x11_display_valid(const char * display)287 client_x11_display_valid(const char *display)
288 {
289 size_t i, dlen;
290
291 dlen = strlen(display);
292 for (i = 0; i < dlen; i++) {
293 if (!isalnum((u_char)display[i]) &&
294 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
295 debug("Invalid character '%c' in DISPLAY", display[i]);
296 return 0;
297 }
298 }
299 return 1;
300 }
301
302 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
303 void
client_x11_get_proto(const char * display,const char * xauth_path,u_int trusted,u_int timeout,char ** _proto,char ** _data)304 client_x11_get_proto(const char *display, const char *xauth_path,
305 u_int trusted, u_int timeout, char **_proto, char **_data)
306 {
307 char cmd[1024];
308 char line[512];
309 char xdisplay[512];
310 static char proto[512], data[512];
311 FILE *f;
312 int got_data = 0, generated = 0, do_unlink = 0, i;
313 char *xauthdir, *xauthfile;
314 struct stat st;
315 u_int now;
316
317 xauthdir = xauthfile = NULL;
318 *_proto = proto;
319 *_data = data;
320 proto[0] = data[0] = '\0';
321
322 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
323 debug("No xauth program.");
324 } else if (!client_x11_display_valid(display)) {
325 logit("DISPLAY '%s' invalid, falling back to fake xauth data",
326 display);
327 } else {
328 if (display == NULL) {
329 debug("x11_get_proto: DISPLAY not set");
330 return;
331 }
332 /*
333 * Handle FamilyLocal case where $DISPLAY does
334 * not match an authorization entry. For this we
335 * just try "xauth list unix:displaynum.screennum".
336 * XXX: "localhost" match to determine FamilyLocal
337 * is not perfect.
338 */
339 if (strncmp(display, "localhost:", 10) == 0) {
340 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
341 display + 10);
342 display = xdisplay;
343 }
344 if (trusted == 0) {
345 xauthdir = xmalloc(MAXPATHLEN);
346 xauthfile = xmalloc(MAXPATHLEN);
347 mktemp_proto(xauthdir, MAXPATHLEN);
348 if (mkdtemp(xauthdir) != NULL) {
349 do_unlink = 1;
350 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
351 xauthdir);
352 snprintf(cmd, sizeof(cmd),
353 "%s -f %s generate %s " SSH_X11_PROTO
354 " untrusted timeout %u 2>" _PATH_DEVNULL,
355 xauth_path, xauthfile, display, timeout);
356 debug2("x11_get_proto: %s", cmd);
357 if (system(cmd) == 0)
358 generated = 1;
359 if (x11_refuse_time == 0) {
360 now = monotime() + 1;
361 if (UINT_MAX - timeout < now)
362 x11_refuse_time = UINT_MAX;
363 else
364 x11_refuse_time = now + timeout;
365 }
366 }
367 }
368
369 /*
370 * When in untrusted mode, we read the cookie only if it was
371 * successfully generated as an untrusted one in the step
372 * above.
373 */
374 if (trusted || generated) {
375 snprintf(cmd, sizeof(cmd),
376 "%s %s%s list %s 2>" _PATH_DEVNULL,
377 xauth_path,
378 generated ? "-f " : "" ,
379 generated ? xauthfile : "",
380 display);
381 debug2("x11_get_proto: %s", cmd);
382 f = popen(cmd, "r");
383 if (f && fgets(line, sizeof(line), f) &&
384 sscanf(line, "%*s %511s %511s", proto, data) == 2)
385 got_data = 1;
386 if (f)
387 pclose(f);
388 } else
389 error("Warning: untrusted X11 forwarding setup failed: "
390 "xauth key data not generated");
391 }
392
393 if (do_unlink) {
394 unlink(xauthfile);
395 rmdir(xauthdir);
396 }
397 free(xauthdir);
398 free(xauthfile);
399
400 /*
401 * If we didn't get authentication data, just make up some
402 * data. The forwarding code will check the validity of the
403 * response anyway, and substitute this data. The X11
404 * server, however, will ignore this fake data and use
405 * whatever authentication mechanisms it was using otherwise
406 * for the local connection.
407 */
408 if (!got_data) {
409 u_int32_t rnd = 0;
410
411 logit("Warning: No xauth data; "
412 "using fake authentication data for X11 forwarding.");
413 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
414 for (i = 0; i < 16; i++) {
415 if (i % 4 == 0)
416 rnd = arc4random();
417 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
418 rnd & 0xff);
419 rnd >>= 8;
420 }
421 }
422 }
423
424 /*
425 * This is called when the interactive is entered. This checks if there is
426 * an EOF coming on stdin. We must check this explicitly, as select() does
427 * not appear to wake up when redirecting from /dev/null.
428 */
429
430 static void
client_check_initial_eof_on_stdin(void)431 client_check_initial_eof_on_stdin(void)
432 {
433 int len;
434 char buf[1];
435
436 /*
437 * If standard input is to be "redirected from /dev/null", we simply
438 * mark that we have seen an EOF and send an EOF message to the
439 * server. Otherwise, we try to read a single character; it appears
440 * that for some files, such /dev/null, select() never wakes up for
441 * read for this descriptor, which means that we never get EOF. This
442 * way we will get the EOF if stdin comes from /dev/null or similar.
443 */
444 if (stdin_null_flag) {
445 /* Fake EOF on stdin. */
446 debug("Sending eof.");
447 stdin_eof = 1;
448 packet_start(SSH_CMSG_EOF);
449 packet_send();
450 } else {
451 enter_non_blocking();
452
453 /* Check for immediate EOF on stdin. */
454 len = read(fileno(stdin), buf, 1);
455 if (len == 0) {
456 /*
457 * EOF. Record that we have seen it and send
458 * EOF to server.
459 */
460 debug("Sending eof.");
461 stdin_eof = 1;
462 packet_start(SSH_CMSG_EOF);
463 packet_send();
464 } else if (len > 0) {
465 /*
466 * Got data. We must store the data in the buffer,
467 * and also process it as an escape character if
468 * appropriate.
469 */
470 if ((u_char) buf[0] == escape_char1)
471 escape_pending1 = 1;
472 else
473 buffer_append(&stdin_buffer, buf, 1);
474 }
475 leave_non_blocking();
476 }
477 }
478
479
480 /*
481 * Make packets from buffered stdin data, and buffer them for sending to the
482 * connection.
483 */
484
485 static void
client_make_packets_from_stdin_data(void)486 client_make_packets_from_stdin_data(void)
487 {
488 u_int len;
489
490 /* Send buffered stdin data to the server. */
491 while (buffer_len(&stdin_buffer) > 0 &&
492 packet_not_very_much_data_to_write()) {
493 len = buffer_len(&stdin_buffer);
494 /* Keep the packets at reasonable size. */
495 if (len > packet_get_maxsize())
496 len = packet_get_maxsize();
497 packet_start(SSH_CMSG_STDIN_DATA);
498 packet_put_string(buffer_ptr(&stdin_buffer), len);
499 packet_send();
500 buffer_consume(&stdin_buffer, len);
501 /* If we have a pending EOF, send it now. */
502 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
503 packet_start(SSH_CMSG_EOF);
504 packet_send();
505 }
506 }
507 }
508
509 /*
510 * Checks if the client window has changed, and sends a packet about it to
511 * the server if so. The actual change is detected elsewhere (by a software
512 * interrupt on Unix); this just checks the flag and sends a message if
513 * appropriate.
514 */
515
516 static void
client_check_window_change(void)517 client_check_window_change(void)
518 {
519 struct winsize ws;
520
521 if (! received_window_change_signal)
522 return;
523 /** XXX race */
524 received_window_change_signal = 0;
525
526 debug2("client_check_window_change: changed");
527
528 if (compat20) {
529 channel_send_window_changes();
530 } else {
531 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
532 return;
533 packet_start(SSH_CMSG_WINDOW_SIZE);
534 packet_put_int((u_int)ws.ws_row);
535 packet_put_int((u_int)ws.ws_col);
536 packet_put_int((u_int)ws.ws_xpixel);
537 packet_put_int((u_int)ws.ws_ypixel);
538 packet_send();
539 }
540 }
541
542 static void
client_global_request_reply(int type,u_int32_t seq,void * ctxt)543 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
544 {
545 struct global_confirm *gc;
546
547 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
548 return;
549 if (gc->cb != NULL)
550 gc->cb(type, seq, gc->ctx);
551 if (--gc->ref_count <= 0) {
552 TAILQ_REMOVE(&global_confirms, gc, entry);
553 explicit_bzero(gc, sizeof(*gc));
554 free(gc);
555 }
556
557 packet_set_alive_timeouts(0);
558 }
559
560 static void
server_alive_check(void)561 server_alive_check(void)
562 {
563 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
564 logit("Timeout, server %s not responding.", host);
565 cleanup_exit(255);
566 }
567 packet_start(SSH2_MSG_GLOBAL_REQUEST);
568 packet_put_cstring("keepalive@openssh.com");
569 packet_put_char(1); /* boolean: want reply */
570 packet_send();
571 /* Insert an empty placeholder to maintain ordering */
572 client_register_global_confirm(NULL, NULL);
573 }
574
575 /*
576 * Waits until the client can do something (some data becomes available on
577 * one of the file descriptors).
578 */
579 static void
client_wait_until_can_do_something(fd_set ** readsetp,fd_set ** writesetp,int * maxfdp,u_int * nallocp,int rekeying)580 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
581 int *maxfdp, u_int *nallocp, int rekeying)
582 {
583 struct timeval tv, *tvp;
584 int timeout_secs;
585 time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
586 int ret;
587
588 /* Add any selections by the channel mechanism. */
589 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
590 &minwait_secs, rekeying);
591
592 if (!compat20) {
593 /* Read from the connection, unless our buffers are full. */
594 if (buffer_len(&stdout_buffer) < buffer_high &&
595 buffer_len(&stderr_buffer) < buffer_high &&
596 channel_not_very_much_buffered_data())
597 FD_SET(connection_in, *readsetp);
598 /*
599 * Read from stdin, unless we have seen EOF or have very much
600 * buffered data to send to the server.
601 */
602 if (!stdin_eof && packet_not_very_much_data_to_write())
603 FD_SET(fileno(stdin), *readsetp);
604
605 /* Select stdout/stderr if have data in buffer. */
606 if (buffer_len(&stdout_buffer) > 0)
607 FD_SET(fileno(stdout), *writesetp);
608 if (buffer_len(&stderr_buffer) > 0)
609 FD_SET(fileno(stderr), *writesetp);
610 } else {
611 /* channel_prepare_select could have closed the last channel */
612 if (session_closed && !channel_still_open() &&
613 !packet_have_data_to_write()) {
614 /* clear mask since we did not call select() */
615 memset(*readsetp, 0, *nallocp);
616 memset(*writesetp, 0, *nallocp);
617 return;
618 } else {
619 FD_SET(connection_in, *readsetp);
620 }
621 }
622
623 /* Select server connection if have data to write to the server. */
624 if (packet_have_data_to_write())
625 FD_SET(connection_out, *writesetp);
626
627 /*
628 * Wait for something to happen. This will suspend the process until
629 * some selected descriptor can be read, written, or has some other
630 * event pending, or a timeout expires.
631 */
632
633 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
634 if (options.server_alive_interval > 0 && compat20) {
635 timeout_secs = options.server_alive_interval;
636 server_alive_time = now + options.server_alive_interval;
637 }
638 if (options.rekey_interval > 0 && compat20 && !rekeying)
639 timeout_secs = MIN(timeout_secs, packet_get_rekey_timeout());
640 set_control_persist_exit_time();
641 if (control_persist_exit_time > 0) {
642 timeout_secs = MIN(timeout_secs,
643 control_persist_exit_time - now);
644 if (timeout_secs < 0)
645 timeout_secs = 0;
646 }
647 if (minwait_secs != 0)
648 timeout_secs = MIN(timeout_secs, (int)minwait_secs);
649 if (timeout_secs == INT_MAX)
650 tvp = NULL;
651 else {
652 tv.tv_sec = timeout_secs;
653 tv.tv_usec = 0;
654 tvp = &tv;
655 }
656
657 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
658 if (ret < 0) {
659 char buf[100];
660
661 /*
662 * We have to clear the select masks, because we return.
663 * We have to return, because the mainloop checks for the flags
664 * set by the signal handlers.
665 */
666 memset(*readsetp, 0, *nallocp);
667 memset(*writesetp, 0, *nallocp);
668
669 if (errno == EINTR)
670 return;
671 /* Note: we might still have data in the buffers. */
672 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
673 buffer_append(&stderr_buffer, buf, strlen(buf));
674 quit_pending = 1;
675 } else if (ret == 0) {
676 /*
677 * Timeout. Could have been either keepalive or rekeying.
678 * Keepalive we check here, rekeying is checked in clientloop.
679 */
680 if (server_alive_time != 0 && server_alive_time <= monotime())
681 server_alive_check();
682 }
683
684 }
685
686 static void
client_suspend_self(Buffer * bin,Buffer * bout,Buffer * berr)687 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
688 {
689 /* Flush stdout and stderr buffers. */
690 if (buffer_len(bout) > 0)
691 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
692 buffer_len(bout));
693 if (buffer_len(berr) > 0)
694 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
695 buffer_len(berr));
696
697 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
698
699 /*
700 * Free (and clear) the buffer to reduce the amount of data that gets
701 * written to swap.
702 */
703 buffer_free(bin);
704 buffer_free(bout);
705 buffer_free(berr);
706
707 /* Send the suspend signal to the program itself. */
708 kill(getpid(), SIGTSTP);
709
710 /* Reset window sizes in case they have changed */
711 received_window_change_signal = 1;
712
713 /* OK, we have been continued by the user. Reinitialize buffers. */
714 buffer_init(bin);
715 buffer_init(bout);
716 buffer_init(berr);
717
718 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
719 }
720
721 static void
client_process_net_input(fd_set * readset)722 client_process_net_input(fd_set *readset)
723 {
724 int len, cont = 0;
725 char buf[SSH_IOBUFSZ];
726
727 /*
728 * Read input from the server, and add any such data to the buffer of
729 * the packet subsystem.
730 */
731 if (FD_ISSET(connection_in, readset)) {
732 /* Read as much as possible. */
733 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
734 if (len == 0 && cont == 0) {
735 /*
736 * Received EOF. The remote host has closed the
737 * connection.
738 */
739 snprintf(buf, sizeof buf,
740 "Connection to %.300s closed by remote host.\r\n",
741 host);
742 buffer_append(&stderr_buffer, buf, strlen(buf));
743 quit_pending = 1;
744 return;
745 }
746 /*
747 * There is a kernel bug on Solaris that causes select to
748 * sometimes wake up even though there is no data available.
749 */
750 if (len < 0 &&
751 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
752 len = 0;
753
754 if (len < 0) {
755 /*
756 * An error has encountered. Perhaps there is a
757 * network problem.
758 */
759 snprintf(buf, sizeof buf,
760 "Read from remote host %.300s: %.100s\r\n",
761 host, strerror(errno));
762 buffer_append(&stderr_buffer, buf, strlen(buf));
763 quit_pending = 1;
764 return;
765 }
766 packet_process_incoming(buf, len);
767 }
768 }
769
770 static void
client_status_confirm(int type,Channel * c,void * ctx)771 client_status_confirm(int type, Channel *c, void *ctx)
772 {
773 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
774 char errmsg[256];
775 int tochan;
776
777 /*
778 * If a TTY was explicitly requested, then a failure to allocate
779 * one is fatal.
780 */
781 if (cr->action == CONFIRM_TTY &&
782 (options.request_tty == REQUEST_TTY_FORCE ||
783 options.request_tty == REQUEST_TTY_YES))
784 cr->action = CONFIRM_CLOSE;
785
786 /* XXX supress on mux _client_ quietmode */
787 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
788 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
789
790 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
791 debug2("%s request accepted on channel %d",
792 cr->request_type, c->self);
793 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
794 if (tochan) {
795 snprintf(errmsg, sizeof(errmsg),
796 "%s request failed\r\n", cr->request_type);
797 } else {
798 snprintf(errmsg, sizeof(errmsg),
799 "%s request failed on channel %d",
800 cr->request_type, c->self);
801 }
802 /* If error occurred on primary session channel, then exit */
803 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
804 fatal("%s", errmsg);
805 /*
806 * If error occurred on mux client, append to
807 * their stderr.
808 */
809 if (tochan) {
810 buffer_append(&c->extended, errmsg,
811 strlen(errmsg));
812 } else
813 error("%s", errmsg);
814 if (cr->action == CONFIRM_TTY) {
815 /*
816 * If a TTY allocation error occurred, then arrange
817 * for the correct TTY to leave raw mode.
818 */
819 if (c->self == session_ident)
820 leave_raw_mode(0);
821 else
822 mux_tty_alloc_failed(c);
823 } else if (cr->action == CONFIRM_CLOSE) {
824 chan_read_failed(c);
825 chan_write_failed(c);
826 }
827 }
828 free(cr);
829 }
830
831 static void
client_abandon_status_confirm(Channel * c,void * ctx)832 client_abandon_status_confirm(Channel *c, void *ctx)
833 {
834 free(ctx);
835 }
836
837 void
client_expect_confirm(int id,const char * request,enum confirm_action action)838 client_expect_confirm(int id, const char *request,
839 enum confirm_action action)
840 {
841 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
842
843 cr->request_type = request;
844 cr->action = action;
845
846 channel_register_status_confirm(id, client_status_confirm,
847 client_abandon_status_confirm, cr);
848 }
849
850 void
client_register_global_confirm(global_confirm_cb * cb,void * ctx)851 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
852 {
853 struct global_confirm *gc, *last_gc;
854
855 /* Coalesce identical callbacks */
856 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
857 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
858 if (++last_gc->ref_count >= INT_MAX)
859 fatal("%s: last_gc->ref_count = %d",
860 __func__, last_gc->ref_count);
861 return;
862 }
863
864 gc = xcalloc(1, sizeof(*gc));
865 gc->cb = cb;
866 gc->ctx = ctx;
867 gc->ref_count = 1;
868 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
869 }
870
871 static void
process_cmdline(void)872 process_cmdline(void)
873 {
874 void (*handler)(int);
875 char *s, *cmd, *cancel_host;
876 int delete = 0, local = 0, remote = 0, dynamic = 0;
877 int cancel_port, ok;
878 Forward fwd;
879
880 memset(&fwd, 0, sizeof(fwd));
881 fwd.listen_host = fwd.connect_host = NULL;
882
883 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
884 handler = signal(SIGINT, SIG_IGN);
885 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
886 if (s == NULL)
887 goto out;
888 while (isspace((u_char)*s))
889 s++;
890 if (*s == '-')
891 s++; /* Skip cmdline '-', if any */
892 if (*s == '\0')
893 goto out;
894
895 if (*s == 'h' || *s == 'H' || *s == '?') {
896 logit("Commands:");
897 logit(" -L[bind_address:]port:host:hostport "
898 "Request local forward");
899 logit(" -R[bind_address:]port:host:hostport "
900 "Request remote forward");
901 logit(" -D[bind_address:]port "
902 "Request dynamic forward");
903 logit(" -KL[bind_address:]port "
904 "Cancel local forward");
905 logit(" -KR[bind_address:]port "
906 "Cancel remote forward");
907 logit(" -KD[bind_address:]port "
908 "Cancel dynamic forward");
909 if (!options.permit_local_command)
910 goto out;
911 logit(" !args "
912 "Execute local command");
913 goto out;
914 }
915
916 if (*s == '!' && options.permit_local_command) {
917 s++;
918 ssh_local_cmd(s);
919 goto out;
920 }
921
922 if (*s == 'K') {
923 delete = 1;
924 s++;
925 }
926 if (*s == 'L')
927 local = 1;
928 else if (*s == 'R')
929 remote = 1;
930 else if (*s == 'D')
931 dynamic = 1;
932 else {
933 logit("Invalid command.");
934 goto out;
935 }
936
937 if (delete && !compat20) {
938 logit("Not supported for SSH protocol version 1.");
939 goto out;
940 }
941
942 while (isspace((u_char)*++s))
943 ;
944
945 /* XXX update list of forwards in options */
946 if (delete) {
947 cancel_port = 0;
948 cancel_host = hpdelim(&s); /* may be NULL */
949 if (s != NULL) {
950 cancel_port = a2port(s);
951 cancel_host = cleanhostname(cancel_host);
952 } else {
953 cancel_port = a2port(cancel_host);
954 cancel_host = NULL;
955 }
956 if (cancel_port <= 0) {
957 logit("Bad forwarding close port");
958 goto out;
959 }
960 if (remote)
961 ok = channel_request_rforward_cancel(cancel_host,
962 cancel_port) == 0;
963 else if (dynamic)
964 ok = channel_cancel_lport_listener(cancel_host,
965 cancel_port, 0, options.gateway_ports) > 0;
966 else
967 ok = channel_cancel_lport_listener(cancel_host,
968 cancel_port, CHANNEL_CANCEL_PORT_STATIC,
969 options.gateway_ports) > 0;
970 if (!ok) {
971 logit("Unkown port forwarding.");
972 goto out;
973 }
974 logit("Canceled forwarding.");
975 } else {
976 if (!parse_forward(&fwd, s, dynamic, remote)) {
977 logit("Bad forwarding specification.");
978 goto out;
979 }
980 if (local || dynamic) {
981 if (!channel_setup_local_fwd_listener(fwd.listen_host,
982 fwd.listen_port, fwd.connect_host,
983 fwd.connect_port, options.gateway_ports)) {
984 logit("Port forwarding failed.");
985 goto out;
986 }
987 } else {
988 if (channel_request_remote_forwarding(fwd.listen_host,
989 fwd.listen_port, fwd.connect_host,
990 fwd.connect_port) < 0) {
991 logit("Port forwarding failed.");
992 goto out;
993 }
994 }
995 logit("Forwarding port.");
996 }
997
998 out:
999 signal(SIGINT, handler);
1000 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1001 free(cmd);
1002 free(fwd.listen_host);
1003 free(fwd.connect_host);
1004 }
1005
1006 /* reasons to suppress output of an escape command in help output */
1007 #define SUPPRESS_NEVER 0 /* never suppress, always show */
1008 #define SUPPRESS_PROTO1 1 /* don't show in protocol 1 sessions */
1009 #define SUPPRESS_MUXCLIENT 2 /* don't show in mux client sessions */
1010 #define SUPPRESS_MUXMASTER 4 /* don't show in mux master sessions */
1011 #define SUPPRESS_SYSLOG 8 /* don't show when logging to syslog */
1012 struct escape_help_text {
1013 const char *cmd;
1014 const char *text;
1015 unsigned int flags;
1016 };
1017 static struct escape_help_text esc_txt[] = {
1018 {".", "terminate session", SUPPRESS_MUXMASTER},
1019 {".", "terminate connection (and any multiplexed sessions)",
1020 SUPPRESS_MUXCLIENT},
1021 {"B", "send a BREAK to the remote system", SUPPRESS_PROTO1},
1022 {"C", "open a command line", SUPPRESS_MUXCLIENT},
1023 {"R", "request rekey", SUPPRESS_PROTO1},
1024 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1025 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
1026 {"#", "list forwarded connections", SUPPRESS_NEVER},
1027 {"&", "background ssh (when waiting for connections to terminate)",
1028 SUPPRESS_MUXCLIENT},
1029 {"?", "this message", SUPPRESS_NEVER},
1030 };
1031
1032 static void
print_escape_help(Buffer * b,int escape_char,int protocol2,int mux_client,int using_stderr)1033 print_escape_help(Buffer *b, int escape_char, int protocol2, int mux_client,
1034 int using_stderr)
1035 {
1036 unsigned int i, suppress_flags;
1037 char string[1024];
1038
1039 snprintf(string, sizeof string, "%c?\r\n"
1040 "Supported escape sequences:\r\n", escape_char);
1041 buffer_append(b, string, strlen(string));
1042
1043 suppress_flags = (protocol2 ? 0 : SUPPRESS_PROTO1) |
1044 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
1045 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1046 (using_stderr ? 0 : SUPPRESS_SYSLOG);
1047
1048 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
1049 if (esc_txt[i].flags & suppress_flags)
1050 continue;
1051 snprintf(string, sizeof string, " %c%-3s - %s\r\n",
1052 escape_char, esc_txt[i].cmd, esc_txt[i].text);
1053 buffer_append(b, string, strlen(string));
1054 }
1055
1056 snprintf(string, sizeof string,
1057 " %c%c - send the escape character by typing it twice\r\n"
1058 "(Note that escapes are only recognized immediately after "
1059 "newline.)\r\n", escape_char, escape_char);
1060 buffer_append(b, string, strlen(string));
1061 }
1062
1063 /*
1064 * Process the characters one by one, call with c==NULL for proto1 case.
1065 */
1066 static int
process_escapes(Channel * c,Buffer * bin,Buffer * bout,Buffer * berr,char * buf,int len)1067 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
1068 char *buf, int len)
1069 {
1070 char string[1024];
1071 pid_t pid;
1072 int bytes = 0;
1073 u_int i;
1074 u_char ch;
1075 char *s;
1076 int *escape_pendingp, escape_char;
1077 struct escape_filter_ctx *efc;
1078
1079 if (c == NULL) {
1080 escape_pendingp = &escape_pending1;
1081 escape_char = escape_char1;
1082 } else {
1083 if (c->filter_ctx == NULL)
1084 return 0;
1085 efc = (struct escape_filter_ctx *)c->filter_ctx;
1086 escape_pendingp = &efc->escape_pending;
1087 escape_char = efc->escape_char;
1088 }
1089
1090 if (len <= 0)
1091 return (0);
1092
1093 for (i = 0; i < (u_int)len; i++) {
1094 /* Get one character at a time. */
1095 ch = buf[i];
1096
1097 if (*escape_pendingp) {
1098 /* We have previously seen an escape character. */
1099 /* Clear the flag now. */
1100 *escape_pendingp = 0;
1101
1102 /* Process the escaped character. */
1103 switch (ch) {
1104 case '.':
1105 /* Terminate the connection. */
1106 snprintf(string, sizeof string, "%c.\r\n",
1107 escape_char);
1108 buffer_append(berr, string, strlen(string));
1109
1110 if (c && c->ctl_chan != -1) {
1111 chan_read_failed(c);
1112 chan_write_failed(c);
1113 if (c->detach_user)
1114 c->detach_user(c->self, NULL);
1115 c->type = SSH_CHANNEL_ABANDONED;
1116 buffer_clear(&c->input);
1117 chan_ibuf_empty(c);
1118 return 0;
1119 } else
1120 quit_pending = 1;
1121 return -1;
1122
1123 case 'Z' - 64:
1124 /* XXX support this for mux clients */
1125 if (c && c->ctl_chan != -1) {
1126 char b[16];
1127 noescape:
1128 if (ch == 'Z' - 64)
1129 snprintf(b, sizeof b, "^Z");
1130 else
1131 snprintf(b, sizeof b, "%c", ch);
1132 snprintf(string, sizeof string,
1133 "%c%s escape not available to "
1134 "multiplexed sessions\r\n",
1135 escape_char, b);
1136 buffer_append(berr, string,
1137 strlen(string));
1138 continue;
1139 }
1140 /* Suspend the program. Inform the user */
1141 snprintf(string, sizeof string,
1142 "%c^Z [suspend ssh]\r\n", escape_char);
1143 buffer_append(berr, string, strlen(string));
1144
1145 /* Restore terminal modes and suspend. */
1146 client_suspend_self(bin, bout, berr);
1147
1148 /* We have been continued. */
1149 continue;
1150
1151 case 'B':
1152 if (compat20) {
1153 snprintf(string, sizeof string,
1154 "%cB\r\n", escape_char);
1155 buffer_append(berr, string,
1156 strlen(string));
1157 channel_request_start(c->self,
1158 "break", 0);
1159 packet_put_int(1000);
1160 packet_send();
1161 }
1162 continue;
1163
1164 case 'R':
1165 if (compat20) {
1166 if (datafellows & SSH_BUG_NOREKEY)
1167 logit("Server does not "
1168 "support re-keying");
1169 else
1170 need_rekeying = 1;
1171 }
1172 continue;
1173
1174 case 'V':
1175 /* FALLTHROUGH */
1176 case 'v':
1177 if (c && c->ctl_chan != -1)
1178 goto noescape;
1179 if (!log_is_on_stderr()) {
1180 snprintf(string, sizeof string,
1181 "%c%c [Logging to syslog]\r\n",
1182 escape_char, ch);
1183 buffer_append(berr, string,
1184 strlen(string));
1185 continue;
1186 }
1187 if (ch == 'V' && options.log_level >
1188 SYSLOG_LEVEL_QUIET)
1189 log_change_level(--options.log_level);
1190 if (ch == 'v' && options.log_level <
1191 SYSLOG_LEVEL_DEBUG3)
1192 log_change_level(++options.log_level);
1193 snprintf(string, sizeof string,
1194 "%c%c [LogLevel %s]\r\n", escape_char, ch,
1195 log_level_name(options.log_level));
1196 buffer_append(berr, string, strlen(string));
1197 continue;
1198
1199 case '&':
1200 if (c && c->ctl_chan != -1)
1201 goto noescape;
1202 /*
1203 * Detach the program (continue to serve
1204 * connections, but put in background and no
1205 * more new connections).
1206 */
1207 /* Restore tty modes. */
1208 leave_raw_mode(
1209 options.request_tty == REQUEST_TTY_FORCE);
1210
1211 /* Stop listening for new connections. */
1212 channel_stop_listening();
1213
1214 snprintf(string, sizeof string,
1215 "%c& [backgrounded]\n", escape_char);
1216 buffer_append(berr, string, strlen(string));
1217
1218 /* Fork into background. */
1219 pid = fork();
1220 if (pid < 0) {
1221 error("fork: %.100s", strerror(errno));
1222 continue;
1223 }
1224 if (pid != 0) { /* This is the parent. */
1225 /* The parent just exits. */
1226 exit(0);
1227 }
1228 /* The child continues serving connections. */
1229 if (compat20) {
1230 buffer_append(bin, "\004", 1);
1231 /* fake EOF on stdin */
1232 return -1;
1233 } else if (!stdin_eof) {
1234 /*
1235 * Sending SSH_CMSG_EOF alone does not
1236 * always appear to be enough. So we
1237 * try to send an EOF character first.
1238 */
1239 packet_start(SSH_CMSG_STDIN_DATA);
1240 packet_put_string("\004", 1);
1241 packet_send();
1242 /* Close stdin. */
1243 stdin_eof = 1;
1244 if (buffer_len(bin) == 0) {
1245 packet_start(SSH_CMSG_EOF);
1246 packet_send();
1247 }
1248 }
1249 continue;
1250
1251 case '?':
1252 print_escape_help(berr, escape_char, compat20,
1253 (c && c->ctl_chan != -1),
1254 log_is_on_stderr());
1255 continue;
1256
1257 case '#':
1258 snprintf(string, sizeof string, "%c#\r\n",
1259 escape_char);
1260 buffer_append(berr, string, strlen(string));
1261 s = channel_open_message();
1262 buffer_append(berr, s, strlen(s));
1263 free(s);
1264 continue;
1265
1266 case 'C':
1267 if (c && c->ctl_chan != -1)
1268 goto noescape;
1269 process_cmdline();
1270 continue;
1271
1272 default:
1273 if (ch != escape_char) {
1274 buffer_put_char(bin, escape_char);
1275 bytes++;
1276 }
1277 /* Escaped characters fall through here */
1278 break;
1279 }
1280 } else {
1281 /*
1282 * The previous character was not an escape char.
1283 * Check if this is an escape.
1284 */
1285 if (last_was_cr && ch == escape_char) {
1286 /*
1287 * It is. Set the flag and continue to
1288 * next character.
1289 */
1290 *escape_pendingp = 1;
1291 continue;
1292 }
1293 }
1294
1295 /*
1296 * Normal character. Record whether it was a newline,
1297 * and append it to the buffer.
1298 */
1299 last_was_cr = (ch == '\r' || ch == '\n');
1300 buffer_put_char(bin, ch);
1301 bytes++;
1302 }
1303 return bytes;
1304 }
1305
1306 static void
client_process_input(fd_set * readset)1307 client_process_input(fd_set *readset)
1308 {
1309 int len;
1310 char buf[SSH_IOBUFSZ];
1311
1312 /* Read input from stdin. */
1313 if (FD_ISSET(fileno(stdin), readset)) {
1314 /* Read as much as possible. */
1315 len = read(fileno(stdin), buf, sizeof(buf));
1316 if (len < 0 &&
1317 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1318 return; /* we'll try again later */
1319 if (len <= 0) {
1320 /*
1321 * Received EOF or error. They are treated
1322 * similarly, except that an error message is printed
1323 * if it was an error condition.
1324 */
1325 if (len < 0) {
1326 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1327 strerror(errno));
1328 buffer_append(&stderr_buffer, buf, strlen(buf));
1329 }
1330 /* Mark that we have seen EOF. */
1331 stdin_eof = 1;
1332 /*
1333 * Send an EOF message to the server unless there is
1334 * data in the buffer. If there is data in the
1335 * buffer, no message will be sent now. Code
1336 * elsewhere will send the EOF when the buffer
1337 * becomes empty if stdin_eof is set.
1338 */
1339 if (buffer_len(&stdin_buffer) == 0) {
1340 packet_start(SSH_CMSG_EOF);
1341 packet_send();
1342 }
1343 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1344 /*
1345 * Normal successful read, and no escape character.
1346 * Just append the data to buffer.
1347 */
1348 buffer_append(&stdin_buffer, buf, len);
1349 } else {
1350 /*
1351 * Normal, successful read. But we have an escape
1352 * character and have to process the characters one
1353 * by one.
1354 */
1355 if (process_escapes(NULL, &stdin_buffer,
1356 &stdout_buffer, &stderr_buffer, buf, len) == -1)
1357 return;
1358 }
1359 }
1360 }
1361
1362 static void
client_process_output(fd_set * writeset)1363 client_process_output(fd_set *writeset)
1364 {
1365 int len;
1366 char buf[100];
1367
1368 /* Write buffered output to stdout. */
1369 if (FD_ISSET(fileno(stdout), writeset)) {
1370 /* Write as much data as possible. */
1371 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1372 buffer_len(&stdout_buffer));
1373 if (len <= 0) {
1374 if (errno == EINTR || errno == EAGAIN ||
1375 errno == EWOULDBLOCK)
1376 len = 0;
1377 else {
1378 /*
1379 * An error or EOF was encountered. Put an
1380 * error message to stderr buffer.
1381 */
1382 snprintf(buf, sizeof buf,
1383 "write stdout: %.50s\r\n", strerror(errno));
1384 buffer_append(&stderr_buffer, buf, strlen(buf));
1385 quit_pending = 1;
1386 return;
1387 }
1388 }
1389 /* Consume printed data from the buffer. */
1390 buffer_consume(&stdout_buffer, len);
1391 }
1392 /* Write buffered output to stderr. */
1393 if (FD_ISSET(fileno(stderr), writeset)) {
1394 /* Write as much data as possible. */
1395 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1396 buffer_len(&stderr_buffer));
1397 if (len <= 0) {
1398 if (errno == EINTR || errno == EAGAIN ||
1399 errno == EWOULDBLOCK)
1400 len = 0;
1401 else {
1402 /*
1403 * EOF or error, but can't even print
1404 * error message.
1405 */
1406 quit_pending = 1;
1407 return;
1408 }
1409 }
1410 /* Consume printed characters from the buffer. */
1411 buffer_consume(&stderr_buffer, len);
1412 }
1413 }
1414
1415 /*
1416 * Get packets from the connection input buffer, and process them as long as
1417 * there are packets available.
1418 *
1419 * Any unknown packets received during the actual
1420 * session cause the session to terminate. This is
1421 * intended to make debugging easier since no
1422 * confirmations are sent. Any compatible protocol
1423 * extensions must be negotiated during the
1424 * preparatory phase.
1425 */
1426
1427 static void
client_process_buffered_input_packets(void)1428 client_process_buffered_input_packets(void)
1429 {
1430 dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1431 compat20 ? xxx_kex : NULL);
1432 }
1433
1434 /* scan buf[] for '~' before sending data to the peer */
1435
1436 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1437 void *
client_new_escape_filter_ctx(int escape_char)1438 client_new_escape_filter_ctx(int escape_char)
1439 {
1440 struct escape_filter_ctx *ret;
1441
1442 ret = xcalloc(1, sizeof(*ret));
1443 ret->escape_pending = 0;
1444 ret->escape_char = escape_char;
1445 return (void *)ret;
1446 }
1447
1448 /* Free the escape filter context on channel free */
1449 void
client_filter_cleanup(int cid,void * ctx)1450 client_filter_cleanup(int cid, void *ctx)
1451 {
1452 free(ctx);
1453 }
1454
1455 int
client_simple_escape_filter(Channel * c,char * buf,int len)1456 client_simple_escape_filter(Channel *c, char *buf, int len)
1457 {
1458 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1459 return 0;
1460
1461 return process_escapes(c, &c->input, &c->output, &c->extended,
1462 buf, len);
1463 }
1464
1465 static void
client_channel_closed(int id,void * arg)1466 client_channel_closed(int id, void *arg)
1467 {
1468 channel_cancel_cleanup(id);
1469 session_closed = 1;
1470 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1471 }
1472
1473 /*
1474 * Implements the interactive session with the server. This is called after
1475 * the user has been authenticated, and a command has been started on the
1476 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1477 * used as an escape character for terminating or suspending the session.
1478 */
1479
1480 int
client_loop(int have_pty,int escape_char_arg,int ssh2_chan_id)1481 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1482 {
1483 fd_set *readset = NULL, *writeset = NULL;
1484 double start_time, total_time;
1485 int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1486 u_int64_t ibytes, obytes;
1487 u_int nalloc = 0;
1488 char buf[100];
1489
1490 debug("Entering interactive session.");
1491
1492 start_time = get_current_time();
1493
1494 /* Initialize variables. */
1495 escape_pending1 = 0;
1496 last_was_cr = 1;
1497 exit_status = -1;
1498 stdin_eof = 0;
1499 buffer_high = 64 * 1024;
1500 connection_in = packet_get_connection_in();
1501 connection_out = packet_get_connection_out();
1502 max_fd = MAX(connection_in, connection_out);
1503
1504 if (!compat20) {
1505 /* enable nonblocking unless tty */
1506 if (!isatty(fileno(stdin)))
1507 set_nonblock(fileno(stdin));
1508 if (!isatty(fileno(stdout)))
1509 set_nonblock(fileno(stdout));
1510 if (!isatty(fileno(stderr)))
1511 set_nonblock(fileno(stderr));
1512 max_fd = MAX(max_fd, fileno(stdin));
1513 max_fd = MAX(max_fd, fileno(stdout));
1514 max_fd = MAX(max_fd, fileno(stderr));
1515 }
1516 quit_pending = 0;
1517 escape_char1 = escape_char_arg;
1518
1519 /* Initialize buffers. */
1520 buffer_init(&stdin_buffer);
1521 buffer_init(&stdout_buffer);
1522 buffer_init(&stderr_buffer);
1523
1524 client_init_dispatch();
1525
1526 /*
1527 * Set signal handlers, (e.g. to restore non-blocking mode)
1528 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1529 */
1530 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1531 signal(SIGHUP, signal_handler);
1532 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1533 signal(SIGINT, signal_handler);
1534 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1535 signal(SIGQUIT, signal_handler);
1536 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1537 signal(SIGTERM, signal_handler);
1538 signal(SIGWINCH, window_change_handler);
1539
1540 if (have_pty)
1541 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1542
1543 if (compat20) {
1544 session_ident = ssh2_chan_id;
1545 if (session_ident != -1) {
1546 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1547 channel_register_filter(session_ident,
1548 client_simple_escape_filter, NULL,
1549 client_filter_cleanup,
1550 client_new_escape_filter_ctx(
1551 escape_char_arg));
1552 }
1553 channel_register_cleanup(session_ident,
1554 client_channel_closed, 0);
1555 }
1556 } else {
1557 /* Check if we should immediately send eof on stdin. */
1558 client_check_initial_eof_on_stdin();
1559 }
1560
1561 /* Main loop of the client for the interactive session mode. */
1562 while (!quit_pending) {
1563
1564 /* Process buffered packets sent by the server. */
1565 client_process_buffered_input_packets();
1566
1567 if (compat20 && session_closed && !channel_still_open())
1568 break;
1569
1570 rekeying = (xxx_kex != NULL && !xxx_kex->done);
1571
1572 if (rekeying) {
1573 debug("rekeying in progress");
1574 } else {
1575 /*
1576 * Make packets of buffered stdin data, and buffer
1577 * them for sending to the server.
1578 */
1579 if (!compat20)
1580 client_make_packets_from_stdin_data();
1581
1582 /*
1583 * Make packets from buffered channel data, and
1584 * enqueue them for sending to the server.
1585 */
1586 if (packet_not_very_much_data_to_write())
1587 channel_output_poll();
1588
1589 /*
1590 * Check if the window size has changed, and buffer a
1591 * message about it to the server if so.
1592 */
1593 client_check_window_change();
1594
1595 if (quit_pending)
1596 break;
1597 }
1598 /*
1599 * Wait until we have something to do (something becomes
1600 * available on one of the descriptors).
1601 */
1602 max_fd2 = max_fd;
1603 client_wait_until_can_do_something(&readset, &writeset,
1604 &max_fd2, &nalloc, rekeying);
1605
1606 if (quit_pending)
1607 break;
1608
1609 /* Do channel operations unless rekeying in progress. */
1610 if (!rekeying) {
1611 channel_after_select(readset, writeset);
1612 if (need_rekeying || packet_need_rekeying()) {
1613 debug("need rekeying");
1614 xxx_kex->done = 0;
1615 kex_send_kexinit(xxx_kex);
1616 need_rekeying = 0;
1617 }
1618 }
1619
1620 /* Buffer input from the connection. */
1621 client_process_net_input(readset);
1622
1623 if (quit_pending)
1624 break;
1625
1626 if (!compat20) {
1627 /* Buffer data from stdin */
1628 client_process_input(readset);
1629 /*
1630 * Process output to stdout and stderr. Output to
1631 * the connection is processed elsewhere (above).
1632 */
1633 client_process_output(writeset);
1634 }
1635
1636 if (session_resumed) {
1637 connection_in = packet_get_connection_in();
1638 connection_out = packet_get_connection_out();
1639 max_fd = MAX(max_fd, connection_out);
1640 max_fd = MAX(max_fd, connection_in);
1641 session_resumed = 0;
1642 }
1643
1644 /*
1645 * Send as much buffered packet data as possible to the
1646 * sender.
1647 */
1648 if (FD_ISSET(connection_out, writeset))
1649 packet_write_poll();
1650
1651 /*
1652 * If we are a backgrounded control master, and the
1653 * timeout has expired without any active client
1654 * connections, then quit.
1655 */
1656 if (control_persist_exit_time > 0) {
1657 if (monotime() >= control_persist_exit_time) {
1658 debug("ControlPersist timeout expired");
1659 break;
1660 }
1661 }
1662 }
1663 free(readset);
1664 free(writeset);
1665
1666 /* Terminate the session. */
1667
1668 /* Stop watching for window change. */
1669 signal(SIGWINCH, SIG_DFL);
1670
1671 if (compat20) {
1672 packet_start(SSH2_MSG_DISCONNECT);
1673 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1674 packet_put_cstring("disconnected by user");
1675 packet_put_cstring(""); /* language tag */
1676 packet_send();
1677 packet_write_wait();
1678 }
1679
1680 channel_free_all();
1681
1682 if (have_pty)
1683 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1684
1685 /* restore blocking io */
1686 if (!isatty(fileno(stdin)))
1687 unset_nonblock(fileno(stdin));
1688 if (!isatty(fileno(stdout)))
1689 unset_nonblock(fileno(stdout));
1690 if (!isatty(fileno(stderr)))
1691 unset_nonblock(fileno(stderr));
1692
1693 /*
1694 * If there was no shell or command requested, there will be no remote
1695 * exit status to be returned. In that case, clear error code if the
1696 * connection was deliberately terminated at this end.
1697 */
1698 if (no_shell_flag && received_signal == SIGTERM) {
1699 received_signal = 0;
1700 exit_status = 0;
1701 }
1702
1703 if (received_signal)
1704 fatal("Killed by signal %d.", (int) received_signal);
1705
1706 /*
1707 * In interactive mode (with pseudo tty) display a message indicating
1708 * that the connection has been closed.
1709 */
1710 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1711 snprintf(buf, sizeof buf,
1712 "Connection to %.64s closed.\r\n", host);
1713 buffer_append(&stderr_buffer, buf, strlen(buf));
1714 }
1715
1716 /* Output any buffered data for stdout. */
1717 if (buffer_len(&stdout_buffer) > 0) {
1718 len = atomicio(vwrite, fileno(stdout),
1719 buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1720 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1721 error("Write failed flushing stdout buffer.");
1722 else
1723 buffer_consume(&stdout_buffer, len);
1724 }
1725
1726 /* Output any buffered data for stderr. */
1727 if (buffer_len(&stderr_buffer) > 0) {
1728 len = atomicio(vwrite, fileno(stderr),
1729 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1730 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1731 error("Write failed flushing stderr buffer.");
1732 else
1733 buffer_consume(&stderr_buffer, len);
1734 }
1735
1736 /* Clear and free any buffers. */
1737 memset(buf, 0, sizeof(buf));
1738 buffer_free(&stdin_buffer);
1739 buffer_free(&stdout_buffer);
1740 buffer_free(&stderr_buffer);
1741
1742 /* Report bytes transferred, and transfer rates. */
1743 total_time = get_current_time() - start_time;
1744 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1745 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1746 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1747 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1748 if (total_time > 0)
1749 verbose("Bytes per second: sent %.1f, received %.1f",
1750 obytes / total_time, ibytes / total_time);
1751 /* Return the exit status of the program. */
1752 debug("Exit status %d", exit_status);
1753 return exit_status;
1754 }
1755
1756 /*********/
1757
1758 static void
client_input_stdout_data(int type,u_int32_t seq,void * ctxt)1759 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1760 {
1761 u_int data_len;
1762 char *data = packet_get_string(&data_len);
1763 packet_check_eom();
1764 buffer_append(&stdout_buffer, data, data_len);
1765 explicit_bzero(data, data_len);
1766 free(data);
1767 }
1768 static void
client_input_stderr_data(int type,u_int32_t seq,void * ctxt)1769 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1770 {
1771 u_int data_len;
1772 char *data = packet_get_string(&data_len);
1773 packet_check_eom();
1774 buffer_append(&stderr_buffer, data, data_len);
1775 explicit_bzero(data, data_len);
1776 free(data);
1777 }
1778 static void
client_input_exit_status(int type,u_int32_t seq,void * ctxt)1779 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1780 {
1781 exit_status = packet_get_int();
1782 packet_check_eom();
1783 /* Acknowledge the exit. */
1784 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1785 packet_send();
1786 /*
1787 * Must wait for packet to be sent since we are
1788 * exiting the loop.
1789 */
1790 packet_write_wait();
1791 /* Flag that we want to exit. */
1792 quit_pending = 1;
1793 }
1794 static void
client_input_agent_open(int type,u_int32_t seq,void * ctxt)1795 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1796 {
1797 Channel *c = NULL;
1798 int remote_id, sock;
1799
1800 /* Read the remote channel number from the message. */
1801 remote_id = packet_get_int();
1802 packet_check_eom();
1803
1804 /*
1805 * Get a connection to the local authentication agent (this may again
1806 * get forwarded).
1807 */
1808 sock = ssh_get_authentication_socket();
1809
1810 /*
1811 * If we could not connect the agent, send an error message back to
1812 * the server. This should never happen unless the agent dies,
1813 * because authentication forwarding is only enabled if we have an
1814 * agent.
1815 */
1816 if (sock >= 0) {
1817 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1818 -1, 0, 0, 0, "authentication agent connection", 1);
1819 c->remote_id = remote_id;
1820 c->force_drain = 1;
1821 }
1822 if (c == NULL) {
1823 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1824 packet_put_int(remote_id);
1825 } else {
1826 /* Send a confirmation to the remote host. */
1827 debug("Forwarding authentication connection.");
1828 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1829 packet_put_int(remote_id);
1830 packet_put_int(c->self);
1831 }
1832 packet_send();
1833 }
1834
1835 static Channel *
client_request_forwarded_tcpip(const char * request_type,int rchan)1836 client_request_forwarded_tcpip(const char *request_type, int rchan)
1837 {
1838 Channel *c = NULL;
1839 char *listen_address, *originator_address;
1840 u_short listen_port, originator_port;
1841
1842 /* Get rest of the packet */
1843 listen_address = packet_get_string(NULL);
1844 listen_port = packet_get_int();
1845 originator_address = packet_get_string(NULL);
1846 originator_port = packet_get_int();
1847 packet_check_eom();
1848
1849 debug("client_request_forwarded_tcpip: listen %s port %d, "
1850 "originator %s port %d", listen_address, listen_port,
1851 originator_address, originator_port);
1852
1853 c = channel_connect_by_listen_address(listen_port,
1854 "forwarded-tcpip", originator_address);
1855
1856 free(originator_address);
1857 free(listen_address);
1858 return c;
1859 }
1860
1861 static Channel *
client_request_x11(const char * request_type,int rchan)1862 client_request_x11(const char *request_type, int rchan)
1863 {
1864 Channel *c = NULL;
1865 char *originator;
1866 u_short originator_port;
1867 int sock;
1868
1869 if (!options.forward_x11) {
1870 error("Warning: ssh server tried X11 forwarding.");
1871 error("Warning: this is probably a break-in attempt by a "
1872 "malicious server.");
1873 return NULL;
1874 }
1875 if (x11_refuse_time != 0 && monotime() >= x11_refuse_time) {
1876 verbose("Rejected X11 connection after ForwardX11Timeout "
1877 "expired");
1878 return NULL;
1879 }
1880 originator = packet_get_string(NULL);
1881 if (datafellows & SSH_BUG_X11FWD) {
1882 debug2("buggy server: x11 request w/o originator_port");
1883 originator_port = 0;
1884 } else {
1885 originator_port = packet_get_int();
1886 }
1887 packet_check_eom();
1888 /* XXX check permission */
1889 debug("client_request_x11: request from %s %d", originator,
1890 originator_port);
1891 free(originator);
1892 sock = x11_connect_display();
1893 if (sock < 0)
1894 return NULL;
1895 if (options.hpn_disabled)
1896 c = channel_new("x11", SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1897 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1898 0, "x11", 1);
1899 else
1900 c = channel_new("x11", SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1901 options.hpn_buffer_size, CHAN_X11_PACKET_DEFAULT,
1902 0, "x11", 1);
1903 c->force_drain = 1;
1904 return c;
1905 }
1906
1907 static Channel *
client_request_agent(const char * request_type,int rchan)1908 client_request_agent(const char *request_type, int rchan)
1909 {
1910 Channel *c = NULL;
1911 int sock;
1912
1913 if (!options.forward_agent) {
1914 error("Warning: ssh server tried agent forwarding.");
1915 error("Warning: this is probably a break-in attempt by a "
1916 "malicious server.");
1917 return NULL;
1918 }
1919 sock = ssh_get_authentication_socket();
1920 if (sock < 0)
1921 return NULL;
1922 if (options.hpn_disabled)
1923 c = channel_new("authentication agent connection",
1924 SSH_CHANNEL_OPEN, sock, sock, -1,
1925 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1926 "authentication agent connection", 1);
1927 else
1928 c = channel_new("authentication agent connection",
1929 SSH_CHANNEL_OPEN, sock, sock, -1,
1930 options.hpn_buffer_size, options.hpn_buffer_size, 0,
1931 "authentication agent connection", 1);
1932 c->force_drain = 1;
1933 return c;
1934 }
1935
1936 int
client_request_tun_fwd(int tun_mode,int local_tun,int remote_tun)1937 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1938 {
1939 Channel *c;
1940 int fd;
1941
1942 if (tun_mode == SSH_TUNMODE_NO)
1943 return 0;
1944
1945 if (!compat20) {
1946 error("Tunnel forwarding is not supported for protocol 1");
1947 return -1;
1948 }
1949
1950 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1951
1952 /* Open local tunnel device */
1953 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1954 error("Tunnel device open failed.");
1955 return -1;
1956 }
1957
1958 if (options.hpn_disabled)
1959 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1960 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1961 0, "tun", 1);
1962 else
1963 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1964 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
1965 0, "tun", 1);
1966 c->datagram = 1;
1967
1968 #if defined(SSH_TUN_FILTER)
1969 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1970 channel_register_filter(c->self, sys_tun_infilter,
1971 sys_tun_outfilter, NULL, NULL);
1972 #endif
1973
1974 packet_start(SSH2_MSG_CHANNEL_OPEN);
1975 packet_put_cstring("tun@openssh.com");
1976 packet_put_int(c->self);
1977 packet_put_int(c->local_window_max);
1978 packet_put_int(c->local_maxpacket);
1979 packet_put_int(tun_mode);
1980 packet_put_int(remote_tun);
1981 packet_send();
1982
1983 return 0;
1984 }
1985
1986 /* XXXX move to generic input handler */
1987 static void
client_input_channel_open(int type,u_int32_t seq,void * ctxt)1988 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1989 {
1990 Channel *c = NULL;
1991 char *ctype;
1992 int rchan;
1993 u_int rmaxpack, rwindow, len;
1994
1995 ctype = packet_get_string(&len);
1996 rchan = packet_get_int();
1997 rwindow = packet_get_int();
1998 rmaxpack = packet_get_int();
1999
2000 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
2001 ctype, rchan, rwindow, rmaxpack);
2002
2003 if (strcmp(ctype, "forwarded-tcpip") == 0) {
2004 c = client_request_forwarded_tcpip(ctype, rchan);
2005 } else if (strcmp(ctype, "x11") == 0) {
2006 c = client_request_x11(ctype, rchan);
2007 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
2008 c = client_request_agent(ctype, rchan);
2009 }
2010 /* XXX duplicate : */
2011 if (c != NULL) {
2012 debug("confirm %s", ctype);
2013 c->remote_id = rchan;
2014 c->remote_window = rwindow;
2015 c->remote_maxpacket = rmaxpack;
2016 if (c->type != SSH_CHANNEL_CONNECTING) {
2017 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
2018 packet_put_int(c->remote_id);
2019 packet_put_int(c->self);
2020 packet_put_int(c->local_window);
2021 packet_put_int(c->local_maxpacket);
2022 packet_send();
2023 }
2024 } else {
2025 debug("failure %s", ctype);
2026 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
2027 packet_put_int(rchan);
2028 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
2029 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2030 packet_put_cstring("open failed");
2031 packet_put_cstring("");
2032 }
2033 packet_send();
2034 }
2035 free(ctype);
2036 }
2037 static void
client_input_channel_req(int type,u_int32_t seq,void * ctxt)2038 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
2039 {
2040 Channel *c = NULL;
2041 int exitval, id, reply, success = 0;
2042 char *rtype;
2043
2044 id = packet_get_int();
2045 rtype = packet_get_string(NULL);
2046 reply = packet_get_char();
2047
2048 debug("client_input_channel_req: channel %d rtype %s reply %d",
2049 id, rtype, reply);
2050
2051 if (id == -1) {
2052 error("client_input_channel_req: request for channel -1");
2053 } else if ((c = channel_lookup(id)) == NULL) {
2054 error("client_input_channel_req: channel %d: "
2055 "unknown channel", id);
2056 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
2057 packet_check_eom();
2058 chan_rcvd_eow(c);
2059 } else if (strcmp(rtype, "exit-status") == 0) {
2060 exitval = packet_get_int();
2061 if (c->ctl_chan != -1) {
2062 mux_exit_message(c, exitval);
2063 success = 1;
2064 } else if (id == session_ident) {
2065 /* Record exit value of local session */
2066 success = 1;
2067 exit_status = exitval;
2068 } else {
2069 /* Probably for a mux channel that has already closed */
2070 debug("%s: no sink for exit-status on channel %d",
2071 __func__, id);
2072 }
2073 packet_check_eom();
2074 }
2075 if (reply && c != NULL) {
2076 packet_start(success ?
2077 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
2078 packet_put_int(c->remote_id);
2079 packet_send();
2080 }
2081 free(rtype);
2082 }
2083 static void
client_input_global_request(int type,u_int32_t seq,void * ctxt)2084 client_input_global_request(int type, u_int32_t seq, void *ctxt)
2085 {
2086 char *rtype;
2087 int want_reply;
2088 int success = 0;
2089
2090 rtype = packet_get_string(NULL);
2091 want_reply = packet_get_char();
2092 debug("client_input_global_request: rtype %s want_reply %d",
2093 rtype, want_reply);
2094 if (want_reply) {
2095 packet_start(success ?
2096 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2097 packet_send();
2098 packet_write_wait();
2099 }
2100 free(rtype);
2101 }
2102
2103 void
client_session2_setup(int id,int want_tty,int want_subsystem,const char * term,struct termios * tiop,int in_fd,Buffer * cmd,char ** env)2104 client_session2_setup(int id, int want_tty, int want_subsystem,
2105 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2106 {
2107 int len;
2108 Channel *c = NULL;
2109
2110 debug2("%s: id %d", __func__, id);
2111
2112 if ((c = channel_lookup(id)) == NULL)
2113 fatal("client_session2_setup: channel %d: unknown channel", id);
2114
2115 packet_set_interactive(want_tty,
2116 options.ip_qos_interactive, options.ip_qos_bulk);
2117
2118 if (want_tty) {
2119 struct winsize ws;
2120
2121 /* Store window size in the packet. */
2122 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2123 memset(&ws, 0, sizeof(ws));
2124
2125 channel_request_start(id, "pty-req", 1);
2126 client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
2127 packet_put_cstring(term != NULL ? term : "");
2128 packet_put_int((u_int)ws.ws_col);
2129 packet_put_int((u_int)ws.ws_row);
2130 packet_put_int((u_int)ws.ws_xpixel);
2131 packet_put_int((u_int)ws.ws_ypixel);
2132 if (tiop == NULL)
2133 tiop = get_saved_tio();
2134 tty_make_modes(-1, tiop);
2135 packet_send();
2136 /* XXX wait for reply */
2137 c->client_tty = 1;
2138 }
2139
2140 /* Transfer any environment variables from client to server */
2141 if (options.num_send_env != 0 && env != NULL) {
2142 int i, j, matched;
2143 char *name, *val;
2144
2145 debug("Sending environment.");
2146 for (i = 0; env[i] != NULL; i++) {
2147 /* Split */
2148 name = xstrdup(env[i]);
2149 if ((val = strchr(name, '=')) == NULL) {
2150 free(name);
2151 continue;
2152 }
2153 *val++ = '\0';
2154
2155 matched = 0;
2156 for (j = 0; j < options.num_send_env; j++) {
2157 if (match_pattern(name, options.send_env[j])) {
2158 matched = 1;
2159 break;
2160 }
2161 }
2162 if (!matched) {
2163 debug3("Ignored env %s", name);
2164 free(name);
2165 continue;
2166 }
2167
2168 debug("Sending env %s = %s", name, val);
2169 channel_request_start(id, "env", 0);
2170 packet_put_cstring(name);
2171 packet_put_cstring(val);
2172 packet_send();
2173 free(name);
2174 }
2175 }
2176
2177 len = buffer_len(cmd);
2178 if (len > 0) {
2179 if (len > 900)
2180 len = 900;
2181 if (want_subsystem) {
2182 debug("Sending subsystem: %.*s",
2183 len, (u_char*)buffer_ptr(cmd));
2184 channel_request_start(id, "subsystem", 1);
2185 client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
2186 } else {
2187 debug("Sending command: %.*s",
2188 len, (u_char*)buffer_ptr(cmd));
2189 channel_request_start(id, "exec", 1);
2190 client_expect_confirm(id, "exec", CONFIRM_CLOSE);
2191 }
2192 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2193 packet_send();
2194 } else {
2195 channel_request_start(id, "shell", 1);
2196 client_expect_confirm(id, "shell", CONFIRM_CLOSE);
2197 packet_send();
2198 }
2199 }
2200
2201 static void
client_init_dispatch_20(void)2202 client_init_dispatch_20(void)
2203 {
2204 dispatch_init(&dispatch_protocol_error);
2205
2206 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2207 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2208 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2209 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2210 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2211 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2212 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2213 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2214 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2215 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2216 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2217 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2218
2219 /* rekeying */
2220 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2221
2222 /* global request reply messages */
2223 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2224 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2225 }
2226
2227 static void
client_init_dispatch_13(void)2228 client_init_dispatch_13(void)
2229 {
2230 dispatch_init(NULL);
2231 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2232 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2233 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2234 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2235 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2236 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2237 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2238 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2239 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2240
2241 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2242 &client_input_agent_open : &deny_input_open);
2243 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2244 &x11_input_open : &deny_input_open);
2245 }
2246
2247 static void
client_init_dispatch_15(void)2248 client_init_dispatch_15(void)
2249 {
2250 client_init_dispatch_13();
2251 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2252 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2253 }
2254
2255 static void
client_init_dispatch(void)2256 client_init_dispatch(void)
2257 {
2258 if (compat20)
2259 client_init_dispatch_20();
2260 else if (compat13)
2261 client_init_dispatch_13();
2262 else
2263 client_init_dispatch_15();
2264 }
2265
2266 void
client_stop_mux(void)2267 client_stop_mux(void)
2268 {
2269 if (options.control_path != NULL && muxserver_sock != -1)
2270 unlink(options.control_path);
2271 /*
2272 * If we are in persist mode, or don't have a shell, signal that we
2273 * should close when all active channels are closed.
2274 */
2275 if (options.control_persist || no_shell_flag) {
2276 session_closed = 1;
2277 setproctitle("[stopped mux]");
2278 }
2279 }
2280
2281 /* client specific fatal cleanup */
2282 void
cleanup_exit(int i)2283 cleanup_exit(int i)
2284 {
2285 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2286 leave_non_blocking();
2287 if (options.control_path != NULL && muxserver_sock != -1)
2288 unlink(options.control_path);
2289 ssh_kill_proxy_command();
2290 _exit(i);
2291 }
2292