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