Annotation of src/usr.bin/ssh/clientloop.c, Revision 1.264
1.264 ! markus 1: /* $OpenBSD: clientloop.c,v 1.263 2015/01/19 19:52:16 markus 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.264 ! markus 531: static int
1.117 markus 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)
1.264 ! markus 537: return 0;
1.196 djm 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.264 ! markus 547: return 0;
1.117 markus 548: }
549:
550: static void
551: server_alive_check(void)
552: {
1.210 andreas 553: if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
1.228 djm 554: logit("Timeout, server %s not responding.", host);
1.176 markus 555: cleanup_exit(255);
556: }
1.117 markus 557: packet_start(SSH2_MSG_GLOBAL_REQUEST);
558: packet_put_cstring("keepalive@openssh.com");
559: packet_put_char(1); /* boolean: want reply */
560: packet_send();
1.196 djm 561: /* Insert an empty placeholder to maintain ordering */
562: client_register_global_confirm(NULL, NULL);
1.117 markus 563: }
564:
1.13 markus 565: /*
566: * Waits until the client can do something (some data becomes available on
567: * one of the file descriptors).
568: */
1.77 itojun 569: static void
1.46 markus 570: client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
1.130 avsm 571: int *maxfdp, u_int *nallocp, int rekeying)
1.11 markus 572: {
1.117 markus 573: struct timeval tv, *tvp;
1.222 djm 574: int timeout_secs;
1.251 dtucker 575: time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
1.117 markus 576: int ret;
577:
1.46 markus 578: /* Add any selections by the channel mechanism. */
1.239 djm 579: channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
580: &minwait_secs, rekeying);
1.11 markus 581:
1.16 markus 582: if (!compat20) {
1.17 markus 583: /* Read from the connection, unless our buffers are full. */
1.16 markus 584: if (buffer_len(&stdout_buffer) < buffer_high &&
585: buffer_len(&stderr_buffer) < buffer_high &&
586: channel_not_very_much_buffered_data())
1.46 markus 587: FD_SET(connection_in, *readsetp);
1.17 markus 588: /*
589: * Read from stdin, unless we have seen EOF or have very much
590: * buffered data to send to the server.
591: */
592: if (!stdin_eof && packet_not_very_much_data_to_write())
1.46 markus 593: FD_SET(fileno(stdin), *readsetp);
1.17 markus 594:
595: /* Select stdout/stderr if have data in buffer. */
596: if (buffer_len(&stdout_buffer) > 0)
1.46 markus 597: FD_SET(fileno(stdout), *writesetp);
1.17 markus 598: if (buffer_len(&stderr_buffer) > 0)
1.46 markus 599: FD_SET(fileno(stderr), *writesetp);
1.16 markus 600: } else {
1.71 markus 601: /* channel_prepare_select could have closed the last channel */
1.84 markus 602: if (session_closed && !channel_still_open() &&
603: !packet_have_data_to_write()) {
604: /* clear mask since we did not call select() */
1.87 markus 605: memset(*readsetp, 0, *nallocp);
606: memset(*writesetp, 0, *nallocp);
1.84 markus 607: return;
1.71 markus 608: } else {
609: FD_SET(connection_in, *readsetp);
610: }
1.16 markus 611: }
1.11 markus 612:
613: /* Select server connection if have data to write to the server. */
614: if (packet_have_data_to_write())
1.46 markus 615: FD_SET(connection_out, *writesetp);
1.11 markus 616:
1.13 markus 617: /*
618: * Wait for something to happen. This will suspend the process until
619: * some selected descriptor can be read, written, or has some other
1.222 djm 620: * event pending, or a timeout expires.
1.13 markus 621: */
1.11 markus 622:
1.222 djm 623: timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
1.249 dtucker 624: if (options.server_alive_interval > 0 && compat20) {
1.222 djm 625: timeout_secs = options.server_alive_interval;
1.249 dtucker 626: server_alive_time = now + options.server_alive_interval;
627: }
628: if (options.rekey_interval > 0 && compat20 && !rekeying)
629: timeout_secs = MIN(timeout_secs, packet_get_rekey_timeout());
1.222 djm 630: set_control_persist_exit_time();
631: if (control_persist_exit_time > 0) {
632: timeout_secs = MIN(timeout_secs,
1.249 dtucker 633: control_persist_exit_time - now);
1.222 djm 634: if (timeout_secs < 0)
635: timeout_secs = 0;
636: }
1.239 djm 637: if (minwait_secs != 0)
638: timeout_secs = MIN(timeout_secs, (int)minwait_secs);
1.222 djm 639: if (timeout_secs == INT_MAX)
1.117 markus 640: tvp = NULL;
1.129 deraadt 641: else {
1.222 djm 642: tv.tv_sec = timeout_secs;
1.117 markus 643: tv.tv_usec = 0;
644: tvp = &tv;
645: }
1.222 djm 646:
1.117 markus 647: ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
648: if (ret < 0) {
1.11 markus 649: char buf[100];
1.51 markus 650:
651: /*
652: * We have to clear the select masks, because we return.
653: * We have to return, because the mainloop checks for the flags
654: * set by the signal handlers.
655: */
1.87 markus 656: memset(*readsetp, 0, *nallocp);
657: memset(*writesetp, 0, *nallocp);
1.50 deraadt 658:
1.11 markus 659: if (errno == EINTR)
660: return;
661: /* Note: we might still have data in the buffers. */
662: snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
663: buffer_append(&stderr_buffer, buf, strlen(buf));
664: quit_pending = 1;
1.249 dtucker 665: } else if (ret == 0) {
666: /*
667: * Timeout. Could have been either keepalive or rekeying.
668: * Keepalive we check here, rekeying is checked in clientloop.
669: */
1.251 dtucker 670: if (server_alive_time != 0 && server_alive_time <= monotime())
1.249 dtucker 671: server_alive_check();
672: }
673:
1.11 markus 674: }
675:
1.77 itojun 676: static void
1.31 markus 677: client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
1.1 deraadt 678: {
1.11 markus 679: /* Flush stdout and stderr buffers. */
1.31 markus 680: if (buffer_len(bout) > 0)
1.197 djm 681: atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
682: buffer_len(bout));
1.31 markus 683: if (buffer_len(berr) > 0)
1.197 djm 684: atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
685: buffer_len(berr));
1.11 markus 686:
1.233 djm 687: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11 markus 688:
1.13 markus 689: /*
690: * Free (and clear) the buffer to reduce the amount of data that gets
691: * written to swap.
692: */
1.31 markus 693: buffer_free(bin);
694: buffer_free(bout);
695: buffer_free(berr);
1.11 markus 696:
697: /* Send the suspend signal to the program itself. */
698: kill(getpid(), SIGTSTP);
699:
1.132 djm 700: /* Reset window sizes in case they have changed */
701: received_window_change_signal = 1;
1.11 markus 702:
703: /* OK, we have been continued by the user. Reinitialize buffers. */
1.31 markus 704: buffer_init(bin);
705: buffer_init(bout);
706: buffer_init(berr);
1.11 markus 707:
1.233 djm 708: enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11 markus 709: }
710:
1.77 itojun 711: static void
1.161 deraadt 712: client_process_net_input(fd_set *readset)
1.11 markus 713: {
1.212 andreas 714: int len, cont = 0;
1.17 markus 715: char buf[8192];
1.11 markus 716:
1.13 markus 717: /*
718: * Read input from the server, and add any such data to the buffer of
719: * the packet subsystem.
720: */
1.11 markus 721: if (FD_ISSET(connection_in, readset)) {
722: /* Read as much as possible. */
1.212 andreas 723: len = roaming_read(connection_in, buf, sizeof(buf), &cont);
724: if (len == 0 && cont == 0) {
1.197 djm 725: /*
726: * Received EOF. The remote host has closed the
727: * connection.
728: */
729: snprintf(buf, sizeof buf,
730: "Connection to %.300s closed by remote host.\r\n",
731: host);
1.1 deraadt 732: buffer_append(&stderr_buffer, buf, strlen(buf));
733: quit_pending = 1;
734: return;
1.11 markus 735: }
1.13 markus 736: /*
737: * There is a kernel bug on Solaris that causes select to
738: * sometimes wake up even though there is no data available.
739: */
1.53 millert 740: if (len < 0 && (errno == EAGAIN || errno == EINTR))
1.11 markus 741: len = 0;
742:
743: if (len < 0) {
1.197 djm 744: /*
745: * An error has encountered. Perhaps there is a
746: * network problem.
747: */
748: snprintf(buf, sizeof buf,
749: "Read from remote host %.300s: %.100s\r\n",
750: host, strerror(errno));
1.11 markus 751: buffer_append(&stderr_buffer, buf, strlen(buf));
752: quit_pending = 1;
753: return;
754: }
755: packet_process_incoming(buf, len);
756: }
1.17 markus 757: }
1.16 markus 758:
1.97 jakob 759: static void
1.190 djm 760: client_status_confirm(int type, Channel *c, void *ctx)
1.123 djm 761: {
1.190 djm 762: struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
763: char errmsg[256];
764: int tochan;
765:
1.234 djm 766: /*
767: * If a TTY was explicitly requested, then a failure to allocate
768: * one is fatal.
769: */
770: if (cr->action == CONFIRM_TTY &&
771: (options.request_tty == REQUEST_TTY_FORCE ||
772: options.request_tty == REQUEST_TTY_YES))
773: cr->action = CONFIRM_CLOSE;
774:
1.190 djm 775: /* XXX supress on mux _client_ quietmode */
776: tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
1.217 djm 777: c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
1.190 djm 778:
779: if (type == SSH2_MSG_CHANNEL_SUCCESS) {
780: debug2("%s request accepted on channel %d",
781: cr->request_type, c->self);
782: } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
783: if (tochan) {
784: snprintf(errmsg, sizeof(errmsg),
785: "%s request failed\r\n", cr->request_type);
786: } else {
787: snprintf(errmsg, sizeof(errmsg),
788: "%s request failed on channel %d",
789: cr->request_type, c->self);
790: }
791: /* If error occurred on primary session channel, then exit */
1.234 djm 792: if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
1.190 djm 793: fatal("%s", errmsg);
1.234 djm 794: /*
795: * If error occurred on mux client, append to
796: * their stderr.
797: */
798: if (tochan) {
799: buffer_append(&c->extended, errmsg,
800: strlen(errmsg));
801: } else
1.190 djm 802: error("%s", errmsg);
1.234 djm 803: if (cr->action == CONFIRM_TTY) {
804: /*
805: * If a TTY allocation error occurred, then arrange
806: * for the correct TTY to leave raw mode.
807: */
808: if (c->self == session_ident)
809: leave_raw_mode(0);
810: else
811: mux_tty_alloc_failed(c);
812: } else if (cr->action == CONFIRM_CLOSE) {
1.190 djm 813: chan_read_failed(c);
814: chan_write_failed(c);
815: }
816: }
1.250 djm 817: free(cr);
1.190 djm 818: }
819:
820: static void
821: client_abandon_status_confirm(Channel *c, void *ctx)
822: {
1.250 djm 823: free(ctx);
1.190 djm 824: }
1.129 deraadt 825:
1.236 djm 826: void
1.234 djm 827: client_expect_confirm(int id, const char *request,
828: enum confirm_action action)
1.190 djm 829: {
1.255 djm 830: struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
1.123 djm 831:
1.190 djm 832: cr->request_type = request;
1.234 djm 833: cr->action = action;
1.123 djm 834:
1.190 djm 835: channel_register_status_confirm(id, client_status_confirm,
836: client_abandon_status_confirm, cr);
1.196 djm 837: }
838:
839: void
840: client_register_global_confirm(global_confirm_cb *cb, void *ctx)
841: {
1.201 djm 842: struct global_confirm *gc, *last_gc;
1.196 djm 843:
844: /* Coalesce identical callbacks */
1.201 djm 845: last_gc = TAILQ_LAST(&global_confirms, global_confirms);
846: if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
847: if (++last_gc->ref_count >= INT_MAX)
848: fatal("%s: last_gc->ref_count = %d",
849: __func__, last_gc->ref_count);
1.196 djm 850: return;
851: }
852:
1.255 djm 853: gc = xcalloc(1, sizeof(*gc));
1.196 djm 854: gc->cb = cb;
855: gc->ctx = ctx;
856: gc->ref_count = 1;
857: TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
1.123 djm 858: }
859:
860: static void
1.99 markus 861: process_cmdline(void)
1.97 jakob 862: {
863: void (*handler)(int);
1.261 millert 864: char *s, *cmd;
865: int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
866: struct Forward fwd;
1.97 jakob 867:
1.257 tedu 868: memset(&fwd, 0, sizeof(fwd));
1.183 djm 869:
1.233 djm 870: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.101 markus 871: handler = signal(SIGINT, SIG_IGN);
1.99 markus 872: cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
1.97 jakob 873: if (s == NULL)
874: goto out;
1.256 deraadt 875: while (isspace((u_char)*s))
1.97 jakob 876: s++;
1.121 djm 877: if (*s == '-')
878: s++; /* Skip cmdline '-', if any */
1.120 dtucker 879: if (*s == '\0')
1.97 jakob 880: goto out;
1.121 djm 881:
1.122 djm 882: if (*s == 'h' || *s == 'H' || *s == '?') {
1.121 djm 883: logit("Commands:");
1.164 djm 884: logit(" -L[bind_address:]port:host:hostport "
885: "Request local forward");
886: logit(" -R[bind_address:]port:host:hostport "
887: "Request remote forward");
1.204 stevesk 888: logit(" -D[bind_address:]port "
889: "Request dynamic forward");
1.237 markus 890: logit(" -KL[bind_address:]port "
891: "Cancel local forward");
1.165 stevesk 892: logit(" -KR[bind_address:]port "
1.164 djm 893: "Cancel remote forward");
1.237 markus 894: logit(" -KD[bind_address:]port "
895: "Cancel dynamic forward");
1.146 reyk 896: if (!options.permit_local_command)
897: goto out;
1.164 djm 898: logit(" !args "
899: "Execute local command");
1.146 reyk 900: goto out;
901: }
902:
903: if (*s == '!' && options.permit_local_command) {
904: s++;
905: ssh_local_cmd(s);
1.121 djm 906: goto out;
907: }
908:
909: if (*s == 'K') {
910: delete = 1;
911: s++;
912: }
1.204 stevesk 913: if (*s == 'L')
914: local = 1;
915: else if (*s == 'R')
916: remote = 1;
917: else if (*s == 'D')
918: dynamic = 1;
919: else {
1.109 itojun 920: logit("Invalid command.");
1.97 jakob 921: goto out;
922: }
1.204 stevesk 923:
1.237 markus 924: if (delete && !compat20) {
1.109 itojun 925: logit("Not supported for SSH protocol version 1.");
1.97 jakob 926: goto out;
927: }
1.121 djm 928:
1.256 deraadt 929: while (isspace((u_char)*++s))
1.179 tedu 930: ;
1.97 jakob 931:
1.217 djm 932: /* XXX update list of forwards in options */
1.121 djm 933: if (delete) {
1.261 millert 934: /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
935: if (!parse_forward(&fwd, s, 1, 0)) {
936: logit("Bad forwarding close specification.");
1.121 djm 937: goto out;
938: }
1.237 markus 939: if (remote)
1.261 millert 940: ok = channel_request_rforward_cancel(&fwd) == 0;
1.237 markus 941: else if (dynamic)
1.261 millert 942: ok = channel_cancel_lport_listener(&fwd,
943: 0, &options.fwd_opts) > 0;
1.237 markus 944: else
1.261 millert 945: ok = channel_cancel_lport_listener(&fwd,
946: CHANNEL_CANCEL_PORT_STATIC,
947: &options.fwd_opts) > 0;
1.237 markus 948: if (!ok) {
949: logit("Unkown port forwarding.");
950: goto out;
951: }
952: logit("Canceled forwarding.");
1.121 djm 953: } else {
1.209 djm 954: if (!parse_forward(&fwd, s, dynamic, remote)) {
1.121 djm 955: logit("Bad forwarding specification.");
956: goto out;
957: }
1.204 stevesk 958: if (local || dynamic) {
1.261 millert 959: if (!channel_setup_local_fwd_listener(&fwd,
960: &options.fwd_opts)) {
1.121 djm 961: logit("Port forwarding failed.");
962: goto out;
963: }
1.135 djm 964: } else {
1.261 millert 965: if (channel_request_remote_forwarding(&fwd) < 0) {
1.167 markus 966: logit("Port forwarding failed.");
967: goto out;
968: }
1.135 djm 969: }
1.121 djm 970: logit("Forwarding port.");
971: }
972:
1.97 jakob 973: out:
974: signal(SIGINT, handler);
1.233 djm 975: enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.250 djm 976: free(cmd);
977: free(fwd.listen_host);
1.261 millert 978: free(fwd.listen_path);
1.250 djm 979: free(fwd.connect_host);
1.261 millert 980: free(fwd.connect_path);
1.97 jakob 981: }
982:
1.244 dtucker 983: /* reasons to suppress output of an escape command in help output */
984: #define SUPPRESS_NEVER 0 /* never suppress, always show */
985: #define SUPPRESS_PROTO1 1 /* don't show in protocol 1 sessions */
986: #define SUPPRESS_MUXCLIENT 2 /* don't show in mux client sessions */
987: #define SUPPRESS_MUXMASTER 4 /* don't show in mux master sessions */
988: #define SUPPRESS_SYSLOG 8 /* don't show when logging to syslog */
989: struct escape_help_text {
990: const char *cmd;
991: const char *text;
992: unsigned int flags;
993: };
994: static struct escape_help_text esc_txt[] = {
995: {".", "terminate session", SUPPRESS_MUXMASTER},
996: {".", "terminate connection (and any multiplexed sessions)",
997: SUPPRESS_MUXCLIENT},
998: {"B", "send a BREAK to the remote system", SUPPRESS_PROTO1},
999: {"C", "open a command line", SUPPRESS_MUXCLIENT},
1000: {"R", "request rekey", SUPPRESS_PROTO1},
1.246 dtucker 1001: {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1.244 dtucker 1002: {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
1003: {"#", "list forwarded connections", SUPPRESS_NEVER},
1004: {"&", "background ssh (when waiting for connections to terminate)",
1005: SUPPRESS_MUXCLIENT},
1006: {"?", "this message", SUPPRESS_NEVER},
1007: };
1008:
1009: static void
1010: print_escape_help(Buffer *b, int escape_char, int protocol2, int mux_client,
1011: int using_stderr)
1012: {
1013: unsigned int i, suppress_flags;
1014: char string[1024];
1015:
1016: snprintf(string, sizeof string, "%c?\r\n"
1017: "Supported escape sequences:\r\n", escape_char);
1018: buffer_append(b, string, strlen(string));
1019:
1020: suppress_flags = (protocol2 ? 0 : SUPPRESS_PROTO1) |
1021: (mux_client ? SUPPRESS_MUXCLIENT : 0) |
1022: (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1023: (using_stderr ? 0 : SUPPRESS_SYSLOG);
1024:
1025: for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
1026: if (esc_txt[i].flags & suppress_flags)
1027: continue;
1.246 dtucker 1028: snprintf(string, sizeof string, " %c%-3s - %s\r\n",
1.244 dtucker 1029: escape_char, esc_txt[i].cmd, esc_txt[i].text);
1030: buffer_append(b, string, strlen(string));
1031: }
1032:
1033: snprintf(string, sizeof string,
1.246 dtucker 1034: " %c%c - send the escape character by typing it twice\r\n"
1.244 dtucker 1035: "(Note that escapes are only recognized immediately after "
1036: "newline.)\r\n", escape_char, escape_char);
1037: buffer_append(b, string, strlen(string));
1038: }
1039:
1.195 djm 1040: /*
1041: * Process the characters one by one, call with c==NULL for proto1 case.
1042: */
1.77 itojun 1043: static int
1.195 djm 1044: process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
1045: char *buf, int len)
1.31 markus 1046: {
1.32 markus 1047: char string[1024];
1.31 markus 1048: pid_t pid;
1049: int bytes = 0;
1.42 markus 1050: u_int i;
1051: u_char ch;
1.31 markus 1052: char *s;
1.195 djm 1053: int *escape_pendingp, escape_char;
1054: struct escape_filter_ctx *efc;
1.31 markus 1055:
1.195 djm 1056: if (c == NULL) {
1057: escape_pendingp = &escape_pending1;
1058: escape_char = escape_char1;
1059: } else {
1060: if (c->filter_ctx == NULL)
1061: return 0;
1062: efc = (struct escape_filter_ctx *)c->filter_ctx;
1063: escape_pendingp = &efc->escape_pending;
1064: escape_char = efc->escape_char;
1065: }
1066:
1.139 djm 1067: if (len <= 0)
1068: return (0);
1069:
1070: for (i = 0; i < (u_int)len; i++) {
1.31 markus 1071: /* Get one character at a time. */
1072: ch = buf[i];
1073:
1.195 djm 1074: if (*escape_pendingp) {
1.31 markus 1075: /* We have previously seen an escape character. */
1076: /* Clear the flag now. */
1.195 djm 1077: *escape_pendingp = 0;
1.31 markus 1078:
1079: /* Process the escaped character. */
1080: switch (ch) {
1081: case '.':
1082: /* Terminate the connection. */
1.195 djm 1083: snprintf(string, sizeof string, "%c.\r\n",
1084: escape_char);
1.32 markus 1085: buffer_append(berr, string, strlen(string));
1.31 markus 1086:
1.217 djm 1087: if (c && c->ctl_chan != -1) {
1.195 djm 1088: chan_read_failed(c);
1089: chan_write_failed(c);
1.252 dtucker 1090: if (c->detach_user)
1091: c->detach_user(c->self, NULL);
1.253 dtucker 1092: c->type = SSH_CHANNEL_ABANDONED;
1093: buffer_clear(&c->input);
1094: chan_ibuf_empty(c);
1.195 djm 1095: return 0;
1096: } else
1097: quit_pending = 1;
1.31 markus 1098: return -1;
1099:
1100: case 'Z' - 64:
1.195 djm 1101: /* XXX support this for mux clients */
1.217 djm 1102: if (c && c->ctl_chan != -1) {
1.245 dtucker 1103: char b[16];
1.195 djm 1104: noescape:
1.245 dtucker 1105: if (ch == 'Z' - 64)
1106: snprintf(b, sizeof b, "^Z");
1107: else
1108: snprintf(b, sizeof b, "%c", ch);
1.195 djm 1109: snprintf(string, sizeof string,
1.245 dtucker 1110: "%c%s escape not available to "
1.195 djm 1111: "multiplexed sessions\r\n",
1.245 dtucker 1112: escape_char, b);
1.195 djm 1113: buffer_append(berr, string,
1114: strlen(string));
1115: continue;
1116: }
1.197 djm 1117: /* Suspend the program. Inform the user */
1.195 djm 1118: snprintf(string, sizeof string,
1119: "%c^Z [suspend ssh]\r\n", escape_char);
1.32 markus 1120: buffer_append(berr, string, strlen(string));
1.31 markus 1121:
1122: /* Restore terminal modes and suspend. */
1123: client_suspend_self(bin, bout, berr);
1124:
1125: /* We have been continued. */
1126: continue;
1127:
1.111 markus 1128: case 'B':
1129: if (compat20) {
1130: snprintf(string, sizeof string,
1131: "%cB\r\n", escape_char);
1132: buffer_append(berr, string,
1133: strlen(string));
1.254 djm 1134: channel_request_start(c->self,
1.111 markus 1135: "break", 0);
1136: packet_put_int(1000);
1137: packet_send();
1138: }
1139: continue;
1140:
1.54 markus 1141: case 'R':
1.59 markus 1142: if (compat20) {
1143: if (datafellows & SSH_BUG_NOREKEY)
1.197 djm 1144: logit("Server does not "
1145: "support re-keying");
1.59 markus 1146: else
1147: need_rekeying = 1;
1148: }
1.54 markus 1149: continue;
1150:
1.242 dtucker 1151: case 'V':
1152: /* FALLTHROUGH */
1153: case 'v':
1154: if (c && c->ctl_chan != -1)
1155: goto noescape;
1156: if (!log_is_on_stderr()) {
1157: snprintf(string, sizeof string,
1158: "%c%c [Logging to syslog]\r\n",
1159: escape_char, ch);
1160: buffer_append(berr, string,
1161: strlen(string));
1162: continue;
1163: }
1164: if (ch == 'V' && options.log_level >
1165: SYSLOG_LEVEL_QUIET)
1166: log_change_level(--options.log_level);
1167: if (ch == 'v' && options.log_level <
1168: SYSLOG_LEVEL_DEBUG3)
1169: log_change_level(++options.log_level);
1170: snprintf(string, sizeof string,
1171: "%c%c [LogLevel %s]\r\n", escape_char, ch,
1172: log_level_name(options.log_level));
1173: buffer_append(berr, string, strlen(string));
1174: continue;
1175:
1.31 markus 1176: case '&':
1.217 djm 1177: if (c && c->ctl_chan != -1)
1.195 djm 1178: goto noescape;
1.31 markus 1179: /*
1.197 djm 1180: * Detach the program (continue to serve
1181: * connections, but put in background and no
1182: * more new connections).
1.31 markus 1183: */
1184: /* Restore tty modes. */
1.233 djm 1185: leave_raw_mode(
1186: options.request_tty == REQUEST_TTY_FORCE);
1.31 markus 1187:
1188: /* Stop listening for new connections. */
1.86 markus 1189: channel_stop_listening();
1.31 markus 1190:
1.86 markus 1191: snprintf(string, sizeof string,
1192: "%c& [backgrounded]\n", escape_char);
1193: buffer_append(berr, string, strlen(string));
1.31 markus 1194:
1195: /* Fork into background. */
1196: pid = fork();
1197: if (pid < 0) {
1198: error("fork: %.100s", strerror(errno));
1199: continue;
1200: }
1201: if (pid != 0) { /* This is the parent. */
1202: /* The parent just exits. */
1203: exit(0);
1204: }
1205: /* The child continues serving connections. */
1.86 markus 1206: if (compat20) {
1207: buffer_append(bin, "\004", 1);
1208: /* fake EOF on stdin */
1209: return -1;
1210: } else if (!stdin_eof) {
1211: /*
1.197 djm 1212: * Sending SSH_CMSG_EOF alone does not
1213: * always appear to be enough. So we
1214: * try to send an EOF character first.
1.86 markus 1215: */
1216: packet_start(SSH_CMSG_STDIN_DATA);
1217: packet_put_string("\004", 1);
1218: packet_send();
1219: /* Close stdin. */
1220: stdin_eof = 1;
1221: if (buffer_len(bin) == 0) {
1222: packet_start(SSH_CMSG_EOF);
1223: packet_send();
1224: }
1225: }
1226: continue;
1.31 markus 1227:
1228: case '?':
1.244 dtucker 1229: print_escape_help(berr, escape_char, compat20,
1230: (c && c->ctl_chan != -1),
1231: log_is_on_stderr());
1.31 markus 1232: continue;
1233:
1234: case '#':
1.195 djm 1235: snprintf(string, sizeof string, "%c#\r\n",
1236: escape_char);
1.32 markus 1237: buffer_append(berr, string, strlen(string));
1.31 markus 1238: s = channel_open_message();
1239: buffer_append(berr, s, strlen(s));
1.250 djm 1240: free(s);
1.97 jakob 1241: continue;
1242:
1243: case 'C':
1.217 djm 1244: if (c && c->ctl_chan != -1)
1.206 djm 1245: goto noescape;
1.99 markus 1246: process_cmdline();
1.31 markus 1247: continue;
1248:
1249: default:
1250: if (ch != escape_char) {
1251: buffer_put_char(bin, escape_char);
1252: bytes++;
1253: }
1254: /* Escaped characters fall through here */
1255: break;
1256: }
1257: } else {
1258: /*
1.197 djm 1259: * The previous character was not an escape char.
1260: * Check if this is an escape.
1.31 markus 1261: */
1262: if (last_was_cr && ch == escape_char) {
1.197 djm 1263: /*
1264: * It is. Set the flag and continue to
1265: * next character.
1266: */
1.195 djm 1267: *escape_pendingp = 1;
1.31 markus 1268: continue;
1269: }
1270: }
1271:
1272: /*
1273: * Normal character. Record whether it was a newline,
1274: * and append it to the buffer.
1275: */
1276: last_was_cr = (ch == '\r' || ch == '\n');
1277: buffer_put_char(bin, ch);
1278: bytes++;
1279: }
1280: return bytes;
1281: }
1282:
1.77 itojun 1283: static void
1.161 deraadt 1284: client_process_input(fd_set *readset)
1.17 markus 1285: {
1.21 deraadt 1286: int len;
1.31 markus 1287: char buf[8192];
1.16 markus 1288:
1.11 markus 1289: /* Read input from stdin. */
1290: if (FD_ISSET(fileno(stdin), readset)) {
1291: /* Read as much as possible. */
1292: len = read(fileno(stdin), buf, sizeof(buf));
1.64 markus 1293: if (len < 0 && (errno == EAGAIN || errno == EINTR))
1294: return; /* we'll try again later */
1.11 markus 1295: if (len <= 0) {
1.13 markus 1296: /*
1297: * Received EOF or error. They are treated
1298: * similarly, except that an error message is printed
1299: * if it was an error condition.
1300: */
1.11 markus 1301: if (len < 0) {
1.197 djm 1302: snprintf(buf, sizeof buf, "read: %.100s\r\n",
1303: strerror(errno));
1.11 markus 1304: buffer_append(&stderr_buffer, buf, strlen(buf));
1305: }
1306: /* Mark that we have seen EOF. */
1307: stdin_eof = 1;
1.13 markus 1308: /*
1309: * Send an EOF message to the server unless there is
1310: * data in the buffer. If there is data in the
1311: * buffer, no message will be sent now. Code
1312: * elsewhere will send the EOF when the buffer
1313: * becomes empty if stdin_eof is set.
1314: */
1.11 markus 1315: if (buffer_len(&stdin_buffer) == 0) {
1.1 deraadt 1316: packet_start(SSH_CMSG_EOF);
1317: packet_send();
1.11 markus 1318: }
1.195 djm 1319: } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1.13 markus 1320: /*
1321: * Normal successful read, and no escape character.
1322: * Just append the data to buffer.
1323: */
1.11 markus 1324: buffer_append(&stdin_buffer, buf, len);
1325: } else {
1.13 markus 1326: /*
1.197 djm 1327: * Normal, successful read. But we have an escape
1328: * character and have to process the characters one
1329: * by one.
1.13 markus 1330: */
1.195 djm 1331: if (process_escapes(NULL, &stdin_buffer,
1332: &stdout_buffer, &stderr_buffer, buf, len) == -1)
1.31 markus 1333: return;
1.11 markus 1334: }
1335: }
1336: }
1337:
1.77 itojun 1338: static void
1.161 deraadt 1339: client_process_output(fd_set *writeset)
1.11 markus 1340: {
1341: int len;
1342: char buf[100];
1.1 deraadt 1343:
1.11 markus 1344: /* Write buffered output to stdout. */
1345: if (FD_ISSET(fileno(stdout), writeset)) {
1346: /* Write as much data as possible. */
1347: len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1.14 deraadt 1348: buffer_len(&stdout_buffer));
1.11 markus 1349: if (len <= 0) {
1.64 markus 1350: if (errno == EINTR || errno == EAGAIN)
1.11 markus 1351: len = 0;
1352: else {
1.13 markus 1353: /*
1354: * An error or EOF was encountered. Put an
1355: * error message to stderr buffer.
1356: */
1.197 djm 1357: snprintf(buf, sizeof buf,
1358: "write stdout: %.50s\r\n", strerror(errno));
1.11 markus 1359: buffer_append(&stderr_buffer, buf, strlen(buf));
1360: quit_pending = 1;
1361: return;
1362: }
1363: }
1364: /* Consume printed data from the buffer. */
1365: buffer_consume(&stdout_buffer, len);
1366: }
1367: /* Write buffered output to stderr. */
1368: if (FD_ISSET(fileno(stderr), writeset)) {
1369: /* Write as much data as possible. */
1370: len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1.14 deraadt 1371: buffer_len(&stderr_buffer));
1.11 markus 1372: if (len <= 0) {
1.64 markus 1373: if (errno == EINTR || errno == EAGAIN)
1.11 markus 1374: len = 0;
1375: else {
1.197 djm 1376: /*
1377: * EOF or error, but can't even print
1378: * error message.
1379: */
1.11 markus 1380: quit_pending = 1;
1381: return;
1382: }
1383: }
1384: /* Consume printed characters from the buffer. */
1385: buffer_consume(&stderr_buffer, len);
1386: }
1.1 deraadt 1387: }
1388:
1.13 markus 1389: /*
1.15 markus 1390: * Get packets from the connection input buffer, and process them as long as
1391: * there are packets available.
1392: *
1393: * Any unknown packets received during the actual
1394: * session cause the session to terminate. This is
1395: * intended to make debugging easier since no
1396: * confirmations are sent. Any compatible protocol
1397: * extensions must be negotiated during the
1398: * preparatory phase.
1399: */
1400:
1.77 itojun 1401: static void
1.49 itojun 1402: client_process_buffered_input_packets(void)
1.15 markus 1403: {
1.197 djm 1404: dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1.263 markus 1405: compat20 ? active_state->kex : NULL);
1.15 markus 1406: }
1407:
1.31 markus 1408: /* scan buf[] for '~' before sending data to the peer */
1.30 markus 1409:
1.195 djm 1410: /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1411: void *
1412: client_new_escape_filter_ctx(int escape_char)
1413: {
1414: struct escape_filter_ctx *ret;
1415:
1.255 djm 1416: ret = xcalloc(1, sizeof(*ret));
1.195 djm 1417: ret->escape_pending = 0;
1418: ret->escape_char = escape_char;
1419: return (void *)ret;
1420: }
1421:
1.198 djm 1422: /* Free the escape filter context on channel free */
1423: void
1424: client_filter_cleanup(int cid, void *ctx)
1425: {
1.250 djm 1426: free(ctx);
1.198 djm 1427: }
1428:
1.195 djm 1429: int
1430: client_simple_escape_filter(Channel *c, char *buf, int len)
1.30 markus 1431: {
1.190 djm 1432: if (c->extended_usage != CHAN_EXTENDED_WRITE)
1433: return 0;
1434:
1.195 djm 1435: return process_escapes(c, &c->input, &c->output, &c->extended,
1436: buf, len);
1.30 markus 1437: }
1438:
1.77 itojun 1439: static void
1.60 markus 1440: client_channel_closed(int id, void *arg)
1441: {
1.83 markus 1442: channel_cancel_cleanup(id);
1.60 markus 1443: session_closed = 1;
1.233 djm 1444: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.60 markus 1445: }
1446:
1.15 markus 1447: /*
1.13 markus 1448: * Implements the interactive session with the server. This is called after
1449: * the user has been authenticated, and a command has been started on the
1.72 stevesk 1450: * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1451: * used as an escape character for terminating or suspending the session.
1.13 markus 1452: */
1.1 deraadt 1453:
1.20 markus 1454: int
1.30 markus 1455: client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1.1 deraadt 1456: {
1.46 markus 1457: fd_set *readset = NULL, *writeset = NULL;
1.11 markus 1458: double start_time, total_time;
1.130 avsm 1459: int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1.200 markus 1460: u_int64_t ibytes, obytes;
1.130 avsm 1461: u_int nalloc = 0;
1.11 markus 1462: char buf[100];
1463:
1464: debug("Entering interactive session.");
1465:
1466: start_time = get_current_time();
1467:
1468: /* Initialize variables. */
1.195 djm 1469: escape_pending1 = 0;
1.11 markus 1470: last_was_cr = 1;
1471: exit_status = -1;
1472: stdin_eof = 0;
1473: buffer_high = 64 * 1024;
1474: connection_in = packet_get_connection_in();
1475: connection_out = packet_get_connection_out();
1.46 markus 1476: max_fd = MAX(connection_in, connection_out);
1477:
1478: if (!compat20) {
1.63 markus 1479: /* enable nonblocking unless tty */
1480: if (!isatty(fileno(stdin)))
1481: set_nonblock(fileno(stdin));
1482: if (!isatty(fileno(stdout)))
1483: set_nonblock(fileno(stdout));
1484: if (!isatty(fileno(stderr)))
1485: set_nonblock(fileno(stderr));
1.46 markus 1486: max_fd = MAX(max_fd, fileno(stdin));
1487: max_fd = MAX(max_fd, fileno(stdout));
1488: max_fd = MAX(max_fd, fileno(stderr));
1489: }
1.11 markus 1490: quit_pending = 0;
1.195 djm 1491: escape_char1 = escape_char_arg;
1.11 markus 1492:
1493: /* Initialize buffers. */
1494: buffer_init(&stdin_buffer);
1495: buffer_init(&stdout_buffer);
1496: buffer_init(&stderr_buffer);
1497:
1.15 markus 1498: client_init_dispatch();
1499:
1.105 markus 1500: /*
1501: * Set signal handlers, (e.g. to restore non-blocking mode)
1502: * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1503: */
1.131 djm 1504: if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1505: signal(SIGHUP, signal_handler);
1.105 markus 1506: if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1507: signal(SIGINT, signal_handler);
1508: if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1509: signal(SIGQUIT, signal_handler);
1510: if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1511: signal(SIGTERM, signal_handler);
1.132 djm 1512: signal(SIGWINCH, window_change_handler);
1.11 markus 1513:
1514: if (have_pty)
1.233 djm 1515: enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11 markus 1516:
1.48 markus 1517: if (compat20) {
1518: session_ident = ssh2_chan_id;
1.232 djm 1519: if (session_ident != -1) {
1520: if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1521: channel_register_filter(session_ident,
1522: client_simple_escape_filter, NULL,
1523: client_filter_cleanup,
1524: client_new_escape_filter_ctx(
1525: escape_char_arg));
1526: }
1.60 markus 1527: channel_register_cleanup(session_ident,
1.143 djm 1528: client_channel_closed, 0);
1.232 djm 1529: }
1.48 markus 1530: } else {
1531: /* Check if we should immediately send eof on stdin. */
1.16 markus 1532: client_check_initial_eof_on_stdin();
1.48 markus 1533: }
1.30 markus 1534:
1.11 markus 1535: /* Main loop of the client for the interactive session mode. */
1536: while (!quit_pending) {
1537:
1.13 markus 1538: /* Process buffered packets sent by the server. */
1.11 markus 1539: client_process_buffered_input_packets();
1540:
1.60 markus 1541: if (compat20 && session_closed && !channel_still_open())
1542: break;
1543:
1.263 markus 1544: rekeying = (active_state->kex != NULL && !active_state->kex->done);
1.16 markus 1545:
1.56 markus 1546: if (rekeying) {
1547: debug("rekeying in progress");
1548: } else {
1549: /*
1550: * Make packets of buffered stdin data, and buffer
1551: * them for sending to the server.
1552: */
1553: if (!compat20)
1554: client_make_packets_from_stdin_data();
1.11 markus 1555:
1.56 markus 1556: /*
1557: * Make packets from buffered channel data, and
1558: * enqueue them for sending to the server.
1559: */
1560: if (packet_not_very_much_data_to_write())
1561: channel_output_poll();
1.11 markus 1562:
1.56 markus 1563: /*
1564: * Check if the window size has changed, and buffer a
1565: * message about it to the server if so.
1566: */
1567: client_check_window_change();
1.11 markus 1568:
1.56 markus 1569: if (quit_pending)
1570: break;
1571: }
1.13 markus 1572: /*
1573: * Wait until we have something to do (something becomes
1574: * available on one of the descriptors).
1575: */
1.81 markus 1576: max_fd2 = max_fd;
1.56 markus 1577: client_wait_until_can_do_something(&readset, &writeset,
1.81 markus 1578: &max_fd2, &nalloc, rekeying);
1.11 markus 1579:
1580: if (quit_pending)
1581: break;
1582:
1.56 markus 1583: /* Do channel operations unless rekeying in progress. */
1584: if (!rekeying) {
1585: channel_after_select(readset, writeset);
1.108 markus 1586: if (need_rekeying || packet_need_rekeying()) {
1587: debug("need rekeying");
1.263 markus 1588: active_state->kex->done = 0;
1589: kex_send_kexinit(active_state->kex);
1.56 markus 1590: need_rekeying = 0;
1591: }
1592: }
1.11 markus 1593:
1.17 markus 1594: /* Buffer input from the connection. */
1.46 markus 1595: client_process_net_input(readset);
1.17 markus 1596:
1597: if (quit_pending)
1598: break;
1.11 markus 1599:
1.17 markus 1600: if (!compat20) {
1601: /* Buffer data from stdin */
1.46 markus 1602: client_process_input(readset);
1.17 markus 1603: /*
1604: * Process output to stdout and stderr. Output to
1605: * the connection is processed elsewhere (above).
1606: */
1.46 markus 1607: client_process_output(writeset);
1.214 andreas 1608: }
1609:
1610: if (session_resumed) {
1611: connection_in = packet_get_connection_in();
1612: connection_out = packet_get_connection_out();
1613: max_fd = MAX(max_fd, connection_out);
1614: max_fd = MAX(max_fd, connection_in);
1615: session_resumed = 0;
1.17 markus 1616: }
1.11 markus 1617:
1.197 djm 1618: /*
1619: * Send as much buffered packet data as possible to the
1620: * sender.
1621: */
1.46 markus 1622: if (FD_ISSET(connection_out, writeset))
1.11 markus 1623: packet_write_poll();
1.222 djm 1624:
1625: /*
1626: * If we are a backgrounded control master, and the
1627: * timeout has expired without any active client
1628: * connections, then quit.
1629: */
1630: if (control_persist_exit_time > 0) {
1.251 dtucker 1631: if (monotime() >= control_persist_exit_time) {
1.222 djm 1632: debug("ControlPersist timeout expired");
1633: break;
1634: }
1635: }
1.11 markus 1636: }
1.250 djm 1637: free(readset);
1638: free(writeset);
1.11 markus 1639:
1640: /* Terminate the session. */
1641:
1642: /* Stop watching for window change. */
1.132 djm 1643: signal(SIGWINCH, SIG_DFL);
1.211 andreas 1644:
1.213 stevesk 1645: if (compat20) {
1646: packet_start(SSH2_MSG_DISCONNECT);
1647: packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1648: packet_put_cstring("disconnected by user");
1.219 djm 1649: packet_put_cstring(""); /* language tag */
1.213 stevesk 1650: packet_send();
1651: packet_write_wait();
1652: }
1.11 markus 1653:
1.76 markus 1654: channel_free_all();
1.11 markus 1655:
1.75 markus 1656: if (have_pty)
1.233 djm 1657: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.75 markus 1658:
1659: /* restore blocking io */
1660: if (!isatty(fileno(stdin)))
1661: unset_nonblock(fileno(stdin));
1662: if (!isatty(fileno(stdout)))
1663: unset_nonblock(fileno(stdout));
1664: if (!isatty(fileno(stderr)))
1665: unset_nonblock(fileno(stderr));
1.116 dtucker 1666:
1667: /*
1668: * If there was no shell or command requested, there will be no remote
1669: * exit status to be returned. In that case, clear error code if the
1670: * connection was deliberately terminated at this end.
1671: */
1672: if (no_shell_flag && received_signal == SIGTERM) {
1673: received_signal = 0;
1674: exit_status = 0;
1675: }
1.75 markus 1676:
1.113 markus 1677: if (received_signal)
1.89 itojun 1678: fatal("Killed by signal %d.", (int) received_signal);
1.75 markus 1679:
1.13 markus 1680: /*
1681: * In interactive mode (with pseudo tty) display a message indicating
1682: * that the connection has been closed.
1683: */
1.11 markus 1684: if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1.197 djm 1685: snprintf(buf, sizeof buf,
1686: "Connection to %.64s closed.\r\n", host);
1.11 markus 1687: buffer_append(&stderr_buffer, buf, strlen(buf));
1688: }
1.70 markus 1689:
1.11 markus 1690: /* Output any buffered data for stdout. */
1.231 djm 1691: if (buffer_len(&stdout_buffer) > 0) {
1.230 djm 1692: len = atomicio(vwrite, fileno(stdout),
1693: buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1.231 djm 1694: if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1.11 markus 1695: error("Write failed flushing stdout buffer.");
1.231 djm 1696: else
1697: buffer_consume(&stdout_buffer, len);
1.11 markus 1698: }
1699:
1700: /* Output any buffered data for stderr. */
1.231 djm 1701: if (buffer_len(&stderr_buffer) > 0) {
1.230 djm 1702: len = atomicio(vwrite, fileno(stderr),
1703: buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1.231 djm 1704: if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1.11 markus 1705: error("Write failed flushing stderr buffer.");
1.231 djm 1706: else
1707: buffer_consume(&stderr_buffer, len);
1.11 markus 1708: }
1709:
1710: /* Clear and free any buffers. */
1711: memset(buf, 0, sizeof(buf));
1712: buffer_free(&stdin_buffer);
1713: buffer_free(&stdout_buffer);
1714: buffer_free(&stderr_buffer);
1715:
1716: /* Report bytes transferred, and transfer rates. */
1717: total_time = get_current_time() - start_time;
1.263 markus 1718: packet_get_bytes(&ibytes, &obytes);
1.200 markus 1719: verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1.229 djm 1720: (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1.11 markus 1721: if (total_time > 0)
1.200 markus 1722: verbose("Bytes per second: sent %.1f, received %.1f",
1723: obytes / total_time, ibytes / total_time);
1.11 markus 1724: /* Return the exit status of the program. */
1725: debug("Exit status %d", exit_status);
1726: return exit_status;
1.15 markus 1727: }
1728:
1729: /*********/
1730:
1.264 ! markus 1731: static int
1.94 markus 1732: client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1.15 markus 1733: {
1.42 markus 1734: u_int data_len;
1.15 markus 1735: char *data = packet_get_string(&data_len);
1.93 markus 1736: packet_check_eom();
1.15 markus 1737: buffer_append(&stdout_buffer, data, data_len);
1.258 djm 1738: explicit_bzero(data, data_len);
1.250 djm 1739: free(data);
1.264 ! markus 1740: return 0;
1.15 markus 1741: }
1.264 ! markus 1742: static int
1.94 markus 1743: client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1.15 markus 1744: {
1.42 markus 1745: u_int data_len;
1.15 markus 1746: char *data = packet_get_string(&data_len);
1.93 markus 1747: packet_check_eom();
1.15 markus 1748: buffer_append(&stderr_buffer, data, data_len);
1.258 djm 1749: explicit_bzero(data, data_len);
1.250 djm 1750: free(data);
1.264 ! markus 1751: return 0;
1.15 markus 1752: }
1.264 ! markus 1753: static int
1.94 markus 1754: client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1.15 markus 1755: {
1756: exit_status = packet_get_int();
1.93 markus 1757: packet_check_eom();
1.15 markus 1758: /* Acknowledge the exit. */
1759: packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1760: packet_send();
1761: /*
1762: * Must wait for packet to be sent since we are
1763: * exiting the loop.
1764: */
1765: packet_write_wait();
1766: /* Flag that we want to exit. */
1767: quit_pending = 1;
1.264 ! markus 1768: return 0;
1.15 markus 1769: }
1.264 ! markus 1770: static int
1.115 markus 1771: client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1772: {
1773: Channel *c = NULL;
1.262 djm 1774: int r, remote_id, sock;
1.115 markus 1775:
1776: /* Read the remote channel number from the message. */
1777: remote_id = packet_get_int();
1778: packet_check_eom();
1779:
1780: /*
1781: * Get a connection to the local authentication agent (this may again
1782: * get forwarded).
1783: */
1.262 djm 1784: if ((r = ssh_get_authentication_socket(&sock)) != 0 &&
1785: r != SSH_ERR_AGENT_NOT_PRESENT)
1786: debug("%s: ssh_get_authentication_socket: %s",
1787: __func__, ssh_err(r));
1788:
1.115 markus 1789:
1790: /*
1791: * If we could not connect the agent, send an error message back to
1792: * the server. This should never happen unless the agent dies,
1793: * because authentication forwarding is only enabled if we have an
1794: * agent.
1795: */
1796: if (sock >= 0) {
1797: c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1798: -1, 0, 0, 0, "authentication agent connection", 1);
1799: c->remote_id = remote_id;
1800: c->force_drain = 1;
1801: }
1802: if (c == NULL) {
1803: packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1804: packet_put_int(remote_id);
1805: } else {
1806: /* Send a confirmation to the remote host. */
1807: debug("Forwarding authentication connection.");
1808: packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1809: packet_put_int(remote_id);
1810: packet_put_int(c->self);
1811: }
1812: packet_send();
1.264 ! markus 1813: return 0;
1.115 markus 1814: }
1.15 markus 1815:
1.77 itojun 1816: static Channel *
1.40 markus 1817: client_request_forwarded_tcpip(const char *request_type, int rchan)
1818: {
1.103 deraadt 1819: Channel *c = NULL;
1.40 markus 1820: char *listen_address, *originator_address;
1.208 djm 1821: u_short listen_port, originator_port;
1.40 markus 1822:
1823: /* Get rest of the packet */
1824: listen_address = packet_get_string(NULL);
1825: listen_port = packet_get_int();
1826: originator_address = packet_get_string(NULL);
1827: originator_port = packet_get_int();
1.93 markus 1828: packet_check_eom();
1.40 markus 1829:
1.261 millert 1830: debug("%s: listen %s port %d, originator %s port %d", __func__,
1831: listen_address, listen_port, originator_address, originator_port);
1.191 djm 1832:
1.260 markus 1833: c = channel_connect_by_listen_address(listen_address, listen_port,
1.191 djm 1834: "forwarded-tcpip", originator_address);
1.40 markus 1835:
1.250 djm 1836: free(originator_address);
1837: free(listen_address);
1.40 markus 1838: return c;
1839: }
1840:
1.103 deraadt 1841: static Channel *
1.261 millert 1842: client_request_forwarded_streamlocal(const char *request_type, int rchan)
1843: {
1844: Channel *c = NULL;
1845: char *listen_path;
1846:
1847: /* Get the remote path. */
1848: listen_path = packet_get_string(NULL);
1849: /* XXX: Skip reserved field for now. */
1850: if (packet_get_string_ptr(NULL) == NULL)
1851: fatal("%s: packet_get_string_ptr failed", __func__);
1852: packet_check_eom();
1853:
1854: debug("%s: %s", __func__, listen_path);
1855:
1856: c = channel_connect_by_listen_path(listen_path,
1857: "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1858: free(listen_path);
1859: return c;
1860: }
1861:
1862: static Channel *
1.40 markus 1863: client_request_x11(const char *request_type, int rchan)
1864: {
1865: Channel *c = NULL;
1866: char *originator;
1.208 djm 1867: u_short originator_port;
1.67 markus 1868: int sock;
1.40 markus 1869:
1870: if (!options.forward_x11) {
1871: error("Warning: ssh server tried X11 forwarding.");
1.197 djm 1872: error("Warning: this is probably a break-in attempt by a "
1873: "malicious server.");
1.221 djm 1874: return NULL;
1875: }
1.251 dtucker 1876: if (x11_refuse_time != 0 && monotime() >= x11_refuse_time) {
1.221 djm 1877: verbose("Rejected X11 connection after ForwardX11Timeout "
1878: "expired");
1.40 markus 1879: return NULL;
1880: }
1881: originator = packet_get_string(NULL);
1882: if (datafellows & SSH_BUG_X11FWD) {
1883: debug2("buggy server: x11 request w/o originator_port");
1884: originator_port = 0;
1885: } else {
1886: originator_port = packet_get_int();
1887: }
1.93 markus 1888: packet_check_eom();
1.40 markus 1889: /* XXX check permission */
1.47 markus 1890: debug("client_request_x11: request from %s %d", originator,
1891: originator_port);
1.250 djm 1892: free(originator);
1.40 markus 1893: sock = x11_connect_display();
1.67 markus 1894: if (sock < 0)
1895: return NULL;
1896: c = channel_new("x11",
1897: SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1.110 markus 1898: CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1.82 markus 1899: c->force_drain = 1;
1.40 markus 1900: return c;
1901: }
1902:
1.103 deraadt 1903: static Channel *
1.40 markus 1904: client_request_agent(const char *request_type, int rchan)
1905: {
1906: Channel *c = NULL;
1.262 djm 1907: int r, sock;
1.40 markus 1908:
1909: if (!options.forward_agent) {
1910: error("Warning: ssh server tried agent forwarding.");
1.197 djm 1911: error("Warning: this is probably a break-in attempt by a "
1912: "malicious server.");
1.40 markus 1913: return NULL;
1914: }
1.262 djm 1915: if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1916: if (r != SSH_ERR_AGENT_NOT_PRESENT)
1917: debug("%s: ssh_get_authentication_socket: %s",
1918: __func__, ssh_err(r));
1.67 markus 1919: return NULL;
1.262 djm 1920: }
1.67 markus 1921: c = channel_new("authentication agent connection",
1922: SSH_CHANNEL_OPEN, sock, sock, -1,
1.185 dtucker 1923: CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1.110 markus 1924: "authentication agent connection", 1);
1.82 markus 1925: c->force_drain = 1;
1.40 markus 1926: return c;
1.180 djm 1927: }
1928:
1929: int
1930: client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1931: {
1932: Channel *c;
1933: int fd;
1934:
1935: if (tun_mode == SSH_TUNMODE_NO)
1936: return 0;
1937:
1938: if (!compat20) {
1.207 stevesk 1939: error("Tunnel forwarding is not supported for protocol 1");
1.180 djm 1940: return -1;
1941: }
1942:
1943: debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1944:
1945: /* Open local tunnel device */
1946: if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1947: error("Tunnel device open failed.");
1948: return -1;
1949: }
1950:
1951: c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1952: CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1953: c->datagram = 1;
1954:
1955: packet_start(SSH2_MSG_CHANNEL_OPEN);
1956: packet_put_cstring("tun@openssh.com");
1957: packet_put_int(c->self);
1958: packet_put_int(c->local_window_max);
1959: packet_put_int(c->local_maxpacket);
1960: packet_put_int(tun_mode);
1961: packet_put_int(remote_tun);
1962: packet_send();
1963:
1964: return 0;
1.40 markus 1965: }
1966:
1.22 markus 1967: /* XXXX move to generic input handler */
1.264 ! markus 1968: static int
1.94 markus 1969: client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1.22 markus 1970: {
1971: Channel *c = NULL;
1972: char *ctype;
1973: int rchan;
1.102 markus 1974: u_int rmaxpack, rwindow, len;
1.22 markus 1975:
1976: ctype = packet_get_string(&len);
1977: rchan = packet_get_int();
1978: rwindow = packet_get_int();
1979: rmaxpack = packet_get_int();
1980:
1.24 markus 1981: debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1.22 markus 1982: ctype, rchan, rwindow, rmaxpack);
1983:
1.40 markus 1984: if (strcmp(ctype, "forwarded-tcpip") == 0) {
1985: c = client_request_forwarded_tcpip(ctype, rchan);
1.261 millert 1986: } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1987: c = client_request_forwarded_streamlocal(ctype, rchan);
1.40 markus 1988: } else if (strcmp(ctype, "x11") == 0) {
1989: c = client_request_x11(ctype, rchan);
1990: } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1991: c = client_request_agent(ctype, rchan);
1.22 markus 1992: }
1993: /* XXX duplicate : */
1994: if (c != NULL) {
1995: debug("confirm %s", ctype);
1996: c->remote_id = rchan;
1997: c->remote_window = rwindow;
1998: c->remote_maxpacket = rmaxpack;
1.69 markus 1999: if (c->type != SSH_CHANNEL_CONNECTING) {
2000: packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
2001: packet_put_int(c->remote_id);
2002: packet_put_int(c->self);
2003: packet_put_int(c->local_window);
2004: packet_put_int(c->local_maxpacket);
2005: packet_send();
2006: }
1.22 markus 2007: } else {
2008: debug("failure %s", ctype);
2009: packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
2010: packet_put_int(rchan);
2011: packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1.66 markus 2012: if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.69 markus 2013: packet_put_cstring("open failed");
1.66 markus 2014: packet_put_cstring("");
2015: }
1.22 markus 2016: packet_send();
2017: }
1.250 djm 2018: free(ctype);
1.264 ! markus 2019: return 0;
1.22 markus 2020: }
1.264 ! markus 2021: static int
1.94 markus 2022: client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1.48 markus 2023: {
2024: Channel *c = NULL;
1.123 djm 2025: int exitval, id, reply, success = 0;
1.48 markus 2026: char *rtype;
2027:
2028: id = packet_get_int();
2029: rtype = packet_get_string(NULL);
2030: reply = packet_get_char();
2031:
2032: debug("client_input_channel_req: channel %d rtype %s reply %d",
2033: id, rtype, reply);
2034:
1.128 djm 2035: if (id == -1) {
2036: error("client_input_channel_req: request for channel -1");
2037: } else if ((c = channel_lookup(id)) == NULL) {
1.197 djm 2038: error("client_input_channel_req: channel %d: "
2039: "unknown channel", id);
1.193 markus 2040: } else if (strcmp(rtype, "eow@openssh.com") == 0) {
2041: packet_check_eom();
2042: chan_rcvd_eow(c);
1.48 markus 2043: } else if (strcmp(rtype, "exit-status") == 0) {
1.123 djm 2044: exitval = packet_get_int();
1.217 djm 2045: if (c->ctl_chan != -1) {
2046: mux_exit_message(c, exitval);
1.215 djm 2047: success = 1;
2048: } else if (id == session_ident) {
2049: /* Record exit value of local session */
1.123 djm 2050: success = 1;
2051: exit_status = exitval;
1.215 djm 2052: } else {
1.218 djm 2053: /* Probably for a mux channel that has already closed */
2054: debug("%s: no sink for exit-status on channel %d",
2055: __func__, id);
1.123 djm 2056: }
1.93 markus 2057: packet_check_eom();
1.48 markus 2058: }
1.259 djm 2059: if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1.48 markus 2060: packet_start(success ?
2061: SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1.205 markus 2062: packet_put_int(c->remote_id);
1.48 markus 2063: packet_send();
2064: }
1.250 djm 2065: free(rtype);
1.264 ! markus 2066: return 0;
1.48 markus 2067: }
1.264 ! markus 2068: static int
1.95 markus 2069: client_input_global_request(int type, u_int32_t seq, void *ctxt)
2070: {
2071: char *rtype;
2072: int want_reply;
2073: int success = 0;
2074:
2075: rtype = packet_get_string(NULL);
2076: want_reply = packet_get_char();
1.117 markus 2077: debug("client_input_global_request: rtype %s want_reply %d",
2078: rtype, want_reply);
1.95 markus 2079: if (want_reply) {
2080: packet_start(success ?
2081: SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2082: packet_send();
2083: packet_write_wait();
2084: }
1.250 djm 2085: free(rtype);
1.264 ! markus 2086: return 0;
1.95 markus 2087: }
1.22 markus 2088:
1.123 djm 2089: void
1.129 deraadt 2090: client_session2_setup(int id, int want_tty, int want_subsystem,
1.190 djm 2091: const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
1.123 djm 2092: {
2093: int len;
1.132 djm 2094: Channel *c = NULL;
1.123 djm 2095:
2096: debug2("%s: id %d", __func__, id);
2097:
1.132 djm 2098: if ((c = channel_lookup(id)) == NULL)
2099: fatal("client_session2_setup: channel %d: unknown channel", id);
1.224 djm 2100:
2101: packet_set_interactive(want_tty,
2102: options.ip_qos_interactive, options.ip_qos_bulk);
1.132 djm 2103:
1.123 djm 2104: if (want_tty) {
2105: struct winsize ws;
2106:
2107: /* Store window size in the packet. */
2108: if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2109: memset(&ws, 0, sizeof(ws));
2110:
1.190 djm 2111: channel_request_start(id, "pty-req", 1);
1.234 djm 2112: client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
1.123 djm 2113: packet_put_cstring(term != NULL ? term : "");
1.158 deraadt 2114: packet_put_int((u_int)ws.ws_col);
2115: packet_put_int((u_int)ws.ws_row);
2116: packet_put_int((u_int)ws.ws_xpixel);
2117: packet_put_int((u_int)ws.ws_ypixel);
1.194 djm 2118: if (tiop == NULL)
2119: tiop = get_saved_tio();
2120: tty_make_modes(-1, tiop);
1.123 djm 2121: packet_send();
2122: /* XXX wait for reply */
1.132 djm 2123: c->client_tty = 1;
1.123 djm 2124: }
2125:
2126: /* Transfer any environment variables from client to server */
1.126 djm 2127: if (options.num_send_env != 0 && env != NULL) {
1.123 djm 2128: int i, j, matched;
2129: char *name, *val;
2130:
2131: debug("Sending environment.");
1.126 djm 2132: for (i = 0; env[i] != NULL; i++) {
1.123 djm 2133: /* Split */
1.126 djm 2134: name = xstrdup(env[i]);
1.123 djm 2135: if ((val = strchr(name, '=')) == NULL) {
1.250 djm 2136: free(name);
1.123 djm 2137: continue;
2138: }
2139: *val++ = '\0';
2140:
2141: matched = 0;
2142: for (j = 0; j < options.num_send_env; j++) {
2143: if (match_pattern(name, options.send_env[j])) {
2144: matched = 1;
2145: break;
2146: }
2147: }
2148: if (!matched) {
2149: debug3("Ignored env %s", name);
1.250 djm 2150: free(name);
1.123 djm 2151: continue;
2152: }
2153:
2154: debug("Sending env %s = %s", name, val);
2155: channel_request_start(id, "env", 0);
2156: packet_put_cstring(name);
2157: packet_put_cstring(val);
2158: packet_send();
1.250 djm 2159: free(name);
1.123 djm 2160: }
2161: }
2162:
2163: len = buffer_len(cmd);
2164: if (len > 0) {
2165: if (len > 900)
2166: len = 900;
2167: if (want_subsystem) {
1.190 djm 2168: debug("Sending subsystem: %.*s",
2169: len, (u_char*)buffer_ptr(cmd));
2170: channel_request_start(id, "subsystem", 1);
1.234 djm 2171: client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
1.123 djm 2172: } else {
1.190 djm 2173: debug("Sending command: %.*s",
2174: len, (u_char*)buffer_ptr(cmd));
2175: channel_request_start(id, "exec", 1);
1.234 djm 2176: client_expect_confirm(id, "exec", CONFIRM_CLOSE);
1.123 djm 2177: }
2178: packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2179: packet_send();
2180: } else {
1.190 djm 2181: channel_request_start(id, "shell", 1);
1.234 djm 2182: client_expect_confirm(id, "shell", CONFIRM_CLOSE);
1.123 djm 2183: packet_send();
2184: }
2185: }
2186:
1.77 itojun 2187: static void
1.49 itojun 2188: client_init_dispatch_20(void)
1.16 markus 2189: {
1.55 markus 2190: dispatch_init(&dispatch_protocol_error);
1.100 markus 2191:
1.16 markus 2192: dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2193: dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2194: dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2195: dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1.22 markus 2196: dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1.16 markus 2197: dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2198: dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1.48 markus 2199: dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1.16 markus 2200: dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1.189 djm 2201: dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2202: dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
1.95 markus 2203: dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1.55 markus 2204:
2205: /* rekeying */
2206: dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.100 markus 2207:
2208: /* global request reply messages */
2209: dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2210: dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1.16 markus 2211: }
1.197 djm 2212:
1.77 itojun 2213: static void
1.49 itojun 2214: client_init_dispatch_13(void)
1.15 markus 2215: {
2216: dispatch_init(NULL);
2217: dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2218: dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2219: dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2220: dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2221: dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2222: dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2223: dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2224: dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2225: dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
1.39 markus 2226:
2227: dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
1.115 markus 2228: &client_input_agent_open : &deny_input_open);
1.39 markus 2229: dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2230: &x11_input_open : &deny_input_open);
1.15 markus 2231: }
1.197 djm 2232:
1.77 itojun 2233: static void
1.49 itojun 2234: client_init_dispatch_15(void)
1.15 markus 2235: {
2236: client_init_dispatch_13();
2237: dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2238: dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2239: }
1.197 djm 2240:
1.79 stevesk 2241: static void
1.49 itojun 2242: client_init_dispatch(void)
1.15 markus 2243: {
1.16 markus 2244: if (compat20)
2245: client_init_dispatch_20();
2246: else if (compat13)
1.15 markus 2247: client_init_dispatch_13();
2248: else
2249: client_init_dispatch_15();
1.232 djm 2250: }
2251:
2252: void
2253: client_stop_mux(void)
2254: {
2255: if (options.control_path != NULL && muxserver_sock != -1)
2256: unlink(options.control_path);
2257: /*
1.247 dtucker 2258: * If we are in persist mode, or don't have a shell, signal that we
2259: * should close when all active channels are closed.
1.232 djm 2260: */
1.247 dtucker 2261: if (options.control_persist || no_shell_flag) {
1.232 djm 2262: session_closed = 1;
1.235 djm 2263: setproctitle("[stopped mux]");
2264: }
1.113 markus 2265: }
2266:
2267: /* client specific fatal cleanup */
2268: void
1.114 markus 2269: cleanup_exit(int i)
1.113 markus 2270: {
1.233 djm 2271: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.113 markus 2272: leave_non_blocking();
1.192 djm 2273: if (options.control_path != NULL && muxserver_sock != -1)
1.123 djm 2274: unlink(options.control_path);
1.223 djm 2275: ssh_kill_proxy_command();
1.114 markus 2276: _exit(i);
1.1 deraadt 2277: }