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