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