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