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