Annotation of src/usr.bin/ssh/clientloop.c, Revision 1.265
1.265 ! markus 1: /* $OpenBSD: clientloop.c,v 1.264 2015/01/19 20:07:45 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.265 ! markus 1404: dispatch_run(DISPATCH_NONBLOCK, &quit_pending, active_state);
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.265 ! markus 1458: int r, 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;
1.265 ! markus 1588: if ((r = kex_send_kexinit(active_state)) != 0)
! 1589: fatal("%s: kex_send_kexinit: %s",
! 1590: __func__, ssh_err(r));
1.56 markus 1591: need_rekeying = 0;
1592: }
1593: }
1.11 markus 1594:
1.17 markus 1595: /* Buffer input from the connection. */
1.46 markus 1596: client_process_net_input(readset);
1.17 markus 1597:
1598: if (quit_pending)
1599: break;
1.11 markus 1600:
1.17 markus 1601: if (!compat20) {
1602: /* Buffer data from stdin */
1.46 markus 1603: client_process_input(readset);
1.17 markus 1604: /*
1605: * Process output to stdout and stderr. Output to
1606: * the connection is processed elsewhere (above).
1607: */
1.46 markus 1608: client_process_output(writeset);
1.214 andreas 1609: }
1610:
1611: if (session_resumed) {
1612: connection_in = packet_get_connection_in();
1613: connection_out = packet_get_connection_out();
1614: max_fd = MAX(max_fd, connection_out);
1615: max_fd = MAX(max_fd, connection_in);
1616: session_resumed = 0;
1.17 markus 1617: }
1.11 markus 1618:
1.197 djm 1619: /*
1620: * Send as much buffered packet data as possible to the
1621: * sender.
1622: */
1.46 markus 1623: if (FD_ISSET(connection_out, writeset))
1.11 markus 1624: packet_write_poll();
1.222 djm 1625:
1626: /*
1627: * If we are a backgrounded control master, and the
1628: * timeout has expired without any active client
1629: * connections, then quit.
1630: */
1631: if (control_persist_exit_time > 0) {
1.251 dtucker 1632: if (monotime() >= control_persist_exit_time) {
1.222 djm 1633: debug("ControlPersist timeout expired");
1634: break;
1635: }
1636: }
1.11 markus 1637: }
1.250 djm 1638: free(readset);
1639: free(writeset);
1.11 markus 1640:
1641: /* Terminate the session. */
1642:
1643: /* Stop watching for window change. */
1.132 djm 1644: signal(SIGWINCH, SIG_DFL);
1.211 andreas 1645:
1.213 stevesk 1646: if (compat20) {
1647: packet_start(SSH2_MSG_DISCONNECT);
1648: packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1649: packet_put_cstring("disconnected by user");
1.219 djm 1650: packet_put_cstring(""); /* language tag */
1.213 stevesk 1651: packet_send();
1652: packet_write_wait();
1653: }
1.11 markus 1654:
1.76 markus 1655: channel_free_all();
1.11 markus 1656:
1.75 markus 1657: if (have_pty)
1.233 djm 1658: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.75 markus 1659:
1660: /* restore blocking io */
1661: if (!isatty(fileno(stdin)))
1662: unset_nonblock(fileno(stdin));
1663: if (!isatty(fileno(stdout)))
1664: unset_nonblock(fileno(stdout));
1665: if (!isatty(fileno(stderr)))
1666: unset_nonblock(fileno(stderr));
1.116 dtucker 1667:
1668: /*
1669: * If there was no shell or command requested, there will be no remote
1670: * exit status to be returned. In that case, clear error code if the
1671: * connection was deliberately terminated at this end.
1672: */
1673: if (no_shell_flag && received_signal == SIGTERM) {
1674: received_signal = 0;
1675: exit_status = 0;
1676: }
1.75 markus 1677:
1.113 markus 1678: if (received_signal)
1.89 itojun 1679: fatal("Killed by signal %d.", (int) received_signal);
1.75 markus 1680:
1.13 markus 1681: /*
1682: * In interactive mode (with pseudo tty) display a message indicating
1683: * that the connection has been closed.
1684: */
1.11 markus 1685: if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1.197 djm 1686: snprintf(buf, sizeof buf,
1687: "Connection to %.64s closed.\r\n", host);
1.11 markus 1688: buffer_append(&stderr_buffer, buf, strlen(buf));
1689: }
1.70 markus 1690:
1.11 markus 1691: /* Output any buffered data for stdout. */
1.231 djm 1692: if (buffer_len(&stdout_buffer) > 0) {
1.230 djm 1693: len = atomicio(vwrite, fileno(stdout),
1694: buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1.231 djm 1695: if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1.11 markus 1696: error("Write failed flushing stdout buffer.");
1.231 djm 1697: else
1698: buffer_consume(&stdout_buffer, len);
1.11 markus 1699: }
1700:
1701: /* Output any buffered data for stderr. */
1.231 djm 1702: if (buffer_len(&stderr_buffer) > 0) {
1.230 djm 1703: len = atomicio(vwrite, fileno(stderr),
1704: buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1.231 djm 1705: if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1.11 markus 1706: error("Write failed flushing stderr buffer.");
1.231 djm 1707: else
1708: buffer_consume(&stderr_buffer, len);
1.11 markus 1709: }
1710:
1711: /* Clear and free any buffers. */
1712: memset(buf, 0, sizeof(buf));
1713: buffer_free(&stdin_buffer);
1714: buffer_free(&stdout_buffer);
1715: buffer_free(&stderr_buffer);
1716:
1717: /* Report bytes transferred, and transfer rates. */
1718: total_time = get_current_time() - start_time;
1.263 markus 1719: packet_get_bytes(&ibytes, &obytes);
1.200 markus 1720: verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1.229 djm 1721: (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1.11 markus 1722: if (total_time > 0)
1.200 markus 1723: verbose("Bytes per second: sent %.1f, received %.1f",
1724: obytes / total_time, ibytes / total_time);
1.11 markus 1725: /* Return the exit status of the program. */
1726: debug("Exit status %d", exit_status);
1727: return exit_status;
1.15 markus 1728: }
1729:
1730: /*********/
1731:
1.264 markus 1732: static int
1.94 markus 1733: client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1.15 markus 1734: {
1.42 markus 1735: u_int data_len;
1.15 markus 1736: char *data = packet_get_string(&data_len);
1.93 markus 1737: packet_check_eom();
1.15 markus 1738: buffer_append(&stdout_buffer, data, data_len);
1.258 djm 1739: explicit_bzero(data, data_len);
1.250 djm 1740: free(data);
1.264 markus 1741: return 0;
1.15 markus 1742: }
1.264 markus 1743: static int
1.94 markus 1744: client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1.15 markus 1745: {
1.42 markus 1746: u_int data_len;
1.15 markus 1747: char *data = packet_get_string(&data_len);
1.93 markus 1748: packet_check_eom();
1.15 markus 1749: buffer_append(&stderr_buffer, data, data_len);
1.258 djm 1750: explicit_bzero(data, data_len);
1.250 djm 1751: free(data);
1.264 markus 1752: return 0;
1.15 markus 1753: }
1.264 markus 1754: static int
1.94 markus 1755: client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1.15 markus 1756: {
1757: exit_status = packet_get_int();
1.93 markus 1758: packet_check_eom();
1.15 markus 1759: /* Acknowledge the exit. */
1760: packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1761: packet_send();
1762: /*
1763: * Must wait for packet to be sent since we are
1764: * exiting the loop.
1765: */
1766: packet_write_wait();
1767: /* Flag that we want to exit. */
1768: quit_pending = 1;
1.264 markus 1769: return 0;
1.15 markus 1770: }
1.264 markus 1771: static int
1.115 markus 1772: client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1773: {
1774: Channel *c = NULL;
1.262 djm 1775: int r, remote_id, sock;
1.115 markus 1776:
1777: /* Read the remote channel number from the message. */
1778: remote_id = packet_get_int();
1779: packet_check_eom();
1780:
1781: /*
1782: * Get a connection to the local authentication agent (this may again
1783: * get forwarded).
1784: */
1.262 djm 1785: if ((r = ssh_get_authentication_socket(&sock)) != 0 &&
1786: r != SSH_ERR_AGENT_NOT_PRESENT)
1787: debug("%s: ssh_get_authentication_socket: %s",
1788: __func__, ssh_err(r));
1789:
1.115 markus 1790:
1791: /*
1792: * If we could not connect the agent, send an error message back to
1793: * the server. This should never happen unless the agent dies,
1794: * because authentication forwarding is only enabled if we have an
1795: * agent.
1796: */
1797: if (sock >= 0) {
1798: c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1799: -1, 0, 0, 0, "authentication agent connection", 1);
1800: c->remote_id = remote_id;
1801: c->force_drain = 1;
1802: }
1803: if (c == NULL) {
1804: packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1805: packet_put_int(remote_id);
1806: } else {
1807: /* Send a confirmation to the remote host. */
1808: debug("Forwarding authentication connection.");
1809: packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1810: packet_put_int(remote_id);
1811: packet_put_int(c->self);
1812: }
1813: packet_send();
1.264 markus 1814: return 0;
1.115 markus 1815: }
1.15 markus 1816:
1.77 itojun 1817: static Channel *
1.40 markus 1818: client_request_forwarded_tcpip(const char *request_type, int rchan)
1819: {
1.103 deraadt 1820: Channel *c = NULL;
1.40 markus 1821: char *listen_address, *originator_address;
1.208 djm 1822: u_short listen_port, originator_port;
1.40 markus 1823:
1824: /* Get rest of the packet */
1825: listen_address = packet_get_string(NULL);
1826: listen_port = packet_get_int();
1827: originator_address = packet_get_string(NULL);
1828: originator_port = packet_get_int();
1.93 markus 1829: packet_check_eom();
1.40 markus 1830:
1.261 millert 1831: debug("%s: listen %s port %d, originator %s port %d", __func__,
1832: listen_address, listen_port, originator_address, originator_port);
1.191 djm 1833:
1.260 markus 1834: c = channel_connect_by_listen_address(listen_address, listen_port,
1.191 djm 1835: "forwarded-tcpip", originator_address);
1.40 markus 1836:
1.250 djm 1837: free(originator_address);
1838: free(listen_address);
1.40 markus 1839: return c;
1840: }
1841:
1.103 deraadt 1842: static Channel *
1.261 millert 1843: client_request_forwarded_streamlocal(const char *request_type, int rchan)
1844: {
1845: Channel *c = NULL;
1846: char *listen_path;
1847:
1848: /* Get the remote path. */
1849: listen_path = packet_get_string(NULL);
1850: /* XXX: Skip reserved field for now. */
1851: if (packet_get_string_ptr(NULL) == NULL)
1852: fatal("%s: packet_get_string_ptr failed", __func__);
1853: packet_check_eom();
1854:
1855: debug("%s: %s", __func__, listen_path);
1856:
1857: c = channel_connect_by_listen_path(listen_path,
1858: "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1859: free(listen_path);
1860: return c;
1861: }
1862:
1863: static Channel *
1.40 markus 1864: client_request_x11(const char *request_type, int rchan)
1865: {
1866: Channel *c = NULL;
1867: char *originator;
1.208 djm 1868: u_short originator_port;
1.67 markus 1869: int sock;
1.40 markus 1870:
1871: if (!options.forward_x11) {
1872: error("Warning: ssh server tried X11 forwarding.");
1.197 djm 1873: error("Warning: this is probably a break-in attempt by a "
1874: "malicious server.");
1.221 djm 1875: return NULL;
1876: }
1.251 dtucker 1877: if (x11_refuse_time != 0 && monotime() >= x11_refuse_time) {
1.221 djm 1878: verbose("Rejected X11 connection after ForwardX11Timeout "
1879: "expired");
1.40 markus 1880: return NULL;
1881: }
1882: originator = packet_get_string(NULL);
1883: if (datafellows & SSH_BUG_X11FWD) {
1884: debug2("buggy server: x11 request w/o originator_port");
1885: originator_port = 0;
1886: } else {
1887: originator_port = packet_get_int();
1888: }
1.93 markus 1889: packet_check_eom();
1.40 markus 1890: /* XXX check permission */
1.47 markus 1891: debug("client_request_x11: request from %s %d", originator,
1892: originator_port);
1.250 djm 1893: free(originator);
1.40 markus 1894: sock = x11_connect_display();
1.67 markus 1895: if (sock < 0)
1896: return NULL;
1897: c = channel_new("x11",
1898: SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1.110 markus 1899: CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1.82 markus 1900: c->force_drain = 1;
1.40 markus 1901: return c;
1902: }
1903:
1.103 deraadt 1904: static Channel *
1.40 markus 1905: client_request_agent(const char *request_type, int rchan)
1906: {
1907: Channel *c = NULL;
1.262 djm 1908: int r, sock;
1.40 markus 1909:
1910: if (!options.forward_agent) {
1911: error("Warning: ssh server tried agent forwarding.");
1.197 djm 1912: error("Warning: this is probably a break-in attempt by a "
1913: "malicious server.");
1.40 markus 1914: return NULL;
1915: }
1.262 djm 1916: if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1917: if (r != SSH_ERR_AGENT_NOT_PRESENT)
1918: debug("%s: ssh_get_authentication_socket: %s",
1919: __func__, ssh_err(r));
1.67 markus 1920: return NULL;
1.262 djm 1921: }
1.67 markus 1922: c = channel_new("authentication agent connection",
1923: SSH_CHANNEL_OPEN, sock, sock, -1,
1.185 dtucker 1924: CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1.110 markus 1925: "authentication agent connection", 1);
1.82 markus 1926: c->force_drain = 1;
1.40 markus 1927: return c;
1.180 djm 1928: }
1929:
1930: int
1931: client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1932: {
1933: Channel *c;
1934: int fd;
1935:
1936: if (tun_mode == SSH_TUNMODE_NO)
1937: return 0;
1938:
1939: if (!compat20) {
1.207 stevesk 1940: error("Tunnel forwarding is not supported for protocol 1");
1.180 djm 1941: return -1;
1942: }
1943:
1944: debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1945:
1946: /* Open local tunnel device */
1947: if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1948: error("Tunnel device open failed.");
1949: return -1;
1950: }
1951:
1952: c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1953: CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1954: c->datagram = 1;
1955:
1956: packet_start(SSH2_MSG_CHANNEL_OPEN);
1957: packet_put_cstring("tun@openssh.com");
1958: packet_put_int(c->self);
1959: packet_put_int(c->local_window_max);
1960: packet_put_int(c->local_maxpacket);
1961: packet_put_int(tun_mode);
1962: packet_put_int(remote_tun);
1963: packet_send();
1964:
1965: return 0;
1.40 markus 1966: }
1967:
1.22 markus 1968: /* XXXX move to generic input handler */
1.264 markus 1969: static int
1.94 markus 1970: client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1.22 markus 1971: {
1972: Channel *c = NULL;
1973: char *ctype;
1974: int rchan;
1.102 markus 1975: u_int rmaxpack, rwindow, len;
1.22 markus 1976:
1977: ctype = packet_get_string(&len);
1978: rchan = packet_get_int();
1979: rwindow = packet_get_int();
1980: rmaxpack = packet_get_int();
1981:
1.24 markus 1982: debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1.22 markus 1983: ctype, rchan, rwindow, rmaxpack);
1984:
1.40 markus 1985: if (strcmp(ctype, "forwarded-tcpip") == 0) {
1986: c = client_request_forwarded_tcpip(ctype, rchan);
1.261 millert 1987: } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1988: c = client_request_forwarded_streamlocal(ctype, rchan);
1.40 markus 1989: } else if (strcmp(ctype, "x11") == 0) {
1990: c = client_request_x11(ctype, rchan);
1991: } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1992: c = client_request_agent(ctype, rchan);
1.22 markus 1993: }
1994: /* XXX duplicate : */
1995: if (c != NULL) {
1996: debug("confirm %s", ctype);
1997: c->remote_id = rchan;
1998: c->remote_window = rwindow;
1999: c->remote_maxpacket = rmaxpack;
1.69 markus 2000: if (c->type != SSH_CHANNEL_CONNECTING) {
2001: packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
2002: packet_put_int(c->remote_id);
2003: packet_put_int(c->self);
2004: packet_put_int(c->local_window);
2005: packet_put_int(c->local_maxpacket);
2006: packet_send();
2007: }
1.22 markus 2008: } else {
2009: debug("failure %s", ctype);
2010: packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
2011: packet_put_int(rchan);
2012: packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1.66 markus 2013: if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.69 markus 2014: packet_put_cstring("open failed");
1.66 markus 2015: packet_put_cstring("");
2016: }
1.22 markus 2017: packet_send();
2018: }
1.250 djm 2019: free(ctype);
1.264 markus 2020: return 0;
1.22 markus 2021: }
1.264 markus 2022: static int
1.94 markus 2023: client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1.48 markus 2024: {
2025: Channel *c = NULL;
1.123 djm 2026: int exitval, id, reply, success = 0;
1.48 markus 2027: char *rtype;
2028:
2029: id = packet_get_int();
2030: rtype = packet_get_string(NULL);
2031: reply = packet_get_char();
2032:
2033: debug("client_input_channel_req: channel %d rtype %s reply %d",
2034: id, rtype, reply);
2035:
1.128 djm 2036: if (id == -1) {
2037: error("client_input_channel_req: request for channel -1");
2038: } else if ((c = channel_lookup(id)) == NULL) {
1.197 djm 2039: error("client_input_channel_req: channel %d: "
2040: "unknown channel", id);
1.193 markus 2041: } else if (strcmp(rtype, "eow@openssh.com") == 0) {
2042: packet_check_eom();
2043: chan_rcvd_eow(c);
1.48 markus 2044: } else if (strcmp(rtype, "exit-status") == 0) {
1.123 djm 2045: exitval = packet_get_int();
1.217 djm 2046: if (c->ctl_chan != -1) {
2047: mux_exit_message(c, exitval);
1.215 djm 2048: success = 1;
2049: } else if (id == session_ident) {
2050: /* Record exit value of local session */
1.123 djm 2051: success = 1;
2052: exit_status = exitval;
1.215 djm 2053: } else {
1.218 djm 2054: /* Probably for a mux channel that has already closed */
2055: debug("%s: no sink for exit-status on channel %d",
2056: __func__, id);
1.123 djm 2057: }
1.93 markus 2058: packet_check_eom();
1.48 markus 2059: }
1.259 djm 2060: if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1.48 markus 2061: packet_start(success ?
2062: SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1.205 markus 2063: packet_put_int(c->remote_id);
1.48 markus 2064: packet_send();
2065: }
1.250 djm 2066: free(rtype);
1.264 markus 2067: return 0;
1.48 markus 2068: }
1.264 markus 2069: static int
1.95 markus 2070: client_input_global_request(int type, u_int32_t seq, void *ctxt)
2071: {
2072: char *rtype;
2073: int want_reply;
2074: int success = 0;
2075:
2076: rtype = packet_get_string(NULL);
2077: want_reply = packet_get_char();
1.117 markus 2078: debug("client_input_global_request: rtype %s want_reply %d",
2079: rtype, want_reply);
1.95 markus 2080: if (want_reply) {
2081: packet_start(success ?
2082: SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2083: packet_send();
2084: packet_write_wait();
2085: }
1.250 djm 2086: free(rtype);
1.264 markus 2087: return 0;
1.95 markus 2088: }
1.22 markus 2089:
1.123 djm 2090: void
1.129 deraadt 2091: client_session2_setup(int id, int want_tty, int want_subsystem,
1.190 djm 2092: const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
1.123 djm 2093: {
2094: int len;
1.132 djm 2095: Channel *c = NULL;
1.123 djm 2096:
2097: debug2("%s: id %d", __func__, id);
2098:
1.132 djm 2099: if ((c = channel_lookup(id)) == NULL)
2100: fatal("client_session2_setup: channel %d: unknown channel", id);
1.224 djm 2101:
2102: packet_set_interactive(want_tty,
2103: options.ip_qos_interactive, options.ip_qos_bulk);
1.132 djm 2104:
1.123 djm 2105: if (want_tty) {
2106: struct winsize ws;
2107:
2108: /* Store window size in the packet. */
2109: if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2110: memset(&ws, 0, sizeof(ws));
2111:
1.190 djm 2112: channel_request_start(id, "pty-req", 1);
1.234 djm 2113: client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
1.123 djm 2114: packet_put_cstring(term != NULL ? term : "");
1.158 deraadt 2115: packet_put_int((u_int)ws.ws_col);
2116: packet_put_int((u_int)ws.ws_row);
2117: packet_put_int((u_int)ws.ws_xpixel);
2118: packet_put_int((u_int)ws.ws_ypixel);
1.194 djm 2119: if (tiop == NULL)
2120: tiop = get_saved_tio();
2121: tty_make_modes(-1, tiop);
1.123 djm 2122: packet_send();
2123: /* XXX wait for reply */
1.132 djm 2124: c->client_tty = 1;
1.123 djm 2125: }
2126:
2127: /* Transfer any environment variables from client to server */
1.126 djm 2128: if (options.num_send_env != 0 && env != NULL) {
1.123 djm 2129: int i, j, matched;
2130: char *name, *val;
2131:
2132: debug("Sending environment.");
1.126 djm 2133: for (i = 0; env[i] != NULL; i++) {
1.123 djm 2134: /* Split */
1.126 djm 2135: name = xstrdup(env[i]);
1.123 djm 2136: if ((val = strchr(name, '=')) == NULL) {
1.250 djm 2137: free(name);
1.123 djm 2138: continue;
2139: }
2140: *val++ = '\0';
2141:
2142: matched = 0;
2143: for (j = 0; j < options.num_send_env; j++) {
2144: if (match_pattern(name, options.send_env[j])) {
2145: matched = 1;
2146: break;
2147: }
2148: }
2149: if (!matched) {
2150: debug3("Ignored env %s", name);
1.250 djm 2151: free(name);
1.123 djm 2152: continue;
2153: }
2154:
2155: debug("Sending env %s = %s", name, val);
2156: channel_request_start(id, "env", 0);
2157: packet_put_cstring(name);
2158: packet_put_cstring(val);
2159: packet_send();
1.250 djm 2160: free(name);
1.123 djm 2161: }
2162: }
2163:
2164: len = buffer_len(cmd);
2165: if (len > 0) {
2166: if (len > 900)
2167: len = 900;
2168: if (want_subsystem) {
1.190 djm 2169: debug("Sending subsystem: %.*s",
2170: len, (u_char*)buffer_ptr(cmd));
2171: channel_request_start(id, "subsystem", 1);
1.234 djm 2172: client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
1.123 djm 2173: } else {
1.190 djm 2174: debug("Sending command: %.*s",
2175: len, (u_char*)buffer_ptr(cmd));
2176: channel_request_start(id, "exec", 1);
1.234 djm 2177: client_expect_confirm(id, "exec", CONFIRM_CLOSE);
1.123 djm 2178: }
2179: packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2180: packet_send();
2181: } else {
1.190 djm 2182: channel_request_start(id, "shell", 1);
1.234 djm 2183: client_expect_confirm(id, "shell", CONFIRM_CLOSE);
1.123 djm 2184: packet_send();
2185: }
2186: }
2187:
1.77 itojun 2188: static void
1.49 itojun 2189: client_init_dispatch_20(void)
1.16 markus 2190: {
1.55 markus 2191: dispatch_init(&dispatch_protocol_error);
1.100 markus 2192:
1.16 markus 2193: dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2194: dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2195: dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2196: dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1.22 markus 2197: dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1.16 markus 2198: dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2199: dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1.48 markus 2200: dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1.16 markus 2201: dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1.189 djm 2202: dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2203: dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
1.95 markus 2204: dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1.55 markus 2205:
2206: /* rekeying */
2207: dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.100 markus 2208:
2209: /* global request reply messages */
2210: dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2211: dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1.16 markus 2212: }
1.197 djm 2213:
1.77 itojun 2214: static void
1.49 itojun 2215: client_init_dispatch_13(void)
1.15 markus 2216: {
2217: dispatch_init(NULL);
2218: dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2219: dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2220: dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2221: dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2222: dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2223: dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2224: dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2225: dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2226: dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
1.39 markus 2227:
2228: dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
1.115 markus 2229: &client_input_agent_open : &deny_input_open);
1.39 markus 2230: dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2231: &x11_input_open : &deny_input_open);
1.15 markus 2232: }
1.197 djm 2233:
1.77 itojun 2234: static void
1.49 itojun 2235: client_init_dispatch_15(void)
1.15 markus 2236: {
2237: client_init_dispatch_13();
2238: dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2239: dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2240: }
1.197 djm 2241:
1.79 stevesk 2242: static void
1.49 itojun 2243: client_init_dispatch(void)
1.15 markus 2244: {
1.16 markus 2245: if (compat20)
2246: client_init_dispatch_20();
2247: else if (compat13)
1.15 markus 2248: client_init_dispatch_13();
2249: else
2250: client_init_dispatch_15();
1.232 djm 2251: }
2252:
2253: void
2254: client_stop_mux(void)
2255: {
2256: if (options.control_path != NULL && muxserver_sock != -1)
2257: unlink(options.control_path);
2258: /*
1.247 dtucker 2259: * If we are in persist mode, or don't have a shell, signal that we
2260: * should close when all active channels are closed.
1.232 djm 2261: */
1.247 dtucker 2262: if (options.control_persist || no_shell_flag) {
1.232 djm 2263: session_closed = 1;
1.235 djm 2264: setproctitle("[stopped mux]");
2265: }
1.113 markus 2266: }
2267:
2268: /* client specific fatal cleanup */
2269: void
1.114 markus 2270: cleanup_exit(int i)
1.113 markus 2271: {
1.233 djm 2272: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.113 markus 2273: leave_non_blocking();
1.192 djm 2274: if (options.control_path != NULL && muxserver_sock != -1)
1.123 djm 2275: unlink(options.control_path);
1.223 djm 2276: ssh_kill_proxy_command();
1.114 markus 2277: _exit(i);
1.1 deraadt 2278: }