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