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