Annotation of src/usr.bin/ssh/clientloop.c, Revision 1.401
1.401 ! djm 1: /* $OpenBSD: clientloop.c,v 1.400 2023/10/12 02:12:53 djm Exp $ */
1.1 deraadt 2: /*
1.12 deraadt 3: * Author: Tatu Ylonen <ylo@cs.hut.fi>
4: * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5: * All rights reserved
1.33 deraadt 6: * The main loop for the interactive session (client side).
1.20 markus 7: *
1.33 deraadt 8: * As far as I am concerned, the code I have written for this software
9: * can be used freely for any purpose. Any derived versions of this
10: * software must be clearly marked as such, and if the derived work is
11: * incompatible with the protocol description in the RFC file, it must be
12: * called by a name other than "ssh" or "Secure Shell".
13: *
14: *
15: * Copyright (c) 1999 Theo de Raadt. All rights reserved.
16: *
17: * Redistribution and use in source and binary forms, with or without
18: * modification, are permitted provided that the following conditions
19: * are met:
20: * 1. Redistributions of source code must retain the above copyright
21: * notice, this list of conditions and the following disclaimer.
22: * 2. Redistributions in binary form must reproduce the above copyright
23: * notice, this list of conditions and the following disclaimer in the
24: * documentation and/or other materials provided with the distribution.
25: *
26: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27: * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31: * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35: * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.20 markus 36: *
37: *
1.33 deraadt 38: * SSH2 support added by Markus Friedl.
1.78 markus 39: * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
1.20 markus 40: *
1.33 deraadt 41: * Redistribution and use in source and binary forms, with or without
42: * modification, are permitted provided that the following conditions
43: * are met:
44: * 1. Redistributions of source code must retain the above copyright
45: * notice, this list of conditions and the following disclaimer.
46: * 2. Redistributions in binary form must reproduce the above copyright
47: * notice, this list of conditions and the following disclaimer in the
48: * documentation and/or other materials provided with the distribution.
49: *
50: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
51: * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
52: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
53: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
54: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
55: * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
56: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
57: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
58: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
59: * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.12 deraadt 60: */
1.1 deraadt 61:
1.152 stevesk 62:
1.175 deraadt 63: #include <sys/types.h>
1.152 stevesk 64: #include <sys/ioctl.h>
1.154 stevesk 65: #include <sys/stat.h>
1.166 stevesk 66: #include <sys/socket.h>
1.171 stevesk 67: #include <sys/time.h>
1.189 djm 68: #include <sys/queue.h>
1.150 stevesk 69:
1.155 stevesk 70: #include <ctype.h>
1.168 stevesk 71: #include <errno.h>
1.151 stevesk 72: #include <paths.h>
1.374 djm 73: #include <poll.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.328 deraadt 78: #include <stdarg.h>
1.150 stevesk 79: #include <termios.h>
1.175 deraadt 80: #include <pwd.h>
1.169 stevesk 81: #include <unistd.h>
1.266 deraadt 82: #include <limits.h>
1.1 deraadt 83:
1.175 deraadt 84: #include "xmalloc.h"
1.45 markus 85: #include "ssh.h"
86: #include "ssh2.h"
1.1 deraadt 87: #include "packet.h"
1.315 markus 88: #include "sshbuf.h"
1.15 markus 89: #include "compat.h"
1.74 markus 90: #include "channels.h"
1.15 markus 91: #include "dispatch.h"
1.317 markus 92: #include "sshkey.h"
1.175 deraadt 93: #include "cipher.h"
1.54 markus 94: #include "kex.h"
1.275 markus 95: #include "myproposal.h"
1.45 markus 96: #include "log.h"
1.261 millert 97: #include "misc.h"
1.45 markus 98: #include "readconf.h"
99: #include "clientloop.h"
1.147 djm 100: #include "sshconnect.h"
1.40 markus 101: #include "authfd.h"
1.45 markus 102: #include "atomicio.h"
1.118 deraadt 103: #include "sshpty.h"
1.123 djm 104: #include "match.h"
105: #include "msg.h"
1.262 djm 106: #include "ssherr.h"
1.267 djm 107: #include "hostfile.h"
1.319 djm 108:
1.375 djm 109: /* Permitted RSA signature algorithms for UpdateHostkeys proofs */
110: #define HOSTKEY_PROOF_RSA_ALGS "rsa-sha2-512,rsa-sha2-256"
111:
1.397 djm 112: /* Uncertainty (in percent) of keystroke timing intervals */
113: #define SSH_KEYSTROKE_TIMING_FUZZ 10
114:
1.39 markus 115: /* import options */
116: extern Options options;
1.1 deraadt 117:
1.123 djm 118: /* Control socket */
1.217 djm 119: extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
1.123 djm 120:
1.13 markus 121: /*
122: * Name of the host we are connecting to. This is the name given on the
1.324 jmc 123: * command line, or the Hostname specified for the user-supplied name in a
1.13 markus 124: * configuration file.
125: */
1.1 deraadt 126: extern char *host;
127:
1.13 markus 128: /*
1.330 djm 129: * If this field is not NULL, the ForwardAgent socket is this path and different
130: * instead of SSH_AUTH_SOCK.
131: */
132: extern char *forward_agent_sock_path;
133:
134: /*
1.13 markus 135: * Flag to indicate that we have received a window change signal which has
136: * not yet been processed. This will cause a message indicating the new
137: * window size to be sent to the server a little later. This is volatile
138: * because this is updated in a signal handler.
139: */
1.88 markus 140: static volatile sig_atomic_t received_window_change_signal = 0;
141: static volatile sig_atomic_t received_signal = 0;
1.1 deraadt 142:
1.222 djm 143: /* Time when backgrounded control master using ControlPersist should exit */
144: static time_t control_persist_exit_time = 0;
145:
1.1 deraadt 146: /* Common data for the client loop code. */
1.217 djm 147: volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
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. */
1.315 markus 150: static struct sshbuf *stderr_buffer; /* Used for final exit message. */
1.11 markus 151: static int connection_in; /* Connection to server (input). */
152: static int connection_out; /* Connection to server (output). */
1.56 markus 153: static int need_rekeying; /* Set to non-zero if rekeying is requested. */
1.221 djm 154: static int session_closed; /* In SSH2: login session closed. */
1.388 dtucker 155: static time_t x11_refuse_time; /* If >0, refuse x11 opens after this time. */
1.345 dtucker 156: static time_t server_alive_time; /* Time to do server_alive_check */
1.384 djm 157: static int hostkeys_update_complete;
158: static int session_setup_complete;
1.1 deraadt 159:
1.321 djm 160: static void client_init_dispatch(struct ssh *ssh);
1.16 markus 161: int session_ident = -1;
162:
1.195 djm 163: /* Track escape per proto2 channel */
164: struct escape_filter_ctx {
165: int escape_pending;
166: int escape_char;
167: };
168:
169: /* Context for channel confirmation replies */
1.190 djm 170: struct channel_reply_ctx {
171: const char *request_type;
1.234 djm 172: int id;
173: enum confirm_action action;
1.190 djm 174: };
175:
1.196 djm 176: /* Global request success/failure callbacks */
1.303 djm 177: /* XXX move to struct ssh? */
1.196 djm 178: struct global_confirm {
179: TAILQ_ENTRY(global_confirm) entry;
180: global_confirm_cb *cb;
181: void *ctx;
182: int ref_count;
183: };
184: TAILQ_HEAD(global_confirms, global_confirm);
185: static struct global_confirms global_confirms =
186: TAILQ_HEAD_INITIALIZER(global_confirms);
187:
1.315 markus 188: void ssh_process_session2_setup(int, int, int, struct sshbuf *);
1.377 djm 189: static void quit_message(const char *fmt, ...)
190: __attribute__((__format__ (printf, 1, 2)));
191:
192: static void
193: quit_message(const char *fmt, ...)
194: {
195: char *msg;
196: va_list args;
197: int r;
198:
199: va_start(args, fmt);
200: xvasprintf(&msg, fmt, args);
201: va_end(args);
202:
203: if ((r = sshbuf_putf(stderr_buffer, "%s\r\n", msg)) != 0)
204: fatal_fr(r, "sshbuf_putf");
205: quit_pending = 1;
206: }
1.123 djm 207:
1.13 markus 208: /*
209: * Signal handler for the window change signal (SIGWINCH). This just sets a
210: * flag indicating that the window has changed.
211: */
1.77 itojun 212: static void
1.11 markus 213: window_change_handler(int sig)
1.1 deraadt 214: {
1.11 markus 215: received_window_change_signal = 1;
1.1 deraadt 216: }
217:
1.13 markus 218: /*
219: * Signal handler for signals that cause the program to terminate. These
220: * signals must be trapped to restore terminal modes.
221: */
1.77 itojun 222: static void
1.11 markus 223: signal_handler(int sig)
1.1 deraadt 224: {
1.75 markus 225: received_signal = sig;
226: quit_pending = 1;
1.1 deraadt 227: }
228:
1.13 markus 229: /*
1.222 djm 230: * Sets control_persist_exit_time to the absolute time when the
231: * backgrounded control master should exit due to expiry of the
232: * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
233: * control master process, or if there is no ControlPersist timeout.
234: */
235: static void
1.303 djm 236: set_control_persist_exit_time(struct ssh *ssh)
1.222 djm 237: {
238: if (muxserver_sock == -1 || !options.control_persist
1.232 djm 239: || options.control_persist_timeout == 0) {
1.222 djm 240: /* not using a ControlPersist timeout */
241: control_persist_exit_time = 0;
1.303 djm 242: } else if (channel_still_open(ssh)) {
1.222 djm 243: /* some client connections are still open */
244: if (control_persist_exit_time > 0)
1.354 djm 245: debug2_f("cancel scheduled exit");
1.222 djm 246: control_persist_exit_time = 0;
247: } else if (control_persist_exit_time <= 0) {
248: /* a client connection has recently closed */
1.251 dtucker 249: control_persist_exit_time = monotime() +
1.222 djm 250: (time_t)options.control_persist_timeout;
1.354 djm 251: debug2_f("schedule exit in %d seconds",
1.222 djm 252: options.control_persist_timeout);
253: }
254: /* else we are already counting down to the timeout */
255: }
256:
1.238 dtucker 257: #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
258: static int
259: client_x11_display_valid(const char *display)
260: {
261: size_t i, dlen;
262:
1.279 djm 263: if (display == NULL)
264: return 0;
265:
1.238 dtucker 266: dlen = strlen(display);
267: for (i = 0; i < dlen; i++) {
1.256 deraadt 268: if (!isalnum((u_char)display[i]) &&
1.238 dtucker 269: strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
270: debug("Invalid character '%c' in DISPLAY", display[i]);
271: return 0;
272: }
273: }
274: return 1;
275: }
276:
1.274 djm 277: #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
278: #define X11_TIMEOUT_SLACK 60
1.279 djm 279: int
1.303 djm 280: client_x11_get_proto(struct ssh *ssh, const char *display,
281: const char *xauth_path, u_int trusted, u_int timeout,
282: char **_proto, char **_data)
1.138 djm 283: {
1.318 djm 284: char *cmd, line[512], xdisplay[512];
1.279 djm 285: char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
1.138 djm 286: static char proto[512], data[512];
287: FILE *f;
1.288 tedu 288: int got_data = 0, generated = 0, do_unlink = 0, r;
1.138 djm 289: struct stat st;
1.274 djm 290: u_int now, x11_timeout_real;
1.138 djm 291:
292: *_proto = proto;
293: *_data = data;
1.279 djm 294: proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
1.138 djm 295:
1.279 djm 296: if (!client_x11_display_valid(display)) {
1.283 millert 297: if (display != NULL)
298: logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
299: display);
1.279 djm 300: return -1;
301: }
302: if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
1.138 djm 303: debug("No xauth program.");
1.279 djm 304: xauth_path = NULL;
305: }
306:
307: if (xauth_path != NULL) {
1.138 djm 308: /*
309: * Handle FamilyLocal case where $DISPLAY does
310: * not match an authorization entry. For this we
311: * just try "xauth list unix:displaynum.screennum".
312: * XXX: "localhost" match to determine FamilyLocal
313: * is not perfect.
314: */
315: if (strncmp(display, "localhost:", 10) == 0) {
1.279 djm 316: if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
317: display + 10)) < 0 ||
318: (size_t)r >= sizeof(xdisplay)) {
1.354 djm 319: error_f("display name too long");
1.279 djm 320: return -1;
321: }
1.138 djm 322: display = xdisplay;
323: }
324: if (trusted == 0) {
1.274 djm 325: /*
1.279 djm 326: * Generate an untrusted X11 auth cookie.
327: *
1.274 djm 328: * The authentication cookie should briefly outlive
329: * ssh's willingness to forward X11 connections to
330: * avoid nasty fail-open behaviour in the X server.
331: */
1.279 djm 332: mktemp_proto(xauthdir, sizeof(xauthdir));
333: if (mkdtemp(xauthdir) == NULL) {
1.354 djm 334: error_f("mkdtemp: %s", strerror(errno));
1.279 djm 335: return -1;
336: }
337: do_unlink = 1;
338: if ((r = snprintf(xauthfile, sizeof(xauthfile),
339: "%s/xauthfile", xauthdir)) < 0 ||
340: (size_t)r >= sizeof(xauthfile)) {
1.354 djm 341: error_f("xauthfile path too long");
1.279 djm 342: rmdir(xauthdir);
343: return -1;
344: }
345:
1.318 djm 346: if (timeout == 0) {
347: /* auth doesn't time out */
348: xasprintf(&cmd, "%s -f %s generate %s %s "
349: "untrusted 2>%s",
350: xauth_path, xauthfile, display,
351: SSH_X11_PROTO, _PATH_DEVNULL);
352: } else {
353: /* Add some slack to requested expiry */
354: if (timeout < UINT_MAX - X11_TIMEOUT_SLACK)
355: x11_timeout_real = timeout +
356: X11_TIMEOUT_SLACK;
357: else {
358: /* Don't overflow on long timeouts */
359: x11_timeout_real = UINT_MAX;
360: }
361: xasprintf(&cmd, "%s -f %s generate %s %s "
362: "untrusted timeout %u 2>%s",
363: xauth_path, xauthfile, display,
364: SSH_X11_PROTO, x11_timeout_real,
365: _PATH_DEVNULL);
366: }
1.354 djm 367: debug2_f("xauth command: %s", cmd);
1.318 djm 368:
369: if (timeout != 0 && x11_refuse_time == 0) {
1.279 djm 370: now = monotime() + 1;
1.388 dtucker 371: if (SSH_TIME_T_MAX - timeout < now)
372: x11_refuse_time = SSH_TIME_T_MAX;
1.279 djm 373: else
374: x11_refuse_time = now + timeout;
1.303 djm 375: channel_set_x11_refuse_time(ssh,
376: x11_refuse_time);
1.138 djm 377: }
1.279 djm 378: if (system(cmd) == 0)
379: generated = 1;
1.318 djm 380: free(cmd);
1.138 djm 381: }
1.181 markus 382:
383: /*
384: * When in untrusted mode, we read the cookie only if it was
385: * successfully generated as an untrusted one in the step
386: * above.
387: */
388: if (trusted || generated) {
1.318 djm 389: xasprintf(&cmd,
1.181 markus 390: "%s %s%s list %s 2>" _PATH_DEVNULL,
391: xauth_path,
392: generated ? "-f " : "" ,
393: generated ? xauthfile : "",
394: display);
395: debug2("x11_get_proto: %s", cmd);
396: f = popen(cmd, "r");
397: if (f && fgets(line, sizeof(line), f) &&
398: sscanf(line, "%*s %511s %511s", proto, data) == 2)
399: got_data = 1;
400: if (f)
401: pclose(f);
1.318 djm 402: free(cmd);
1.279 djm 403: }
1.138 djm 404: }
405:
406: if (do_unlink) {
407: unlink(xauthfile);
408: rmdir(xauthdir);
409: }
410:
1.279 djm 411: /* Don't fall back to fake X11 data for untrusted forwarding */
412: if (!trusted && !got_data) {
413: error("Warning: untrusted X11 forwarding setup failed: "
414: "xauth key data not generated");
415: return -1;
416: }
417:
1.138 djm 418: /*
419: * If we didn't get authentication data, just make up some
420: * data. The forwarding code will check the validity of the
421: * response anyway, and substitute this data. The X11
422: * server, however, will ignore this fake data and use
423: * whatever authentication mechanisms it was using otherwise
424: * for the local connection.
425: */
426: if (!got_data) {
1.288 tedu 427: u_int8_t rnd[16];
428: u_int i;
1.138 djm 429:
430: logit("Warning: No xauth data; "
431: "using fake authentication data for X11 forwarding.");
432: strlcpy(proto, SSH_X11_PROTO, sizeof proto);
1.288 tedu 433: arc4random_buf(rnd, sizeof(rnd));
434: for (i = 0; i < sizeof(rnd); i++) {
1.138 djm 435: snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
1.288 tedu 436: rnd[i]);
1.138 djm 437: }
438: }
1.279 djm 439:
440: return 0;
1.1 deraadt 441: }
442:
1.13 markus 443: /*
444: * Checks if the client window has changed, and sends a packet about it to
445: * the server if so. The actual change is detected elsewhere (by a software
446: * interrupt on Unix); this just checks the flag and sends a message if
447: * appropriate.
448: */
1.1 deraadt 449:
1.77 itojun 450: static void
1.303 djm 451: client_check_window_change(struct ssh *ssh)
1.1 deraadt 452: {
1.292 djm 453: if (!received_window_change_signal)
1.16 markus 454: return;
455: received_window_change_signal = 0;
1.354 djm 456: debug2_f("changed");
1.303 djm 457: channel_send_window_changes(ssh);
1.1 deraadt 458: }
459:
1.264 markus 460: static int
1.297 markus 461: client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
1.117 markus 462: {
1.196 djm 463: struct global_confirm *gc;
464:
465: if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
1.264 markus 466: return 0;
1.196 djm 467: if (gc->cb != NULL)
1.303 djm 468: gc->cb(ssh, type, seq, gc->ctx);
1.196 djm 469: if (--gc->ref_count <= 0) {
470: TAILQ_REMOVE(&global_confirms, gc, entry);
1.342 jsg 471: freezero(gc, sizeof(*gc));
1.196 djm 472: }
473:
1.320 djm 474: ssh_packet_set_alive_timeouts(ssh, 0);
1.264 markus 475: return 0;
1.117 markus 476: }
477:
478: static void
1.345 dtucker 479: schedule_server_alive_check(void)
480: {
481: if (options.server_alive_interval > 0)
482: server_alive_time = monotime() + options.server_alive_interval;
483: }
484:
485: static void
1.320 djm 486: server_alive_check(struct ssh *ssh)
1.117 markus 487: {
1.320 djm 488: int r;
489:
490: if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) {
1.228 djm 491: logit("Timeout, server %s not responding.", host);
1.176 markus 492: cleanup_exit(255);
493: }
1.320 djm 494: if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
495: (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 ||
496: (r = sshpkt_put_u8(ssh, 1)) != 0 || /* boolean: want reply */
497: (r = sshpkt_send(ssh)) != 0)
1.354 djm 498: fatal_fr(r, "send packet");
1.196 djm 499: /* Insert an empty placeholder to maintain ordering */
500: client_register_global_confirm(NULL, NULL);
1.345 dtucker 501: schedule_server_alive_check();
1.117 markus 502: }
503:
1.393 djm 504: /* Try to send a dummy keystroke */
505: static int
506: send_chaff(struct ssh *ssh)
507: {
508: int r;
509:
510: if ((ssh->kex->flags & KEX_HAS_PING) == 0)
511: return 0;
512: /* XXX probabilistically send chaff? */
513: /*
514: * a SSH2_MSG_CHANNEL_DATA payload is 9 bytes:
515: * 4 bytes channel ID + 4 bytes string length + 1 byte string data
516: * simulate that here.
517: */
518: if ((r = sshpkt_start(ssh, SSH2_MSG_PING)) != 0 ||
519: (r = sshpkt_put_cstring(ssh, "PING!")) != 0 ||
520: (r = sshpkt_send(ssh)) != 0)
521: fatal_fr(r, "send packet");
522: return 1;
523: }
524:
1.397 djm 525: /* Sets the next interval to send a keystroke or chaff packet */
526: static void
527: set_next_interval(const struct timespec *now, struct timespec *next_interval,
528: u_int interval_ms, int starting)
529: {
530: struct timespec tmp;
531: long long interval_ns, fuzz_ns;
532: static long long rate_fuzz;
533:
534: interval_ns = interval_ms * (1000LL * 1000);
535: fuzz_ns = (interval_ns * SSH_KEYSTROKE_TIMING_FUZZ) / 100;
536: /* Center fuzz around requested interval */
537: if (fuzz_ns > INT_MAX)
538: fuzz_ns = INT_MAX;
539: if (fuzz_ns > interval_ns) {
540: /* Shouldn't happen */
541: fatal_f("internal error: fuzz %u%% %lldns > interval %lldns",
542: SSH_KEYSTROKE_TIMING_FUZZ, fuzz_ns, interval_ns);
543: }
544: /*
545: * Randomise the keystroke/chaff intervals in two ways:
546: * 1. Each interval has some random jitter applied to make the
547: * interval-to-interval time unpredictable.
548: * 2. The overall interval rate is also randomly perturbed for each
1.398 djm 549: * chaffing session to make the average rate unpredictable.
1.397 djm 550: */
551: if (starting)
552: rate_fuzz = arc4random_uniform(fuzz_ns);
553: interval_ns -= fuzz_ns;
554: interval_ns += arc4random_uniform(fuzz_ns) + rate_fuzz;
555:
556: tmp.tv_sec = interval_ns / (1000 * 1000 * 1000);
557: tmp.tv_nsec = interval_ns % (1000 * 1000 * 1000);
558:
559: timespecadd(now, &tmp, next_interval);
560: }
561:
1.393 djm 562: /*
563: * Performs keystroke timing obfuscation. Returns non-zero if the
564: * output fd should be polled.
565: */
566: static int
1.396 djm 567: obfuscate_keystroke_timing(struct ssh *ssh, struct timespec *timeout,
568: int channel_did_enqueue)
1.393 djm 569: {
570: static int active;
571: static struct timespec next_interval, chaff_until;
572: struct timespec now, tmp;
573: int just_started = 0, had_keystroke = 0;
574: static unsigned long long nchaff;
575: char *stop_reason = NULL;
576: long long n;
577:
578: monotime_ts(&now);
579:
580: if (options.obscure_keystroke_timing_interval <= 0)
581: return 1; /* disabled in config */
582:
1.401 ! djm 583: if (!channel_tty_open(ssh) || quit_pending) {
1.393 djm 584: /* Stop if no channels left of we're waiting for one to close */
585: stop_reason = "no active channels";
586: } else if (ssh_packet_is_rekeying(ssh)) {
587: /* Stop if we're rekeying */
588: stop_reason = "rekeying started";
589: } else if (!ssh_packet_interactive_data_to_write(ssh) &&
590: ssh_packet_have_data_to_write(ssh)) {
591: /* Stop if the output buffer has more than a few keystrokes */
592: stop_reason = "output buffer filling";
1.396 djm 593: } else if (active && channel_did_enqueue &&
594: ssh_packet_have_data_to_write(ssh)) {
1.393 djm 595: /* Still in active mode and have a keystroke queued. */
596: had_keystroke = 1;
597: } else if (active) {
598: if (timespeccmp(&now, &chaff_until, >=)) {
599: /* Stop if there have been no keystrokes for a while */
600: stop_reason = "chaff time expired";
601: } else if (timespeccmp(&now, &next_interval, >=)) {
602: /* Otherwise if we were due to send, then send chaff */
603: if (send_chaff(ssh))
604: nchaff++;
605: }
606: }
607:
608: if (stop_reason != NULL) {
1.395 djm 609: if (active) {
610: debug3_f("stopping: %s (%llu chaff packets sent)",
611: stop_reason, nchaff);
612: active = 0;
613: }
1.393 djm 614: return 1;
615: }
616:
617: /*
618: * If we're in interactive mode, and only have a small amount
619: * of outbound data, then we assume that the user is typing
620: * interactively. In this case, start quantising outbound packets to
621: * fixed time intervals to hide inter-keystroke timing.
622: */
1.396 djm 623: if (!active && ssh_packet_interactive_data_to_write(ssh) &&
624: channel_did_enqueue && ssh_packet_have_data_to_write(ssh)) {
1.397 djm 625: debug3_f("starting: interval ~%dms",
1.393 djm 626: options.obscure_keystroke_timing_interval);
627: just_started = had_keystroke = active = 1;
628: nchaff = 0;
1.397 djm 629: set_next_interval(&now, &next_interval,
630: options.obscure_keystroke_timing_interval, 1);
1.393 djm 631: }
632:
633: /* Don't hold off if obfuscation inactive */
634: if (!active)
635: return 1;
636:
637: if (had_keystroke) {
638: /*
639: * Arrange to send chaff packets for a random interval after
640: * the last keystroke was sent.
641: */
642: ms_to_timespec(&tmp, SSH_KEYSTROKE_CHAFF_MIN_MS +
643: arc4random_uniform(SSH_KEYSTROKE_CHAFF_RNG_MS));
644: timespecadd(&now, &tmp, &chaff_until);
645: }
646:
647: ptimeout_deadline_monotime_tsp(timeout, &next_interval);
648:
649: if (just_started)
650: return 1;
651:
652: /* Don't arm output fd for poll until the timing interval has elapsed */
653: if (timespeccmp(&now, &next_interval, <))
654: return 0;
655:
656: /* Calculate number of intervals missed since the last check */
1.394 djm 657: n = (now.tv_sec - next_interval.tv_sec) * 1000LL * 1000 * 1000;
1.393 djm 658: n += now.tv_nsec - next_interval.tv_nsec;
1.394 djm 659: n /= options.obscure_keystroke_timing_interval * 1000LL * 1000;
1.393 djm 660: n = (n < 0) ? 1 : n + 1;
661:
662: /* Advance to the next interval */
1.397 djm 663: set_next_interval(&now, &next_interval,
664: options.obscure_keystroke_timing_interval * n, 0);
1.393 djm 665: return 1;
666: }
667:
1.13 markus 668: /*
669: * Waits until the client can do something (some data becomes available on
670: * one of the file descriptors).
671: */
1.77 itojun 672: static void
1.374 djm 673: client_wait_until_can_do_something(struct ssh *ssh, struct pollfd **pfdp,
1.396 djm 674: u_int *npfd_allocp, u_int *npfd_activep, int channel_did_enqueue,
1.400 djm 675: sigset_t *sigsetp, int *conn_in_readyp, int *conn_out_readyp)
1.11 markus 676: {
1.386 djm 677: struct timespec timeout;
1.393 djm 678: int ret, oready;
1.374 djm 679: u_int p;
1.117 markus 680:
1.374 djm 681: *conn_in_readyp = *conn_out_readyp = 0;
1.11 markus 682:
1.374 djm 683: /* Prepare channel poll. First two pollfd entries are reserved */
1.386 djm 684: ptimeout_init(&timeout);
685: channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 2, &timeout);
1.374 djm 686: if (*npfd_activep < 2)
687: fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */
688:
689: /* channel_prepare_poll could have closed the last channel */
1.303 djm 690: if (session_closed && !channel_still_open(ssh) &&
1.320 djm 691: !ssh_packet_have_data_to_write(ssh)) {
1.374 djm 692: /* clear events since we did not call poll() */
693: for (p = 0; p < *npfd_activep; p++)
694: (*pfdp)[p].revents = 0;
1.292 djm 695: return;
1.16 markus 696: }
1.11 markus 697:
1.396 djm 698: oready = obfuscate_keystroke_timing(ssh, &timeout, channel_did_enqueue);
1.393 djm 699:
1.374 djm 700: /* Monitor server connection on reserved pollfd entries */
701: (*pfdp)[0].fd = connection_in;
702: (*pfdp)[0].events = POLLIN;
703: (*pfdp)[1].fd = connection_out;
1.393 djm 704: (*pfdp)[1].events = (oready && ssh_packet_have_data_to_write(ssh)) ?
705: POLLOUT : 0;
1.11 markus 706:
1.13 markus 707: /*
708: * Wait for something to happen. This will suspend the process until
1.374 djm 709: * some polled descriptor can be read, written, or has some other
1.222 djm 710: * event pending, or a timeout expires.
1.13 markus 711: */
1.386 djm 712: set_control_persist_exit_time(ssh);
713: if (control_persist_exit_time > 0)
714: ptimeout_deadline_monotime(&timeout, control_persist_exit_time);
1.345 dtucker 715: if (options.server_alive_interval > 0)
1.386 djm 716: ptimeout_deadline_monotime(&timeout, server_alive_time);
1.396 djm 717: if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) {
1.386 djm 718: ptimeout_deadline_sec(&timeout,
1.320 djm 719: ssh_packet_get_rekey_timeout(ssh));
1.386 djm 720: }
1.374 djm 721:
1.400 djm 722: ret = ppoll(*pfdp, *npfd_activep, ptimeout_get_tsp(&timeout), sigsetp);
1.222 djm 723:
1.326 deraadt 724: if (ret == -1) {
1.51 markus 725: /*
1.374 djm 726: * We have to clear the events because we return.
1.51 markus 727: * We have to return, because the mainloop checks for the flags
728: * set by the signal handlers.
729: */
1.374 djm 730: for (p = 0; p < *npfd_activep; p++)
731: (*pfdp)[p].revents = 0;
1.11 markus 732: if (errno == EINTR)
733: return;
734: /* Note: we might still have data in the buffers. */
1.377 djm 735: quit_message("poll: %s", strerror(errno));
1.374 djm 736: return;
737: }
738:
739: *conn_in_readyp = (*pfdp)[0].revents != 0;
740: *conn_out_readyp = (*pfdp)[1].revents != 0;
741:
742: if (options.server_alive_interval > 0 && !*conn_in_readyp &&
743: monotime() >= server_alive_time) {
1.249 dtucker 744: /*
1.374 djm 745: * ServerAlive check is needed. We can't rely on the poll
1.345 dtucker 746: * timing out since traffic on the client side such as port
747: * forwards can keep waking it up.
1.249 dtucker 748: */
1.345 dtucker 749: server_alive_check(ssh);
1.374 djm 750: }
1.11 markus 751: }
752:
1.77 itojun 753: static void
1.315 markus 754: client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
1.1 deraadt 755: {
1.11 markus 756: /* Flush stdout and stderr buffers. */
1.315 markus 757: if (sshbuf_len(bout) > 0)
758: atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
759: sshbuf_len(bout));
760: if (sshbuf_len(berr) > 0)
761: atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
762: sshbuf_len(berr));
1.11 markus 763:
1.233 djm 764: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11 markus 765:
1.305 djm 766: sshbuf_reset(bin);
767: sshbuf_reset(bout);
768: sshbuf_reset(berr);
1.11 markus 769:
770: /* Send the suspend signal to the program itself. */
771: kill(getpid(), SIGTSTP);
772:
1.132 djm 773: /* Reset window sizes in case they have changed */
774: received_window_change_signal = 1;
1.11 markus 775:
1.233 djm 776: enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11 markus 777: }
778:
1.77 itojun 779: static void
1.374 djm 780: client_process_net_input(struct ssh *ssh)
1.11 markus 781: {
1.378 djm 782: int r;
1.11 markus 783:
1.13 markus 784: /*
785: * Read input from the server, and add any such data to the buffer of
786: * the packet subsystem.
787: */
1.374 djm 788: schedule_server_alive_check();
1.378 djm 789: if ((r = ssh_packet_process_read(ssh, connection_in)) == 0)
790: return; /* success */
791: if (r == SSH_ERR_SYSTEM_ERROR) {
792: if (errno == EAGAIN || errno == EINTR)
793: return;
794: if (errno == EPIPE) {
795: quit_message("Connection to %s closed by remote host.",
796: host);
797: return;
798: }
1.11 markus 799: }
1.378 djm 800: quit_message("Read from remote host %s: %s", host, ssh_err(r));
1.17 markus 801: }
1.16 markus 802:
1.97 jakob 803: static void
1.303 djm 804: client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
1.123 djm 805: {
1.190 djm 806: struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
807: char errmsg[256];
1.315 markus 808: int r, tochan;
1.190 djm 809:
1.234 djm 810: /*
811: * If a TTY was explicitly requested, then a failure to allocate
812: * one is fatal.
813: */
814: if (cr->action == CONFIRM_TTY &&
815: (options.request_tty == REQUEST_TTY_FORCE ||
816: options.request_tty == REQUEST_TTY_YES))
817: cr->action = CONFIRM_CLOSE;
818:
1.312 djm 819: /* XXX suppress on mux _client_ quietmode */
1.190 djm 820: tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
1.217 djm 821: c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
1.190 djm 822:
823: if (type == SSH2_MSG_CHANNEL_SUCCESS) {
824: debug2("%s request accepted on channel %d",
825: cr->request_type, c->self);
826: } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
827: if (tochan) {
828: snprintf(errmsg, sizeof(errmsg),
829: "%s request failed\r\n", cr->request_type);
830: } else {
831: snprintf(errmsg, sizeof(errmsg),
832: "%s request failed on channel %d",
833: cr->request_type, c->self);
834: }
835: /* If error occurred on primary session channel, then exit */
1.234 djm 836: if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
1.190 djm 837: fatal("%s", errmsg);
1.234 djm 838: /*
839: * If error occurred on mux client, append to
840: * their stderr.
841: */
842: if (tochan) {
1.360 djm 843: debug3_f("channel %d: mux request: %s", c->self,
844: cr->request_type);
1.315 markus 845: if ((r = sshbuf_put(c->extended, errmsg,
846: strlen(errmsg))) != 0)
1.354 djm 847: fatal_fr(r, "sshbuf_put");
1.234 djm 848: } else
1.190 djm 849: error("%s", errmsg);
1.234 djm 850: if (cr->action == CONFIRM_TTY) {
851: /*
852: * If a TTY allocation error occurred, then arrange
853: * for the correct TTY to leave raw mode.
854: */
855: if (c->self == session_ident)
856: leave_raw_mode(0);
857: else
1.303 djm 858: mux_tty_alloc_failed(ssh, c);
1.234 djm 859: } else if (cr->action == CONFIRM_CLOSE) {
1.303 djm 860: chan_read_failed(ssh, c);
861: chan_write_failed(ssh, c);
1.190 djm 862: }
863: }
1.250 djm 864: free(cr);
1.190 djm 865: }
866:
867: static void
1.303 djm 868: client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
1.190 djm 869: {
1.250 djm 870: free(ctx);
1.190 djm 871: }
1.129 deraadt 872:
1.236 djm 873: void
1.303 djm 874: client_expect_confirm(struct ssh *ssh, int id, const char *request,
1.234 djm 875: enum confirm_action action)
1.190 djm 876: {
1.255 djm 877: struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
1.123 djm 878:
1.190 djm 879: cr->request_type = request;
1.234 djm 880: cr->action = action;
1.123 djm 881:
1.303 djm 882: channel_register_status_confirm(ssh, id, client_status_confirm,
1.190 djm 883: client_abandon_status_confirm, cr);
1.196 djm 884: }
885:
886: void
887: client_register_global_confirm(global_confirm_cb *cb, void *ctx)
888: {
1.201 djm 889: struct global_confirm *gc, *last_gc;
1.196 djm 890:
891: /* Coalesce identical callbacks */
1.201 djm 892: last_gc = TAILQ_LAST(&global_confirms, global_confirms);
893: if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
894: if (++last_gc->ref_count >= INT_MAX)
1.354 djm 895: fatal_f("last_gc->ref_count = %d",
896: last_gc->ref_count);
1.196 djm 897: return;
898: }
899:
1.255 djm 900: gc = xcalloc(1, sizeof(*gc));
1.196 djm 901: gc->cb = cb;
902: gc->ctx = ctx;
903: gc->ref_count = 1;
904: TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
1.123 djm 905: }
906:
1.384 djm 907: /*
908: * Returns non-zero if the client is able to handle a hostkeys-00@openssh.com
909: * hostkey update request.
910: */
911: static int
912: can_update_hostkeys(void)
913: {
914: if (hostkeys_update_complete)
915: return 0;
916: if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
917: options.batch_mode)
918: return 0; /* won't ask in batchmode, so don't even try */
919: if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
920: return 0;
921: return 1;
922: }
923:
1.385 dtucker 924: static void
925: client_repledge(void)
1.384 djm 926: {
927: debug3_f("enter");
928:
929: /* Might be able to tighten pledge now that session is established */
930: if (options.control_master || options.control_path != NULL ||
931: options.forward_x11 || options.fork_after_authentication ||
932: can_update_hostkeys() ||
933: (session_ident != -1 && !session_setup_complete)) {
934: /* Can't tighten */
935: return;
936: }
937: /*
938: * LocalCommand and UpdateHostkeys have finished, so can get rid of
939: * filesystem.
940: *
941: * XXX protocol allows a server can to change hostkeys during the
942: * connection at rekey time that could trigger a hostkeys update
943: * but AFAIK no implementations support this. Could improve by
944: * forcing known_hosts to be read-only or via unveil(2).
945: */
946: if (options.num_local_forwards != 0 ||
947: options.num_remote_forwards != 0 ||
948: options.num_permitted_remote_opens != 0 ||
949: options.enable_escape_commandline != 0) {
950: /* rfwd needs inet */
951: debug("pledge: network");
952: if (pledge("stdio unix inet dns proc tty", NULL) == -1)
953: fatal_f("pledge(): %s", strerror(errno));
954: } else if (options.forward_agent != 0) {
955: /* agent forwarding needs to open $SSH_AUTH_SOCK at will */
956: debug("pledge: agent");
957: if (pledge("stdio unix proc tty", NULL) == -1)
958: fatal_f("pledge(): %s", strerror(errno));
959: } else {
960: debug("pledge: fork");
961: if (pledge("stdio proc tty", NULL) == -1)
962: fatal_f("pledge(): %s", strerror(errno));
963: }
964: /* XXX further things to do:
965: *
966: * - might be able to get rid of proc if we kill ~^Z
967: * - ssh -N (no session)
968: * - stdio forwarding
969: * - sessions without tty
970: */
971: }
972:
1.123 djm 973: static void
1.303 djm 974: process_cmdline(struct ssh *ssh)
1.97 jakob 975: {
976: void (*handler)(int);
1.261 millert 977: char *s, *cmd;
978: int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
979: struct Forward fwd;
1.97 jakob 980:
1.257 tedu 981: memset(&fwd, 0, sizeof(fwd));
1.183 djm 982:
1.233 djm 983: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.332 dtucker 984: handler = ssh_signal(SIGINT, SIG_IGN);
1.99 markus 985: cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
1.97 jakob 986: if (s == NULL)
987: goto out;
1.256 deraadt 988: while (isspace((u_char)*s))
1.97 jakob 989: s++;
1.121 djm 990: if (*s == '-')
991: s++; /* Skip cmdline '-', if any */
1.120 dtucker 992: if (*s == '\0')
1.97 jakob 993: goto out;
1.121 djm 994:
1.122 djm 995: if (*s == 'h' || *s == 'H' || *s == '?') {
1.121 djm 996: logit("Commands:");
1.164 djm 997: logit(" -L[bind_address:]port:host:hostport "
998: "Request local forward");
999: logit(" -R[bind_address:]port:host:hostport "
1000: "Request remote forward");
1.204 stevesk 1001: logit(" -D[bind_address:]port "
1002: "Request dynamic forward");
1.237 markus 1003: logit(" -KL[bind_address:]port "
1004: "Cancel local forward");
1.165 stevesk 1005: logit(" -KR[bind_address:]port "
1.164 djm 1006: "Cancel remote forward");
1.237 markus 1007: logit(" -KD[bind_address:]port "
1008: "Cancel dynamic forward");
1.146 reyk 1009: if (!options.permit_local_command)
1010: goto out;
1.164 djm 1011: logit(" !args "
1012: "Execute local command");
1.146 reyk 1013: goto out;
1014: }
1015:
1016: if (*s == '!' && options.permit_local_command) {
1017: s++;
1018: ssh_local_cmd(s);
1.121 djm 1019: goto out;
1020: }
1021:
1022: if (*s == 'K') {
1023: delete = 1;
1024: s++;
1025: }
1.204 stevesk 1026: if (*s == 'L')
1027: local = 1;
1028: else if (*s == 'R')
1029: remote = 1;
1030: else if (*s == 'D')
1031: dynamic = 1;
1032: else {
1.109 itojun 1033: logit("Invalid command.");
1.97 jakob 1034: goto out;
1035: }
1.204 stevesk 1036:
1.256 deraadt 1037: while (isspace((u_char)*++s))
1.179 tedu 1038: ;
1.97 jakob 1039:
1.217 djm 1040: /* XXX update list of forwards in options */
1.121 djm 1041: if (delete) {
1.261 millert 1042: /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
1043: if (!parse_forward(&fwd, s, 1, 0)) {
1044: logit("Bad forwarding close specification.");
1.121 djm 1045: goto out;
1046: }
1.237 markus 1047: if (remote)
1.303 djm 1048: ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
1.237 markus 1049: else if (dynamic)
1.303 djm 1050: ok = channel_cancel_lport_listener(ssh, &fwd,
1.261 millert 1051: 0, &options.fwd_opts) > 0;
1.237 markus 1052: else
1.303 djm 1053: ok = channel_cancel_lport_listener(ssh, &fwd,
1.261 millert 1054: CHANNEL_CANCEL_PORT_STATIC,
1055: &options.fwd_opts) > 0;
1.237 markus 1056: if (!ok) {
1.290 dtucker 1057: logit("Unknown port forwarding.");
1.237 markus 1058: goto out;
1059: }
1060: logit("Canceled forwarding.");
1.121 djm 1061: } else {
1.382 dtucker 1062: /* -R specs can be both dynamic or not, so check both. */
1063: if (remote) {
1064: if (!parse_forward(&fwd, s, 0, remote) &&
1065: !parse_forward(&fwd, s, 1, remote)) {
1066: logit("Bad remote forwarding specification.");
1067: goto out;
1068: }
1069: } else if (!parse_forward(&fwd, s, dynamic, remote)) {
1070: logit("Bad local forwarding specification.");
1.121 djm 1071: goto out;
1072: }
1.204 stevesk 1073: if (local || dynamic) {
1.303 djm 1074: if (!channel_setup_local_fwd_listener(ssh, &fwd,
1.261 millert 1075: &options.fwd_opts)) {
1.121 djm 1076: logit("Port forwarding failed.");
1077: goto out;
1078: }
1.135 djm 1079: } else {
1.303 djm 1080: if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
1.167 markus 1081: logit("Port forwarding failed.");
1082: goto out;
1083: }
1.135 djm 1084: }
1.121 djm 1085: logit("Forwarding port.");
1086: }
1087:
1.97 jakob 1088: out:
1.332 dtucker 1089: ssh_signal(SIGINT, handler);
1.233 djm 1090: enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.250 djm 1091: free(cmd);
1092: free(fwd.listen_host);
1.261 millert 1093: free(fwd.listen_path);
1.250 djm 1094: free(fwd.connect_host);
1.261 millert 1095: free(fwd.connect_path);
1.97 jakob 1096: }
1097:
1.244 dtucker 1098: /* reasons to suppress output of an escape command in help output */
1099: #define SUPPRESS_NEVER 0 /* never suppress, always show */
1.292 djm 1100: #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */
1101: #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */
1102: #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */
1.383 djm 1103: #define SUPPRESS_NOCMDLINE 8 /* don't show when cmdline disabled*/
1.244 dtucker 1104: struct escape_help_text {
1105: const char *cmd;
1106: const char *text;
1107: unsigned int flags;
1108: };
1109: static struct escape_help_text esc_txt[] = {
1110: {".", "terminate session", SUPPRESS_MUXMASTER},
1111: {".", "terminate connection (and any multiplexed sessions)",
1112: SUPPRESS_MUXCLIENT},
1.292 djm 1113: {"B", "send a BREAK to the remote system", SUPPRESS_NEVER},
1.383 djm 1114: {"C", "open a command line", SUPPRESS_MUXCLIENT|SUPPRESS_NOCMDLINE},
1.292 djm 1115: {"R", "request rekey", SUPPRESS_NEVER},
1.246 dtucker 1116: {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1.244 dtucker 1117: {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
1118: {"#", "list forwarded connections", SUPPRESS_NEVER},
1119: {"&", "background ssh (when waiting for connections to terminate)",
1120: SUPPRESS_MUXCLIENT},
1121: {"?", "this message", SUPPRESS_NEVER},
1122: };
1123:
1124: static void
1.315 markus 1125: print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
1126: int using_stderr)
1.244 dtucker 1127: {
1128: unsigned int i, suppress_flags;
1.315 markus 1129: int r;
1.244 dtucker 1130:
1.315 markus 1131: if ((r = sshbuf_putf(b,
1132: "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
1.354 djm 1133: fatal_fr(r, "sshbuf_putf");
1.244 dtucker 1134:
1.292 djm 1135: suppress_flags =
1.244 dtucker 1136: (mux_client ? SUPPRESS_MUXCLIENT : 0) |
1137: (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1.383 djm 1138: (using_stderr ? 0 : SUPPRESS_SYSLOG) |
1139: (options.enable_escape_commandline == 0 ? SUPPRESS_NOCMDLINE : 0);
1.244 dtucker 1140:
1141: for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
1142: if (esc_txt[i].flags & suppress_flags)
1143: continue;
1.315 markus 1144: if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
1145: escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
1.354 djm 1146: fatal_fr(r, "sshbuf_putf");
1.244 dtucker 1147: }
1148:
1.315 markus 1149: if ((r = sshbuf_putf(b,
1.246 dtucker 1150: " %c%c - send the escape character by typing it twice\r\n"
1.244 dtucker 1151: "(Note that escapes are only recognized immediately after "
1.315 markus 1152: "newline.)\r\n", escape_char, escape_char)) != 0)
1.354 djm 1153: fatal_fr(r, "sshbuf_putf");
1.244 dtucker 1154: }
1155:
1.314 djm 1156: /*
1.296 naddy 1157: * Process the characters one by one.
1.195 djm 1158: */
1.77 itojun 1159: static int
1.303 djm 1160: process_escapes(struct ssh *ssh, Channel *c,
1.315 markus 1161: struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
1.195 djm 1162: char *buf, int len)
1.31 markus 1163: {
1164: pid_t pid;
1.315 markus 1165: int r, bytes = 0;
1.42 markus 1166: u_int i;
1167: u_char ch;
1.31 markus 1168: char *s;
1.392 dtucker 1169: struct escape_filter_ctx *efc;
1.31 markus 1170:
1.392 dtucker 1171: if (c == NULL || c->filter_ctx == NULL || len <= 0)
1.294 djm 1172: return 0;
1.314 djm 1173:
1.392 dtucker 1174: efc = (struct escape_filter_ctx *)c->filter_ctx;
1.139 djm 1175:
1176: for (i = 0; i < (u_int)len; i++) {
1.31 markus 1177: /* Get one character at a time. */
1178: ch = buf[i];
1179:
1.294 djm 1180: if (efc->escape_pending) {
1.31 markus 1181: /* We have previously seen an escape character. */
1182: /* Clear the flag now. */
1.294 djm 1183: efc->escape_pending = 0;
1.31 markus 1184:
1185: /* Process the escaped character. */
1186: switch (ch) {
1187: case '.':
1188: /* Terminate the connection. */
1.315 markus 1189: if ((r = sshbuf_putf(berr, "%c.\r\n",
1190: efc->escape_char)) != 0)
1.354 djm 1191: fatal_fr(r, "sshbuf_putf");
1.217 djm 1192: if (c && c->ctl_chan != -1) {
1.387 djm 1193: channel_force_close(ssh, c, 1);
1.195 djm 1194: return 0;
1195: } else
1196: quit_pending = 1;
1.31 markus 1197: return -1;
1198:
1199: case 'Z' - 64:
1.195 djm 1200: /* XXX support this for mux clients */
1.217 djm 1201: if (c && c->ctl_chan != -1) {
1.245 dtucker 1202: char b[16];
1.195 djm 1203: noescape:
1.245 dtucker 1204: if (ch == 'Z' - 64)
1205: snprintf(b, sizeof b, "^Z");
1206: else
1207: snprintf(b, sizeof b, "%c", ch);
1.315 markus 1208: if ((r = sshbuf_putf(berr,
1.245 dtucker 1209: "%c%s escape not available to "
1.195 djm 1210: "multiplexed sessions\r\n",
1.315 markus 1211: efc->escape_char, b)) != 0)
1.354 djm 1212: fatal_fr(r, "sshbuf_putf");
1.195 djm 1213: continue;
1214: }
1.197 djm 1215: /* Suspend the program. Inform the user */
1.315 markus 1216: if ((r = sshbuf_putf(berr,
1217: "%c^Z [suspend ssh]\r\n",
1218: efc->escape_char)) != 0)
1.354 djm 1219: fatal_fr(r, "sshbuf_putf");
1.31 markus 1220:
1221: /* Restore terminal modes and suspend. */
1222: client_suspend_self(bin, bout, berr);
1223:
1224: /* We have been continued. */
1225: continue;
1226:
1.111 markus 1227: case 'B':
1.315 markus 1228: if ((r = sshbuf_putf(berr,
1229: "%cB\r\n", efc->escape_char)) != 0)
1.354 djm 1230: fatal_fr(r, "sshbuf_putf");
1.303 djm 1231: channel_request_start(ssh, c->self, "break", 0);
1.315 markus 1232: if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
1233: (r = sshpkt_send(ssh)) != 0)
1.354 djm 1234: fatal_fr(r, "send packet");
1.111 markus 1235: continue;
1236:
1.54 markus 1237: case 'R':
1.357 djm 1238: if (ssh->compat & SSH_BUG_NOREKEY)
1.292 djm 1239: logit("Server does not "
1240: "support re-keying");
1241: else
1242: need_rekeying = 1;
1.54 markus 1243: continue;
1244:
1.242 dtucker 1245: case 'V':
1246: /* FALLTHROUGH */
1247: case 'v':
1248: if (c && c->ctl_chan != -1)
1249: goto noescape;
1250: if (!log_is_on_stderr()) {
1.315 markus 1251: if ((r = sshbuf_putf(berr,
1.242 dtucker 1252: "%c%c [Logging to syslog]\r\n",
1.315 markus 1253: efc->escape_char, ch)) != 0)
1.354 djm 1254: fatal_fr(r, "sshbuf_putf");
1.242 dtucker 1255: continue;
1256: }
1257: if (ch == 'V' && options.log_level >
1258: SYSLOG_LEVEL_QUIET)
1259: log_change_level(--options.log_level);
1260: if (ch == 'v' && options.log_level <
1261: SYSLOG_LEVEL_DEBUG3)
1262: log_change_level(++options.log_level);
1.315 markus 1263: if ((r = sshbuf_putf(berr,
1.294 djm 1264: "%c%c [LogLevel %s]\r\n",
1265: efc->escape_char, ch,
1.315 markus 1266: log_level_name(options.log_level))) != 0)
1.354 djm 1267: fatal_fr(r, "sshbuf_putf");
1.242 dtucker 1268: continue;
1269:
1.31 markus 1270: case '&':
1.392 dtucker 1271: if (c->ctl_chan != -1)
1.195 djm 1272: goto noescape;
1.31 markus 1273: /*
1.197 djm 1274: * Detach the program (continue to serve
1275: * connections, but put in background and no
1276: * more new connections).
1.31 markus 1277: */
1278: /* Restore tty modes. */
1.233 djm 1279: leave_raw_mode(
1280: options.request_tty == REQUEST_TTY_FORCE);
1.31 markus 1281:
1282: /* Stop listening for new connections. */
1.303 djm 1283: channel_stop_listening(ssh);
1.31 markus 1284:
1.354 djm 1285: if ((r = sshbuf_putf(berr, "%c& "
1286: "[backgrounded]\n", efc->escape_char)) != 0)
1287: fatal_fr(r, "sshbuf_putf");
1.31 markus 1288:
1289: /* Fork into background. */
1290: pid = fork();
1.326 deraadt 1291: if (pid == -1) {
1.31 markus 1292: error("fork: %.100s", strerror(errno));
1293: continue;
1294: }
1295: if (pid != 0) { /* This is the parent. */
1296: /* The parent just exits. */
1297: exit(0);
1298: }
1299: /* The child continues serving connections. */
1.292 djm 1300: /* fake EOF on stdin */
1.315 markus 1301: if ((r = sshbuf_put_u8(bin, 4)) != 0)
1.354 djm 1302: fatal_fr(r, "sshbuf_put_u8");
1.292 djm 1303: return -1;
1.31 markus 1304: case '?':
1.294 djm 1305: print_escape_help(berr, efc->escape_char,
1.244 dtucker 1306: (c && c->ctl_chan != -1),
1307: log_is_on_stderr());
1.31 markus 1308: continue;
1309:
1310: case '#':
1.315 markus 1311: if ((r = sshbuf_putf(berr, "%c#\r\n",
1312: efc->escape_char)) != 0)
1.354 djm 1313: fatal_fr(r, "sshbuf_putf");
1.303 djm 1314: s = channel_open_message(ssh);
1.315 markus 1315: if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
1.354 djm 1316: fatal_fr(r, "sshbuf_put");
1.250 djm 1317: free(s);
1.97 jakob 1318: continue;
1319:
1320: case 'C':
1.217 djm 1321: if (c && c->ctl_chan != -1)
1.206 djm 1322: goto noescape;
1.383 djm 1323: if (options.enable_escape_commandline == 0) {
1324: if ((r = sshbuf_putf(berr,
1325: "commandline disabled\r\n")) != 0)
1326: fatal_fr(r, "sshbuf_putf");
1327: continue;
1328: }
1.303 djm 1329: process_cmdline(ssh);
1.31 markus 1330: continue;
1331:
1332: default:
1.294 djm 1333: if (ch != efc->escape_char) {
1.315 markus 1334: if ((r = sshbuf_put_u8(bin,
1335: efc->escape_char)) != 0)
1.354 djm 1336: fatal_fr(r, "sshbuf_put_u8");
1.31 markus 1337: bytes++;
1338: }
1339: /* Escaped characters fall through here */
1340: break;
1341: }
1342: } else {
1343: /*
1.197 djm 1344: * The previous character was not an escape char.
1345: * Check if this is an escape.
1.31 markus 1346: */
1.294 djm 1347: if (last_was_cr && ch == efc->escape_char) {
1.197 djm 1348: /*
1349: * It is. Set the flag and continue to
1350: * next character.
1351: */
1.294 djm 1352: efc->escape_pending = 1;
1.31 markus 1353: continue;
1354: }
1355: }
1356:
1357: /*
1358: * Normal character. Record whether it was a newline,
1359: * and append it to the buffer.
1360: */
1361: last_was_cr = (ch == '\r' || ch == '\n');
1.315 markus 1362: if ((r = sshbuf_put_u8(bin, ch)) != 0)
1.354 djm 1363: fatal_fr(r, "sshbuf_put_u8");
1.31 markus 1364: bytes++;
1365: }
1366: return bytes;
1367: }
1368:
1.13 markus 1369: /*
1.15 markus 1370: * Get packets from the connection input buffer, and process them as long as
1371: * there are packets available.
1372: *
1373: * Any unknown packets received during the actual
1374: * session cause the session to terminate. This is
1375: * intended to make debugging easier since no
1376: * confirmations are sent. Any compatible protocol
1377: * extensions must be negotiated during the
1378: * preparatory phase.
1379: */
1380:
1.77 itojun 1381: static void
1.321 djm 1382: client_process_buffered_input_packets(struct ssh *ssh)
1.15 markus 1383: {
1.321 djm 1384: ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending);
1.15 markus 1385: }
1386:
1.31 markus 1387: /* scan buf[] for '~' before sending data to the peer */
1.30 markus 1388:
1.195 djm 1389: /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1390: void *
1391: client_new_escape_filter_ctx(int escape_char)
1392: {
1393: struct escape_filter_ctx *ret;
1394:
1.255 djm 1395: ret = xcalloc(1, sizeof(*ret));
1.195 djm 1396: ret->escape_pending = 0;
1397: ret->escape_char = escape_char;
1398: return (void *)ret;
1399: }
1400:
1.198 djm 1401: /* Free the escape filter context on channel free */
1402: void
1.303 djm 1403: client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1.198 djm 1404: {
1.250 djm 1405: free(ctx);
1.198 djm 1406: }
1407:
1.195 djm 1408: int
1.303 djm 1409: client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1.30 markus 1410: {
1.190 djm 1411: if (c->extended_usage != CHAN_EXTENDED_WRITE)
1412: return 0;
1413:
1.303 djm 1414: return process_escapes(ssh, c, c->input, c->output, c->extended,
1.195 djm 1415: buf, len);
1.30 markus 1416: }
1417:
1.77 itojun 1418: static void
1.387 djm 1419: client_channel_closed(struct ssh *ssh, int id, int force, void *arg)
1.60 markus 1420: {
1.303 djm 1421: channel_cancel_cleanup(ssh, id);
1.60 markus 1422: session_closed = 1;
1.233 djm 1423: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.60 markus 1424: }
1425:
1.15 markus 1426: /*
1.13 markus 1427: * Implements the interactive session with the server. This is called after
1428: * the user has been authenticated, and a command has been started on the
1.72 stevesk 1429: * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1430: * used as an escape character for terminating or suspending the session.
1.13 markus 1431: */
1.20 markus 1432: int
1.303 djm 1433: client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
1434: int ssh2_chan_id)
1.1 deraadt 1435: {
1.374 djm 1436: struct pollfd *pfd = NULL;
1437: u_int npfd_alloc = 0, npfd_active = 0;
1.11 markus 1438: double start_time, total_time;
1.396 djm 1439: int channel_did_enqueue = 0, r, len;
1.200 markus 1440: u_int64_t ibytes, obytes;
1.374 djm 1441: int conn_in_ready, conn_out_ready;
1.400 djm 1442: sigset_t bsigset, osigset;
1.11 markus 1443:
1444: debug("Entering interactive session.");
1.384 djm 1445: session_ident = ssh2_chan_id;
1.277 semarie 1446:
1.278 semarie 1447: if (options.control_master &&
1.286 djm 1448: !option_clear_or_none(options.control_path)) {
1.278 semarie 1449: debug("pledge: id");
1.327 mestre 1450: if (pledge("stdio rpath wpath cpath unix inet dns recvfd sendfd proc exec id tty",
1.278 semarie 1451: NULL) == -1)
1.354 djm 1452: fatal_f("pledge(): %s", strerror(errno));
1.278 semarie 1453:
1454: } else if (options.forward_x11 || options.permit_local_command) {
1.277 semarie 1455: debug("pledge: exec");
1456: if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1457: NULL) == -1)
1.354 djm 1458: fatal_f("pledge(): %s", strerror(errno));
1.277 semarie 1459:
1460: } else if (options.update_hostkeys) {
1.373 jsg 1461: debug("pledge: filesystem");
1.277 semarie 1462: if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1463: NULL) == -1)
1.354 djm 1464: fatal_f("pledge(): %s", strerror(errno));
1.277 semarie 1465:
1.286 djm 1466: } else if (!option_clear_or_none(options.proxy_command) ||
1.369 djm 1467: options.fork_after_authentication) {
1.277 semarie 1468: debug("pledge: proc");
1469: if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1.354 djm 1470: fatal_f("pledge(): %s", strerror(errno));
1.277 semarie 1471:
1472: } else {
1473: debug("pledge: network");
1.300 mestre 1474: if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1.354 djm 1475: fatal_f("pledge(): %s", strerror(errno));
1.277 semarie 1476: }
1.11 markus 1477:
1.384 djm 1478: /* might be able to tighten now */
1479: client_repledge();
1480:
1.307 dtucker 1481: start_time = monotime_double();
1.11 markus 1482:
1483: /* Initialize variables. */
1484: last_was_cr = 1;
1485: exit_status = -1;
1.320 djm 1486: connection_in = ssh_packet_get_connection_in(ssh);
1487: connection_out = ssh_packet_get_connection_out(ssh);
1.46 markus 1488:
1.11 markus 1489: quit_pending = 0;
1490:
1.315 markus 1491: /* Initialize buffer. */
1492: if ((stderr_buffer = sshbuf_new()) == NULL)
1.354 djm 1493: fatal_f("sshbuf_new failed");
1.11 markus 1494:
1.321 djm 1495: client_init_dispatch(ssh);
1.15 markus 1496:
1.105 markus 1497: /*
1498: * Set signal handlers, (e.g. to restore non-blocking mode)
1499: * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1500: */
1.332 dtucker 1501: if (ssh_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1502: ssh_signal(SIGHUP, signal_handler);
1503: if (ssh_signal(SIGINT, SIG_IGN) != SIG_IGN)
1504: ssh_signal(SIGINT, signal_handler);
1505: if (ssh_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1506: ssh_signal(SIGQUIT, signal_handler);
1507: if (ssh_signal(SIGTERM, SIG_IGN) != SIG_IGN)
1508: ssh_signal(SIGTERM, signal_handler);
1509: ssh_signal(SIGWINCH, window_change_handler);
1.11 markus 1510:
1511: if (have_pty)
1.233 djm 1512: enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11 markus 1513:
1.292 djm 1514: if (session_ident != -1) {
1515: if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1.303 djm 1516: channel_register_filter(ssh, session_ident,
1.292 djm 1517: client_simple_escape_filter, NULL,
1518: client_filter_cleanup,
1519: client_new_escape_filter_ctx(
1520: escape_char_arg));
1.232 djm 1521: }
1.303 djm 1522: channel_register_cleanup(ssh, session_ident,
1.292 djm 1523: client_channel_closed, 0);
1.48 markus 1524: }
1.345 dtucker 1525:
1526: schedule_server_alive_check();
1.30 markus 1527:
1.400 djm 1528: if (sigemptyset(&bsigset) == -1 ||
1529: sigaddset(&bsigset, SIGHUP) == -1 ||
1530: sigaddset(&bsigset, SIGINT) == -1 ||
1531: sigaddset(&bsigset, SIGQUIT) == -1 ||
1532: sigaddset(&bsigset, SIGTERM) == -1)
1533: error_f("bsigset setup: %s", strerror(errno));
1534:
1.11 markus 1535: /* Main loop of the client for the interactive session mode. */
1536: while (!quit_pending) {
1.396 djm 1537: channel_did_enqueue = 0;
1.11 markus 1538:
1.13 markus 1539: /* Process buffered packets sent by the server. */
1.321 djm 1540: client_process_buffered_input_packets(ssh);
1.11 markus 1541:
1.303 djm 1542: if (session_closed && !channel_still_open(ssh))
1.60 markus 1543: break;
1544:
1.303 djm 1545: if (ssh_packet_is_rekeying(ssh)) {
1.56 markus 1546: debug("rekeying in progress");
1.284 djm 1547: } else if (need_rekeying) {
1548: /* manual rekey request */
1549: debug("need rekeying");
1.303 djm 1550: if ((r = kex_start_rekex(ssh)) != 0)
1.354 djm 1551: fatal_fr(r, "kex_start_rekex");
1.284 djm 1552: need_rekeying = 0;
1.56 markus 1553: } else {
1554: /*
1555: * Make packets from buffered channel data, and
1556: * enqueue them for sending to the server.
1557: */
1.320 djm 1558: if (ssh_packet_not_very_much_data_to_write(ssh))
1.396 djm 1559: channel_did_enqueue = channel_output_poll(ssh);
1.11 markus 1560:
1.56 markus 1561: /*
1562: * Check if the window size has changed, and buffer a
1563: * message about it to the server if so.
1564: */
1.303 djm 1565: client_check_window_change(ssh);
1.56 markus 1566: }
1.13 markus 1567: /*
1568: * Wait until we have something to do (something becomes
1569: * available on one of the descriptors).
1570: */
1.400 djm 1571: if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1)
1572: error_f("bsigset sigprocmask: %s", strerror(errno));
1573: if (quit_pending)
1574: break;
1.374 djm 1575: client_wait_until_can_do_something(ssh, &pfd, &npfd_alloc,
1.400 djm 1576: &npfd_active, channel_did_enqueue, &osigset,
1.374 djm 1577: &conn_in_ready, &conn_out_ready);
1.400 djm 1578: if (sigprocmask(SIG_UNBLOCK, &bsigset, &osigset) == -1)
1579: error_f("osigset sigprocmask: %s", strerror(errno));
1.11 markus 1580:
1581: if (quit_pending)
1582: break;
1583:
1.379 djm 1584: /* Do channel operations. */
1585: channel_after_poll(ssh, pfd, npfd_active);
1.11 markus 1586:
1.17 markus 1587: /* Buffer input from the connection. */
1.374 djm 1588: if (conn_in_ready)
1589: client_process_net_input(ssh);
1.17 markus 1590:
1591: if (quit_pending)
1592: break;
1.367 djm 1593:
1594: /* A timeout may have triggered rekeying */
1595: if ((r = ssh_packet_check_rekey(ssh)) != 0)
1596: fatal_fr(r, "cannot start rekeying");
1.11 markus 1597:
1.197 djm 1598: /*
1599: * Send as much buffered packet data as possible to the
1600: * sender.
1601: */
1.374 djm 1602: if (conn_out_ready) {
1.338 djm 1603: if ((r = ssh_packet_write_poll(ssh)) != 0) {
1604: sshpkt_fatal(ssh, r,
1605: "%s: ssh_packet_write_poll", __func__);
1606: }
1607: }
1.222 djm 1608:
1609: /*
1610: * If we are a backgrounded control master, and the
1611: * timeout has expired without any active client
1612: * connections, then quit.
1613: */
1614: if (control_persist_exit_time > 0) {
1.251 dtucker 1615: if (monotime() >= control_persist_exit_time) {
1.222 djm 1616: debug("ControlPersist timeout expired");
1617: break;
1618: }
1619: }
1.11 markus 1620: }
1.374 djm 1621: free(pfd);
1.11 markus 1622:
1623: /* Terminate the session. */
1624:
1625: /* Stop watching for window change. */
1.332 dtucker 1626: ssh_signal(SIGWINCH, SIG_DFL);
1.211 andreas 1627:
1.320 djm 1628: if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
1629: (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 ||
1630: (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 ||
1631: (r = sshpkt_put_cstring(ssh, "")) != 0 || /* language tag */
1632: (r = sshpkt_send(ssh)) != 0 ||
1633: (r = ssh_packet_write_wait(ssh)) != 0)
1.354 djm 1634: fatal_fr(r, "send disconnect");
1.11 markus 1635:
1.303 djm 1636: channel_free_all(ssh);
1.11 markus 1637:
1.75 markus 1638: if (have_pty)
1.233 djm 1639: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.116 dtucker 1640:
1641: /*
1642: * If there was no shell or command requested, there will be no remote
1643: * exit status to be returned. In that case, clear error code if the
1644: * connection was deliberately terminated at this end.
1645: */
1.370 djm 1646: if (options.session_type == SESSION_TYPE_NONE &&
1647: received_signal == SIGTERM) {
1.116 dtucker 1648: received_signal = 0;
1649: exit_status = 0;
1650: }
1.75 markus 1651:
1.301 dtucker 1652: if (received_signal) {
1653: verbose("Killed by signal %d.", (int) received_signal);
1.359 djm 1654: cleanup_exit(255);
1.301 dtucker 1655: }
1.75 markus 1656:
1.13 markus 1657: /*
1658: * In interactive mode (with pseudo tty) display a message indicating
1659: * that the connection has been closed.
1660: */
1.377 djm 1661: if (have_pty && options.log_level >= SYSLOG_LEVEL_INFO)
1662: quit_message("Connection to %s closed.", host);
1.70 markus 1663:
1.11 markus 1664: /* Output any buffered data for stderr. */
1.315 markus 1665: if (sshbuf_len(stderr_buffer) > 0) {
1.230 djm 1666: len = atomicio(vwrite, fileno(stderr),
1.315 markus 1667: (u_char *)sshbuf_ptr(stderr_buffer),
1668: sshbuf_len(stderr_buffer));
1669: if (len < 0 || (u_int)len != sshbuf_len(stderr_buffer))
1.11 markus 1670: error("Write failed flushing stderr buffer.");
1.315 markus 1671: else if ((r = sshbuf_consume(stderr_buffer, len)) != 0)
1.354 djm 1672: fatal_fr(r, "sshbuf_consume");
1.11 markus 1673: }
1674:
1675: /* Clear and free any buffers. */
1.315 markus 1676: sshbuf_free(stderr_buffer);
1.11 markus 1677:
1678: /* Report bytes transferred, and transfer rates. */
1.307 dtucker 1679: total_time = monotime_double() - start_time;
1.320 djm 1680: ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1.200 markus 1681: verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1.229 djm 1682: (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1.11 markus 1683: if (total_time > 0)
1.200 markus 1684: verbose("Bytes per second: sent %.1f, received %.1f",
1685: obytes / total_time, ibytes / total_time);
1.11 markus 1686: /* Return the exit status of the program. */
1687: debug("Exit status %d", exit_status);
1688: return exit_status;
1.15 markus 1689: }
1690:
1691: /*********/
1692:
1.77 itojun 1693: static Channel *
1.303 djm 1694: client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
1695: int rchan, u_int rwindow, u_int rmaxpack)
1.40 markus 1696: {
1.103 deraadt 1697: Channel *c = NULL;
1.289 markus 1698: struct sshbuf *b = NULL;
1.40 markus 1699: char *listen_address, *originator_address;
1.320 djm 1700: u_int listen_port, originator_port;
1.289 markus 1701: int r;
1.40 markus 1702:
1703: /* Get rest of the packet */
1.320 djm 1704: if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 ||
1705: (r = sshpkt_get_u32(ssh, &listen_port)) != 0 ||
1706: (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 ||
1707: (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1708: (r = sshpkt_get_end(ssh)) != 0)
1.354 djm 1709: fatal_fr(r, "parse packet");
1.40 markus 1710:
1.354 djm 1711: debug_f("listen %s port %d, originator %s port %d",
1.261 millert 1712: listen_address, listen_port, originator_address, originator_port);
1.191 djm 1713:
1.320 djm 1714: if (listen_port > 0xffff)
1.354 djm 1715: error_f("invalid listen port");
1.320 djm 1716: else if (originator_port > 0xffff)
1.354 djm 1717: error_f("invalid originator port");
1.320 djm 1718: else {
1719: c = channel_connect_by_listen_address(ssh,
1720: listen_address, listen_port, "forwarded-tcpip",
1721: originator_address);
1722: }
1.40 markus 1723:
1.289 markus 1724: if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1725: if ((b = sshbuf_new()) == NULL) {
1.354 djm 1726: error_f("alloc reply");
1.289 markus 1727: goto out;
1728: }
1729: /* reconstruct and send to muxclient */
1730: if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1731: (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1732: (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1733: (r = sshbuf_put_u32(b, rchan)) != 0 ||
1734: (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1735: (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1736: (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1737: (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1738: (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1739: (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1.303 djm 1740: (r = sshbuf_put_stringb(c->output, b)) != 0) {
1.354 djm 1741: error_fr(r, "compose for muxclient");
1.289 markus 1742: goto out;
1743: }
1744: }
1745:
1746: out:
1747: sshbuf_free(b);
1.250 djm 1748: free(originator_address);
1749: free(listen_address);
1.40 markus 1750: return c;
1751: }
1752:
1.103 deraadt 1753: static Channel *
1.303 djm 1754: client_request_forwarded_streamlocal(struct ssh *ssh,
1755: const char *request_type, int rchan)
1.261 millert 1756: {
1757: Channel *c = NULL;
1758: char *listen_path;
1.320 djm 1759: int r;
1.261 millert 1760:
1761: /* Get the remote path. */
1.320 djm 1762: if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 ||
1763: (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* reserved */
1764: (r = sshpkt_get_end(ssh)) != 0)
1.354 djm 1765: fatal_fr(r, "parse packet");
1.261 millert 1766:
1.354 djm 1767: debug_f("request: %s", listen_path);
1.261 millert 1768:
1.303 djm 1769: c = channel_connect_by_listen_path(ssh, listen_path,
1.261 millert 1770: "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1771: free(listen_path);
1772: return c;
1773: }
1774:
1775: static Channel *
1.303 djm 1776: client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1.40 markus 1777: {
1778: Channel *c = NULL;
1779: char *originator;
1.321 djm 1780: u_int originator_port;
1.320 djm 1781: int r, sock;
1.40 markus 1782:
1783: if (!options.forward_x11) {
1784: error("Warning: ssh server tried X11 forwarding.");
1.197 djm 1785: error("Warning: this is probably a break-in attempt by a "
1786: "malicious server.");
1.221 djm 1787: return NULL;
1788: }
1.388 dtucker 1789: if (x11_refuse_time != 0 && monotime() >= x11_refuse_time) {
1.221 djm 1790: verbose("Rejected X11 connection after ForwardX11Timeout "
1791: "expired");
1.40 markus 1792: return NULL;
1793: }
1.320 djm 1794: if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
1.321 djm 1795: (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1.320 djm 1796: (r = sshpkt_get_end(ssh)) != 0)
1.354 djm 1797: fatal_fr(r, "parse packet");
1.40 markus 1798: /* XXX check permission */
1.321 djm 1799: /* XXX range check originator port? */
1800: debug("client_request_x11: request from %s %u", originator,
1.47 markus 1801: originator_port);
1.250 djm 1802: free(originator);
1.303 djm 1803: sock = x11_connect_display(ssh);
1.67 markus 1804: if (sock < 0)
1805: return NULL;
1.399 djm 1806: c = channel_new(ssh, "x11-connection",
1.67 markus 1807: SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1.110 markus 1808: CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1.82 markus 1809: c->force_drain = 1;
1.40 markus 1810: return c;
1811: }
1812:
1.103 deraadt 1813: static Channel *
1.303 djm 1814: client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1.40 markus 1815: {
1816: Channel *c = NULL;
1.262 djm 1817: int r, sock;
1.40 markus 1818:
1819: if (!options.forward_agent) {
1820: error("Warning: ssh server tried agent forwarding.");
1.197 djm 1821: error("Warning: this is probably a break-in attempt by a "
1822: "malicious server.");
1.40 markus 1823: return NULL;
1824: }
1.330 djm 1825: if (forward_agent_sock_path == NULL) {
1826: r = ssh_get_authentication_socket(&sock);
1827: } else {
1828: r = ssh_get_authentication_socket_path(forward_agent_sock_path, &sock);
1829: }
1830: if (r != 0) {
1.262 djm 1831: if (r != SSH_ERR_AGENT_NOT_PRESENT)
1.354 djm 1832: debug_fr(r, "ssh_get_authentication_socket");
1.67 markus 1833: return NULL;
1.262 djm 1834: }
1.372 djm 1835: if ((r = ssh_agent_bind_hostkey(sock, ssh->kex->initial_hostkey,
1836: ssh->kex->session_id, ssh->kex->initial_sig, 1)) == 0)
1837: debug_f("bound agent to hostkey");
1838: else
1839: debug2_fr(r, "ssh_agent_bind_hostkey");
1840:
1.399 djm 1841: c = channel_new(ssh, "agent-connection",
1.67 markus 1842: SSH_CHANNEL_OPEN, sock, sock, -1,
1.185 dtucker 1843: CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1.110 markus 1844: "authentication agent connection", 1);
1.82 markus 1845: c->force_drain = 1;
1.40 markus 1846: return c;
1.180 djm 1847: }
1848:
1.306 djm 1849: char *
1.303 djm 1850: client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1.343 djm 1851: int local_tun, int remote_tun, channel_open_fn *cb, void *cbctx)
1.180 djm 1852: {
1853: Channel *c;
1.320 djm 1854: int r, fd;
1.306 djm 1855: char *ifname = NULL;
1.180 djm 1856:
1857: if (tun_mode == SSH_TUNMODE_NO)
1858: return 0;
1859:
1860: debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1861:
1862: /* Open local tunnel device */
1.306 djm 1863: if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
1.180 djm 1864: error("Tunnel device open failed.");
1.306 djm 1865: return NULL;
1.180 djm 1866: }
1.306 djm 1867: debug("Tunnel forwarding using interface %s", ifname);
1.180 djm 1868:
1.399 djm 1869: c = channel_new(ssh, "tun-connection", SSH_CHANNEL_OPENING, fd, fd, -1,
1.180 djm 1870: CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1871: c->datagram = 1;
1.343 djm 1872:
1873: if (cb != NULL)
1874: channel_register_open_confirm(ssh, c->self, cb, cbctx);
1.180 djm 1875:
1.320 djm 1876: if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1877: (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 ||
1878: (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1879: (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 ||
1880: (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1881: (r = sshpkt_put_u32(ssh, tun_mode)) != 0 ||
1882: (r = sshpkt_put_u32(ssh, remote_tun)) != 0 ||
1883: (r = sshpkt_send(ssh)) != 0)
1.321 djm 1884: sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1.180 djm 1885:
1.306 djm 1886: return ifname;
1.40 markus 1887: }
1888:
1.22 markus 1889: /* XXXX move to generic input handler */
1.264 markus 1890: static int
1.297 markus 1891: client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1.22 markus 1892: {
1893: Channel *c = NULL;
1.320 djm 1894: char *ctype = NULL;
1895: int r;
1896: u_int rchan;
1897: size_t len;
1898: u_int rmaxpack, rwindow;
1899:
1900: if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 ||
1901: (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
1902: (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
1903: (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
1904: goto out;
1.22 markus 1905:
1.24 markus 1906: debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1.22 markus 1907: ctype, rchan, rwindow, rmaxpack);
1908:
1.40 markus 1909: if (strcmp(ctype, "forwarded-tcpip") == 0) {
1.303 djm 1910: c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1.289 markus 1911: rmaxpack);
1.261 millert 1912: } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1.303 djm 1913: c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1.40 markus 1914: } else if (strcmp(ctype, "x11") == 0) {
1.303 djm 1915: c = client_request_x11(ssh, ctype, rchan);
1.40 markus 1916: } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1.303 djm 1917: c = client_request_agent(ssh, ctype, rchan);
1.22 markus 1918: }
1.289 markus 1919: if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1920: debug3("proxied to downstream: %s", ctype);
1921: } else if (c != NULL) {
1.22 markus 1922: debug("confirm %s", ctype);
1923: c->remote_id = rchan;
1.304 djm 1924: c->have_remote_id = 1;
1.22 markus 1925: c->remote_window = rwindow;
1926: c->remote_maxpacket = rmaxpack;
1.69 markus 1927: if (c->type != SSH_CHANNEL_CONNECTING) {
1.320 djm 1928: if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1929: (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1930: (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1931: (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1932: (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1933: (r = sshpkt_send(ssh)) != 0)
1934: sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1.69 markus 1935: }
1.22 markus 1936: } else {
1937: debug("failure %s", ctype);
1.320 djm 1938: if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1939: (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
1940: (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 ||
1941: (r = sshpkt_put_cstring(ssh, "open failed")) != 0 ||
1942: (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1943: (r = sshpkt_send(ssh)) != 0)
1944: sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1.22 markus 1945: }
1.320 djm 1946: r = 0;
1947: out:
1.250 djm 1948: free(ctype);
1.320 djm 1949: return r;
1.22 markus 1950: }
1.267 djm 1951:
1.264 markus 1952: static int
1.297 markus 1953: client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1.48 markus 1954: {
1955: Channel *c = NULL;
1.320 djm 1956: char *rtype = NULL;
1957: u_char reply;
1958: u_int id, exitval;
1959: int r, success = 0;
1960:
1961: if ((r = sshpkt_get_u32(ssh, &id)) != 0)
1962: return r;
1963: if (id <= INT_MAX)
1964: c = channel_lookup(ssh, id);
1.297 markus 1965: if (channel_proxy_upstream(c, type, seq, ssh))
1.289 markus 1966: return 0;
1.320 djm 1967: if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
1968: (r = sshpkt_get_u8(ssh, &reply)) != 0)
1969: goto out;
1.48 markus 1970:
1.320 djm 1971: debug("client_input_channel_req: channel %u rtype %s reply %d",
1.48 markus 1972: id, rtype, reply);
1973:
1.320 djm 1974: if (c == NULL) {
1.197 djm 1975: error("client_input_channel_req: channel %d: "
1976: "unknown channel", id);
1.193 markus 1977: } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1.320 djm 1978: if ((r = sshpkt_get_end(ssh)) != 0)
1979: goto out;
1.303 djm 1980: chan_rcvd_eow(ssh, c);
1.48 markus 1981: } else if (strcmp(rtype, "exit-status") == 0) {
1.320 djm 1982: if ((r = sshpkt_get_u32(ssh, &exitval)) != 0)
1983: goto out;
1.217 djm 1984: if (c->ctl_chan != -1) {
1.303 djm 1985: mux_exit_message(ssh, c, exitval);
1.215 djm 1986: success = 1;
1.320 djm 1987: } else if ((int)id == session_ident) {
1.215 djm 1988: /* Record exit value of local session */
1.123 djm 1989: success = 1;
1990: exit_status = exitval;
1.215 djm 1991: } else {
1.218 djm 1992: /* Probably for a mux channel that has already closed */
1.354 djm 1993: debug_f("no sink for exit-status on channel %d",
1994: id);
1.123 djm 1995: }
1.320 djm 1996: if ((r = sshpkt_get_end(ssh)) != 0)
1997: goto out;
1.48 markus 1998: }
1.259 djm 1999: if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1.304 djm 2000: if (!c->have_remote_id)
1.354 djm 2001: fatal_f("channel %d: no remote_id", c->self);
1.320 djm 2002: if ((r = sshpkt_start(ssh, success ?
2003: SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
2004: (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2005: (r = sshpkt_send(ssh)) != 0)
2006: sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1.48 markus 2007: }
1.320 djm 2008: r = 0;
2009: out:
1.250 djm 2010: free(rtype);
1.320 djm 2011: return r;
1.48 markus 2012: }
1.267 djm 2013:
1.269 djm 2014: struct hostkeys_update_ctx {
2015: /* The hostname and (optionally) IP address string for the server */
2016: char *host_str, *ip_str;
2017:
2018: /*
2019: * Keys received from the server and a flag for each indicating
2020: * whether they already exist in known_hosts.
1.351 djm 2021: * keys_match is filled in by hostkeys_find() and later (for new
1.381 djm 2022: * keys) by client_global_hostkeys_prove_confirm().
1.269 djm 2023: */
2024: struct sshkey **keys;
1.351 djm 2025: u_int *keys_match; /* mask of HKF_MATCH_* from hostfile.h */
2026: int *keys_verified; /* flag for new keys verified by server */
2027: size_t nkeys, nnew, nincomplete; /* total, new keys, incomplete match */
1.269 djm 2028:
2029: /*
2030: * Keys that are in known_hosts, but were not present in the update
2031: * from the server (i.e. scheduled to be deleted).
2032: * Filled in by hostkeys_find().
2033: */
2034: struct sshkey **old_keys;
2035: size_t nold;
1.347 djm 2036:
2037: /* Various special cases. */
1.350 djm 2038: int complex_hostspec; /* wildcard or manual pattern-list host name */
1.347 djm 2039: int ca_available; /* saw CA key for this host */
1.352 djm 2040: int old_key_seen; /* saw old key with other name/addr */
1.353 djm 2041: int other_name_seen; /* saw key with other name/addr */
1.269 djm 2042: };
2043:
2044: static void
2045: hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
2046: {
2047: size_t i;
2048:
2049: if (ctx == NULL)
2050: return;
2051: for (i = 0; i < ctx->nkeys; i++)
2052: sshkey_free(ctx->keys[i]);
2053: free(ctx->keys);
1.351 djm 2054: free(ctx->keys_match);
2055: free(ctx->keys_verified);
1.269 djm 2056: for (i = 0; i < ctx->nold; i++)
2057: sshkey_free(ctx->old_keys[i]);
2058: free(ctx->old_keys);
2059: free(ctx->host_str);
2060: free(ctx->ip_str);
2061: free(ctx);
2062: }
2063:
1.350 djm 2064: /*
2065: * Returns non-zero if a known_hosts hostname list is not of a form that
2066: * can be handled by UpdateHostkeys. These include wildcard hostnames and
2067: * hostnames lists that do not follow the form host[,ip].
2068: */
2069: static int
2070: hostspec_is_complex(const char *hosts)
2071: {
2072: char *cp;
2073:
2074: /* wildcard */
2075: if (strchr(hosts, '*') != NULL || strchr(hosts, '?') != NULL)
2076: return 1;
2077: /* single host/ip = ok */
2078: if ((cp = strchr(hosts, ',')) == NULL)
2079: return 0;
2080: /* more than two entries on the line */
2081: if (strchr(cp + 1, ',') != NULL)
2082: return 1;
2083: /* XXX maybe parse cp+1 and ensure it is an IP? */
2084: return 0;
2085: }
2086:
1.352 djm 2087: /* callback to search for ctx->keys in known_hosts */
1.269 djm 2088: static int
2089: hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
2090: {
2091: struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2092: size_t i;
2093: struct sshkey **tmp;
2094:
1.353 djm 2095: if (l->key == NULL)
1.269 djm 2096: return 0;
1.353 djm 2097: if (l->status != HKF_STATUS_MATCHED) {
2098: /* Record if one of the keys appears on a non-matching line */
2099: for (i = 0; i < ctx->nkeys; i++) {
2100: if (sshkey_equal(l->key, ctx->keys[i])) {
2101: ctx->other_name_seen = 1;
1.354 djm 2102: debug3_f("found %s key under different "
2103: "name/addr at %s:%ld",
1.353 djm 2104: sshkey_ssh_name(ctx->keys[i]),
2105: l->path, l->linenum);
2106: return 0;
2107: }
2108: }
2109: return 0;
2110: }
2111: /* Don't proceed if revocation or CA markers are present */
2112: /* XXX relax this */
2113: if (l->marker != MRK_NONE) {
1.354 djm 2114: debug3_f("hostkeys file %s:%ld has CA/revocation marker",
2115: l->path, l->linenum);
1.353 djm 2116: ctx->complex_hostspec = 1;
2117: return 0;
2118: }
2119:
1.355 djm 2120: /* If CheckHostIP is enabled, then check for mismatched hostname/addr */
2121: if (ctx->ip_str != NULL && strchr(l->hosts, ',') != NULL) {
2122: if ((l->match & HKF_MATCH_HOST) == 0) {
2123: /* Record if address matched a different hostname. */
2124: ctx->other_name_seen = 1;
2125: debug3_f("found address %s against different hostname "
2126: "at %s:%ld", ctx->ip_str, l->path, l->linenum);
2127: return 0;
2128: } else if ((l->match & HKF_MATCH_IP) == 0) {
2129: /* Record if hostname matched a different address. */
2130: ctx->other_name_seen = 1;
2131: debug3_f("found hostname %s against different address "
2132: "at %s:%ld", ctx->host_str, l->path, l->linenum);
2133: }
1.353 djm 2134: }
1.269 djm 2135:
1.350 djm 2136: /*
2137: * UpdateHostkeys is skipped for wildcard host names and hostnames
2138: * that contain more than two entries (ssh never writes these).
2139: */
2140: if (hostspec_is_complex(l->hosts)) {
1.354 djm 2141: debug3_f("hostkeys file %s:%ld complex host specification",
2142: l->path, l->linenum);
1.350 djm 2143: ctx->complex_hostspec = 1;
1.347 djm 2144: return 0;
2145: }
2146:
1.269 djm 2147: /* Mark off keys we've already seen for this host */
2148: for (i = 0; i < ctx->nkeys; i++) {
1.351 djm 2149: if (!sshkey_equal(l->key, ctx->keys[i]))
2150: continue;
1.354 djm 2151: debug3_f("found %s key at %s:%ld",
1.351 djm 2152: sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
2153: ctx->keys_match[i] |= l->match;
2154: return 0;
1.269 djm 2155: }
2156: /* This line contained a key that not offered by the server */
1.354 djm 2157: debug3_f("deprecated %s key at %s:%ld", sshkey_ssh_name(l->key),
2158: l->path, l->linenum);
1.299 deraadt 2159: if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
1.269 djm 2160: sizeof(*ctx->old_keys))) == NULL)
1.354 djm 2161: fatal_f("recallocarray failed nold = %zu", ctx->nold);
1.269 djm 2162: ctx->old_keys = tmp;
2163: ctx->old_keys[ctx->nold++] = l->key;
2164: l->key = NULL;
2165:
2166: return 0;
2167: }
2168:
1.352 djm 2169: /* callback to search for ctx->old_keys in known_hosts under other names */
2170: static int
2171: hostkeys_check_old(struct hostkey_foreach_line *l, void *_ctx)
2172: {
2173: struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2174: size_t i;
2175: int hashed;
2176:
2177: /* only care about lines that *don't* match the active host spec */
2178: if (l->status == HKF_STATUS_MATCHED || l->key == NULL)
2179: return 0;
2180:
2181: hashed = l->match & (HKF_MATCH_HOST_HASHED|HKF_MATCH_IP_HASHED);
2182: for (i = 0; i < ctx->nold; i++) {
2183: if (!sshkey_equal(l->key, ctx->old_keys[i]))
2184: continue;
1.354 djm 2185: debug3_f("found deprecated %s key at %s:%ld as %s",
1.364 djm 2186: sshkey_ssh_name(ctx->old_keys[i]), l->path, l->linenum,
1.352 djm 2187: hashed ? "[HASHED]" : l->hosts);
2188: ctx->old_key_seen = 1;
2189: break;
2190: }
2191: return 0;
2192: }
2193:
2194: /*
2195: * Check known_hosts files for deprecated keys under other names. Returns 0
2196: * on success or -1 on failure. Updates ctx->old_key_seen if deprecated keys
2197: * exist under names other than the active hostname/IP.
2198: */
2199: static int
2200: check_old_keys_othernames(struct hostkeys_update_ctx *ctx)
2201: {
2202: size_t i;
2203: int r;
2204:
1.354 djm 2205: debug2_f("checking for %zu deprecated keys", ctx->nold);
1.352 djm 2206: for (i = 0; i < options.num_user_hostfiles; i++) {
1.354 djm 2207: debug3_f("searching %s for %s / %s",
1.352 djm 2208: options.user_hostfiles[i], ctx->host_str,
2209: ctx->ip_str ? ctx->ip_str : "(none)");
2210: if ((r = hostkeys_foreach(options.user_hostfiles[i],
2211: hostkeys_check_old, ctx, ctx->host_str, ctx->ip_str,
1.356 djm 2212: HKF_WANT_PARSE_KEY, 0)) != 0) {
1.352 djm 2213: if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
1.354 djm 2214: debug_f("hostkeys file %s does not exist",
2215: options.user_hostfiles[i]);
1.352 djm 2216: continue;
2217: }
1.354 djm 2218: error_fr(r, "hostkeys_foreach failed for %s",
2219: options.user_hostfiles[i]);
1.352 djm 2220: return -1;
2221: }
2222: }
2223: return 0;
2224: }
2225:
1.269 djm 2226: static void
1.337 djm 2227: hostkey_change_preamble(LogLevel loglevel)
1.269 djm 2228: {
1.336 djm 2229: do_log2(loglevel, "The server has updated its host keys.");
2230: do_log2(loglevel, "These changes were verified by the server's "
2231: "existing trusted key.");
2232: }
2233:
2234: static void
2235: update_known_hosts(struct hostkeys_update_ctx *ctx)
2236: {
2237: int r, was_raw = 0, first = 1;
2238: int asking = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK;
2239: LogLevel loglevel = asking ? SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
1.269 djm 2240: char *fp, *response;
2241: size_t i;
1.333 djm 2242: struct stat sb;
1.269 djm 2243:
2244: for (i = 0; i < ctx->nkeys; i++) {
1.351 djm 2245: if (!ctx->keys_verified[i])
1.269 djm 2246: continue;
2247: if ((fp = sshkey_fingerprint(ctx->keys[i],
2248: options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1.354 djm 2249: fatal_f("sshkey_fingerprint failed");
1.336 djm 2250: if (first && asking)
1.337 djm 2251: hostkey_change_preamble(loglevel);
1.269 djm 2252: do_log2(loglevel, "Learned new hostkey: %s %s",
2253: sshkey_type(ctx->keys[i]), fp);
1.336 djm 2254: first = 0;
1.269 djm 2255: free(fp);
2256: }
2257: for (i = 0; i < ctx->nold; i++) {
2258: if ((fp = sshkey_fingerprint(ctx->old_keys[i],
2259: options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1.354 djm 2260: fatal_f("sshkey_fingerprint failed");
1.336 djm 2261: if (first && asking)
1.337 djm 2262: hostkey_change_preamble(loglevel);
1.269 djm 2263: do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
2264: sshkey_type(ctx->old_keys[i]), fp);
1.336 djm 2265: first = 0;
1.269 djm 2266: free(fp);
2267: }
2268: if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1.271 djm 2269: if (get_saved_tio() != NULL) {
2270: leave_raw_mode(1);
2271: was_raw = 1;
2272: }
1.269 djm 2273: response = NULL;
2274: for (i = 0; !quit_pending && i < 3; i++) {
2275: free(response);
2276: response = read_passphrase("Accept updated hostkeys? "
2277: "(yes/no): ", RP_ECHO);
1.389 dtucker 2278: if (response != NULL && strcasecmp(response, "yes") == 0)
1.269 djm 2279: break;
2280: else if (quit_pending || response == NULL ||
2281: strcasecmp(response, "no") == 0) {
2282: options.update_hostkeys = 0;
2283: break;
2284: } else {
2285: do_log2(loglevel, "Please enter "
2286: "\"yes\" or \"no\"");
2287: }
2288: }
2289: if (quit_pending || i >= 3 || response == NULL)
2290: options.update_hostkeys = 0;
2291: free(response);
1.271 djm 2292: if (was_raw)
2293: enter_raw_mode(1);
1.269 djm 2294: }
1.333 djm 2295: if (options.update_hostkeys == 0)
2296: return;
1.269 djm 2297: /*
2298: * Now that all the keys are verified, we can go ahead and replace
2299: * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
2300: * cancel the operation).
2301: */
1.333 djm 2302: for (i = 0; i < options.num_user_hostfiles; i++) {
2303: /*
2304: * NB. keys are only added to hostfiles[0], for the rest we
2305: * just delete the hostname entries.
2306: */
2307: if (stat(options.user_hostfiles[i], &sb) != 0) {
2308: if (errno == ENOENT) {
1.354 djm 2309: debug_f("known hosts file %s does not "
2310: "exist", options.user_hostfiles[i]);
1.333 djm 2311: } else {
1.354 djm 2312: error_f("known hosts file %s "
2313: "inaccessible: %s",
2314: options.user_hostfiles[i], strerror(errno));
1.333 djm 2315: }
2316: continue;
2317: }
2318: if ((r = hostfile_replace_entries(options.user_hostfiles[i],
2319: ctx->host_str, ctx->ip_str,
2320: i == 0 ? ctx->keys : NULL, i == 0 ? ctx->nkeys : 0,
2321: options.hash_known_hosts, 0,
2322: options.fingerprint_hash)) != 0) {
1.354 djm 2323: error_fr(r, "hostfile_replace_entries failed for %s",
2324: options.user_hostfiles[i]);
1.333 djm 2325: }
2326: }
1.269 djm 2327: }
2328:
2329: static void
1.381 djm 2330: client_global_hostkeys_prove_confirm(struct ssh *ssh, int type,
1.303 djm 2331: u_int32_t seq, void *_ctx)
1.269 djm 2332: {
2333: struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2334: size_t i, ndone;
2335: struct sshbuf *signdata;
1.375 djm 2336: int r, plaintype;
1.269 djm 2337: const u_char *sig;
1.375 djm 2338: const char *rsa_kexalg = NULL;
2339: char *alg = NULL;
1.269 djm 2340: size_t siglen;
2341:
2342: if (ctx->nnew == 0)
1.354 djm 2343: fatal_f("ctx->nnew == 0"); /* sanity */
1.269 djm 2344: if (type != SSH2_MSG_REQUEST_SUCCESS) {
2345: error("Server failed to confirm ownership of "
2346: "private host keys");
2347: hostkeys_update_ctx_free(ctx);
2348: return;
2349: }
1.375 djm 2350: if (sshkey_type_plain(sshkey_type_from_name(
2351: ssh->kex->hostkey_alg)) == KEY_RSA)
2352: rsa_kexalg = ssh->kex->hostkey_alg;
1.269 djm 2353: if ((signdata = sshbuf_new()) == NULL)
1.354 djm 2354: fatal_f("sshbuf_new failed");
1.269 djm 2355: /*
2356: * Expect a signature for each of the ctx->nnew private keys we
2357: * haven't seen before. They will be in the same order as the
1.351 djm 2358: * ctx->keys where the corresponding ctx->keys_match[i] == 0.
1.269 djm 2359: */
2360: for (ndone = i = 0; i < ctx->nkeys; i++) {
1.351 djm 2361: if (ctx->keys_match[i])
1.269 djm 2362: continue;
1.375 djm 2363: plaintype = sshkey_type_plain(ctx->keys[i]->type);
1.269 djm 2364: /* Prepare data to be signed: session ID, unique string, key */
2365: sshbuf_reset(signdata);
1.270 djm 2366: if ( (r = sshbuf_put_cstring(signdata,
2367: "hostkeys-prove-00@openssh.com")) != 0 ||
1.358 djm 2368: (r = sshbuf_put_stringb(signdata,
2369: ssh->kex->session_id)) != 0 ||
1.269 djm 2370: (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
1.354 djm 2371: fatal_fr(r, "compose signdata");
1.269 djm 2372: /* Extract and verify signature */
2373: if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
1.354 djm 2374: error_fr(r, "parse sig");
1.269 djm 2375: goto out;
2376: }
1.375 djm 2377: if ((r = sshkey_get_sigtype(sig, siglen, &alg)) != 0) {
2378: error_fr(r, "server gave unintelligible signature "
2379: "for %s key %zu", sshkey_type(ctx->keys[i]), i);
2380: goto out;
2381: }
1.309 djm 2382: /*
1.375 djm 2383: * Special case for RSA keys: if a RSA hostkey was negotiated,
2384: * then use its signature type for verification of RSA hostkey
2385: * proofs. Otherwise, accept only RSA-SHA256/512 signatures.
1.309 djm 2386: */
1.375 djm 2387: if (plaintype == KEY_RSA && rsa_kexalg == NULL &&
2388: match_pattern_list(alg, HOSTKEY_PROOF_RSA_ALGS, 0) != 1) {
2389: debug_f("server used untrusted RSA signature algorithm "
2390: "%s for key %zu, disregarding", alg, i);
2391: free(alg);
2392: /* zap the key from the list */
2393: sshkey_free(ctx->keys[i]);
2394: ctx->keys[i] = NULL;
2395: ndone++;
2396: continue;
2397: }
2398: debug3_f("verify %s key %zu using sigalg %s",
2399: sshkey_type(ctx->keys[i]), i, alg);
2400: free(alg);
1.269 djm 2401: if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
1.308 djm 2402: sshbuf_ptr(signdata), sshbuf_len(signdata),
1.375 djm 2403: plaintype == KEY_RSA ? rsa_kexalg : NULL, 0, NULL)) != 0) {
1.361 djm 2404: error_fr(r, "server gave bad signature for %s key %zu",
1.354 djm 2405: sshkey_type(ctx->keys[i]), i);
1.269 djm 2406: goto out;
2407: }
2408: /* Key is good. Mark it as 'seen' */
1.351 djm 2409: ctx->keys_verified[i] = 1;
1.269 djm 2410: ndone++;
2411: }
1.354 djm 2412: /* Shouldn't happen */
1.269 djm 2413: if (ndone != ctx->nnew)
1.354 djm 2414: fatal_f("ndone != ctx->nnew (%zu / %zu)", ndone, ctx->nnew);
1.320 djm 2415: if ((r = sshpkt_get_end(ssh)) != 0) {
1.354 djm 2416: error_f("protocol error");
1.320 djm 2417: goto out;
2418: }
1.269 djm 2419:
2420: /* Make the edits to known_hosts */
2421: update_known_hosts(ctx);
2422: out:
2423: hostkeys_update_ctx_free(ctx);
1.384 djm 2424: hostkeys_update_complete = 1;
2425: client_repledge();
1.269 djm 2426: }
2427:
1.267 djm 2428: /*
1.291 djm 2429: * Returns non-zero if the key is accepted by HostkeyAlgorithms.
2430: * Made slightly less trivial by the multiple RSA signature algorithm names.
2431: */
2432: static int
2433: key_accepted_by_hostkeyalgs(const struct sshkey *key)
2434: {
2435: const char *ktype = sshkey_ssh_name(key);
1.331 dtucker 2436: const char *hostkeyalgs = options.hostkeyalgorithms;
1.291 djm 2437:
1.391 djm 2438: if (key->type == KEY_UNSPEC)
1.291 djm 2439: return 0;
2440: if (key->type == KEY_RSA &&
2441: (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
2442: match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
2443: return 1;
2444: return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
2445: }
2446:
2447: /*
1.270 djm 2448: * Handle hostkeys-00@openssh.com global request to inform the client of all
1.267 djm 2449: * the server's hostkeys. The keys are checked against the user's
2450: * HostkeyAlgorithms preference before they are accepted.
2451: */
2452: static int
1.321 djm 2453: client_input_hostkeys(struct ssh *ssh)
1.267 djm 2454: {
2455: const u_char *blob = NULL;
1.269 djm 2456: size_t i, len = 0;
1.267 djm 2457: struct sshbuf *buf = NULL;
1.269 djm 2458: struct sshkey *key = NULL, **tmp;
1.384 djm 2459: int r, prove_sent = 0;
1.269 djm 2460: char *fp;
1.267 djm 2461: static int hostkeys_seen = 0; /* XXX use struct ssh */
1.268 djm 2462: extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
1.272 djm 2463: struct hostkeys_update_ctx *ctx = NULL;
1.351 djm 2464: u_int want;
1.267 djm 2465:
2466: if (hostkeys_seen)
1.354 djm 2467: fatal_f("server already sent hostkeys");
1.384 djm 2468: if (!can_update_hostkeys())
1.267 djm 2469: return 1;
1.384 djm 2470: hostkeys_seen = 1;
1.272 djm 2471:
2472: ctx = xcalloc(1, sizeof(*ctx));
1.269 djm 2473: while (ssh_packet_remaining(ssh) > 0) {
1.267 djm 2474: sshkey_free(key);
2475: key = NULL;
1.269 djm 2476: if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
1.354 djm 2477: error_fr(r, "parse key");
1.269 djm 2478: goto out;
2479: }
1.270 djm 2480: if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
1.354 djm 2481: do_log2_fr(r, r == SSH_ERR_KEY_TYPE_UNKNOWN ?
1.335 djm 2482: SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_ERROR,
1.354 djm 2483: "convert key");
1.335 djm 2484: continue;
1.270 djm 2485: }
1.267 djm 2486: fp = sshkey_fingerprint(key, options.fingerprint_hash,
2487: SSH_FP_DEFAULT);
1.354 djm 2488: debug3_f("received %s key %s", sshkey_type(key), fp);
1.267 djm 2489: free(fp);
1.275 markus 2490:
1.291 djm 2491: if (!key_accepted_by_hostkeyalgs(key)) {
1.354 djm 2492: debug3_f("%s key not permitted by "
2493: "HostkeyAlgorithms", sshkey_ssh_name(key));
1.267 djm 2494: continue;
2495: }
1.269 djm 2496: /* Skip certs */
2497: if (sshkey_is_cert(key)) {
1.354 djm 2498: debug3_f("%s key is a certificate; skipping",
2499: sshkey_ssh_name(key));
1.269 djm 2500: continue;
2501: }
2502: /* Ensure keys are unique */
2503: for (i = 0; i < ctx->nkeys; i++) {
2504: if (sshkey_equal(key, ctx->keys[i])) {
1.354 djm 2505: error_f("received duplicated %s host key",
2506: sshkey_ssh_name(key));
1.269 djm 2507: goto out;
2508: }
2509: }
2510: /* Key is good, record it */
1.299 deraadt 2511: if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
1.269 djm 2512: sizeof(*ctx->keys))) == NULL)
1.354 djm 2513: fatal_f("recallocarray failed nkeys = %zu",
2514: ctx->nkeys);
1.269 djm 2515: ctx->keys = tmp;
2516: ctx->keys[ctx->nkeys++] = key;
1.267 djm 2517: key = NULL;
2518: }
2519:
1.269 djm 2520: if (ctx->nkeys == 0) {
1.354 djm 2521: debug_f("server sent no hostkeys");
1.267 djm 2522: goto out;
2523: }
1.270 djm 2524:
1.351 djm 2525: if ((ctx->keys_match = calloc(ctx->nkeys,
2526: sizeof(*ctx->keys_match))) == NULL ||
2527: (ctx->keys_verified = calloc(ctx->nkeys,
2528: sizeof(*ctx->keys_verified))) == NULL)
1.354 djm 2529: fatal_f("calloc failed");
1.267 djm 2530:
1.268 djm 2531: get_hostfile_hostname_ipaddr(host,
2532: options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
1.269 djm 2533: options.port, &ctx->host_str,
2534: options.check_host_ip ? &ctx->ip_str : NULL);
1.268 djm 2535:
1.269 djm 2536: /* Find which keys we already know about. */
1.333 djm 2537: for (i = 0; i < options.num_user_hostfiles; i++) {
1.354 djm 2538: debug_f("searching %s for %s / %s",
1.339 dtucker 2539: options.user_hostfiles[i], ctx->host_str,
1.340 dtucker 2540: ctx->ip_str ? ctx->ip_str : "(none)");
1.333 djm 2541: if ((r = hostkeys_foreach(options.user_hostfiles[i],
2542: hostkeys_find, ctx, ctx->host_str, ctx->ip_str,
1.356 djm 2543: HKF_WANT_PARSE_KEY, 0)) != 0) {
1.333 djm 2544: if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
1.354 djm 2545: debug_f("hostkeys file %s does not exist",
2546: options.user_hostfiles[i]);
1.333 djm 2547: continue;
2548: }
1.354 djm 2549: error_fr(r, "hostkeys_foreach failed for %s",
2550: options.user_hostfiles[i]);
1.333 djm 2551: goto out;
2552: }
1.267 djm 2553: }
2554:
1.269 djm 2555: /* Figure out if we have any new keys to add */
1.351 djm 2556: ctx->nnew = ctx->nincomplete = 0;
2557: want = HKF_MATCH_HOST | ( options.check_host_ip ? HKF_MATCH_IP : 0);
1.269 djm 2558: for (i = 0; i < ctx->nkeys; i++) {
1.351 djm 2559: if (ctx->keys_match[i] == 0)
1.269 djm 2560: ctx->nnew++;
1.351 djm 2561: if ((ctx->keys_match[i] & want) != want)
2562: ctx->nincomplete++;
1.269 djm 2563: }
2564:
1.354 djm 2565: debug3_f("%zu server keys: %zu new, %zu retained, "
2566: "%zu incomplete match. %zu to remove", ctx->nkeys, ctx->nnew,
2567: ctx->nkeys - ctx->nnew - ctx->nincomplete,
1.351 djm 2568: ctx->nincomplete, ctx->nold);
1.269 djm 2569:
1.353 djm 2570: if (ctx->nnew == 0 && ctx->nold == 0) {
1.354 djm 2571: debug_f("no new or deprecated keys from server");
1.353 djm 2572: goto out;
2573: }
2574:
2575: /* Various reasons why we cannot proceed with the update */
2576: if (ctx->complex_hostspec) {
1.354 djm 2577: debug_f("CA/revocation marker, manual host list or wildcard "
2578: "host pattern found, skipping UserKnownHostsFile update");
1.353 djm 2579: goto out;
2580: }
2581: if (ctx->other_name_seen) {
1.354 djm 2582: debug_f("host key found matching a different name/address, "
2583: "skipping UserKnownHostsFile update");
1.347 djm 2584: goto out;
1.352 djm 2585: }
2586: /*
2587: * If removing keys, check whether they appear under different
2588: * names/addresses and refuse to proceed if they do. This avoids
2589: * cases such as hosts with multiple names becoming inconsistent
2590: * with regards to CheckHostIP entries.
2591: * XXX UpdateHostkeys=force to override this (and other) checks?
2592: */
2593: if (ctx->nold != 0) {
2594: if (check_old_keys_othernames(ctx) != 0)
2595: goto out; /* error already logged */
2596: if (ctx->old_key_seen) {
1.354 djm 2597: debug_f("key(s) for %s%s%s exist under other names; "
2598: "skipping UserKnownHostsFile update",
1.352 djm 2599: ctx->host_str, ctx->ip_str == NULL ? "" : ",",
2600: ctx->ip_str == NULL ? "" : ctx->ip_str);
2601: goto out;
2602: }
2603: }
2604:
1.353 djm 2605: if (ctx->nnew == 0) {
1.351 djm 2606: /*
2607: * We have some keys to remove or fix matching for.
2608: * We can proceed to do this without requiring a fresh proof
2609: * from the server.
2610: */
1.269 djm 2611: update_known_hosts(ctx);
1.353 djm 2612: goto out;
2613: }
2614: /*
2615: * We have received previously-unseen keys from the server.
2616: * Ask the server to confirm ownership of the private halves.
2617: */
1.354 djm 2618: debug3_f("asking server to prove ownership for %zu keys", ctx->nnew);
1.353 djm 2619: if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2620: (r = sshpkt_put_cstring(ssh,
2621: "hostkeys-prove-00@openssh.com")) != 0 ||
2622: (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
1.354 djm 2623: fatal_fr(r, "prepare hostkeys-prove");
1.353 djm 2624: if ((buf = sshbuf_new()) == NULL)
1.354 djm 2625: fatal_f("sshbuf_new");
1.353 djm 2626: for (i = 0; i < ctx->nkeys; i++) {
2627: if (ctx->keys_match[i])
2628: continue;
2629: sshbuf_reset(buf);
2630: if ((r = sshkey_putb(ctx->keys[i], buf)) != 0 ||
1.354 djm 2631: (r = sshpkt_put_stringb(ssh, buf)) != 0)
2632: fatal_fr(r, "assemble hostkeys-prove");
1.269 djm 2633: }
1.353 djm 2634: if ((r = sshpkt_send(ssh)) != 0)
1.354 djm 2635: fatal_fr(r, "send hostkeys-prove");
1.353 djm 2636: client_register_global_confirm(
1.381 djm 2637: client_global_hostkeys_prove_confirm, ctx);
1.353 djm 2638: ctx = NULL; /* will be freed in callback */
1.384 djm 2639: prove_sent = 1;
1.269 djm 2640:
1.267 djm 2641: /* Success */
2642: out:
1.269 djm 2643: hostkeys_update_ctx_free(ctx);
1.267 djm 2644: sshkey_free(key);
2645: sshbuf_free(buf);
1.384 djm 2646: if (!prove_sent) {
2647: /* UpdateHostkeys handling completed */
2648: hostkeys_update_complete = 1;
2649: client_repledge();
2650: }
1.269 djm 2651: /*
2652: * NB. Return success for all cases. The server doesn't need to know
2653: * what the client does with its hosts file.
2654: */
2655: return 1;
1.267 djm 2656: }
2657:
1.264 markus 2658: static int
1.297 markus 2659: client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
1.95 markus 2660: {
2661: char *rtype;
1.320 djm 2662: u_char want_reply;
2663: int r, success = 0;
1.95 markus 2664:
1.320 djm 2665: if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
2666: (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
2667: goto out;
1.117 markus 2668: debug("client_input_global_request: rtype %s want_reply %d",
2669: rtype, want_reply);
1.270 djm 2670: if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
1.321 djm 2671: success = client_input_hostkeys(ssh);
1.95 markus 2672: if (want_reply) {
1.320 djm 2673: if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS :
2674: SSH2_MSG_REQUEST_FAILURE)) != 0 ||
2675: (r = sshpkt_send(ssh)) != 0 ||
2676: (r = ssh_packet_write_wait(ssh)) != 0)
2677: goto out;
1.95 markus 2678: }
1.320 djm 2679: r = 0;
2680: out:
1.250 djm 2681: free(rtype);
1.320 djm 2682: return r;
1.95 markus 2683: }
1.22 markus 2684:
1.354 djm 2685: static void
2686: client_send_env(struct ssh *ssh, int id, const char *name, const char *val)
2687: {
2688: int r;
2689:
2690: debug("channel %d: setting env %s = \"%s\"", id, name, val);
2691: channel_request_start(ssh, id, "env", 0);
2692: if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
2693: (r = sshpkt_put_cstring(ssh, val)) != 0 ||
2694: (r = sshpkt_send(ssh)) != 0)
2695: fatal_fr(r, "send setenv");
2696: }
2697:
1.123 djm 2698: void
1.303 djm 2699: client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
1.315 markus 2700: const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
2701: char **env)
1.123 djm 2702: {
1.380 djm 2703: size_t i, j, len;
2704: int matched, r;
1.313 djm 2705: char *name, *val;
1.132 djm 2706: Channel *c = NULL;
1.123 djm 2707:
1.354 djm 2708: debug2_f("id %d", id);
1.123 djm 2709:
1.303 djm 2710: if ((c = channel_lookup(ssh, id)) == NULL)
1.354 djm 2711: fatal_f("channel %d: unknown channel", id);
1.224 djm 2712:
1.320 djm 2713: ssh_packet_set_interactive(ssh, want_tty,
1.224 djm 2714: options.ip_qos_interactive, options.ip_qos_bulk);
1.132 djm 2715:
1.123 djm 2716: if (want_tty) {
2717: struct winsize ws;
2718:
2719: /* Store window size in the packet. */
1.326 deraadt 2720: if (ioctl(in_fd, TIOCGWINSZ, &ws) == -1)
1.123 djm 2721: memset(&ws, 0, sizeof(ws));
2722:
1.303 djm 2723: channel_request_start(ssh, id, "pty-req", 1);
2724: client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
1.320 djm 2725: if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : ""))
2726: != 0 ||
2727: (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
2728: (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
2729: (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
2730: (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0)
1.354 djm 2731: fatal_fr(r, "build pty-req");
1.194 djm 2732: if (tiop == NULL)
2733: tiop = get_saved_tio();
1.316 markus 2734: ssh_tty_make_modes(ssh, -1, tiop);
1.320 djm 2735: if ((r = sshpkt_send(ssh)) != 0)
1.354 djm 2736: fatal_fr(r, "send pty-req");
1.123 djm 2737: /* XXX wait for reply */
1.132 djm 2738: c->client_tty = 1;
1.123 djm 2739: }
2740:
2741: /* Transfer any environment variables from client to server */
1.126 djm 2742: if (options.num_send_env != 0 && env != NULL) {
1.123 djm 2743: debug("Sending environment.");
1.126 djm 2744: for (i = 0; env[i] != NULL; i++) {
1.123 djm 2745: /* Split */
1.126 djm 2746: name = xstrdup(env[i]);
1.123 djm 2747: if ((val = strchr(name, '=')) == NULL) {
1.250 djm 2748: free(name);
1.123 djm 2749: continue;
2750: }
2751: *val++ = '\0';
2752:
2753: matched = 0;
2754: for (j = 0; j < options.num_send_env; j++) {
2755: if (match_pattern(name, options.send_env[j])) {
2756: matched = 1;
2757: break;
2758: }
2759: }
2760: if (!matched) {
2761: debug3("Ignored env %s", name);
1.250 djm 2762: free(name);
1.123 djm 2763: continue;
2764: }
1.354 djm 2765: client_send_env(ssh, id, name, val);
1.250 djm 2766: free(name);
1.123 djm 2767: }
1.313 djm 2768: }
2769: for (i = 0; i < options.num_setenv; i++) {
2770: /* Split */
2771: name = xstrdup(options.setenv[i]);
2772: if ((val = strchr(name, '=')) == NULL) {
2773: free(name);
2774: continue;
2775: }
2776: *val++ = '\0';
1.354 djm 2777: client_send_env(ssh, id, name, val);
1.313 djm 2778: free(name);
1.123 djm 2779: }
2780:
1.315 markus 2781: len = sshbuf_len(cmd);
1.123 djm 2782: if (len > 0) {
2783: if (len > 900)
2784: len = 900;
2785: if (want_subsystem) {
1.190 djm 2786: debug("Sending subsystem: %.*s",
1.380 djm 2787: (int)len, (const u_char*)sshbuf_ptr(cmd));
1.303 djm 2788: channel_request_start(ssh, id, "subsystem", 1);
2789: client_expect_confirm(ssh, id, "subsystem",
2790: CONFIRM_CLOSE);
1.123 djm 2791: } else {
1.190 djm 2792: debug("Sending command: %.*s",
1.380 djm 2793: (int)len, (const u_char*)sshbuf_ptr(cmd));
1.303 djm 2794: channel_request_start(ssh, id, "exec", 1);
2795: client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
1.123 djm 2796: }
1.320 djm 2797: if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 ||
2798: (r = sshpkt_send(ssh)) != 0)
1.354 djm 2799: fatal_fr(r, "send command");
1.123 djm 2800: } else {
1.303 djm 2801: channel_request_start(ssh, id, "shell", 1);
2802: client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
1.354 djm 2803: if ((r = sshpkt_send(ssh)) != 0)
2804: fatal_fr(r, "send shell");
1.123 djm 2805: }
1.384 djm 2806:
2807: session_setup_complete = 1;
2808: client_repledge();
1.123 djm 2809: }
2810:
1.77 itojun 2811: static void
1.321 djm 2812: client_init_dispatch(struct ssh *ssh)
1.16 markus 2813: {
1.321 djm 2814: ssh_dispatch_init(ssh, &dispatch_protocol_error);
1.100 markus 2815:
1.321 djm 2816: ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2817: ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2818: ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2819: ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2820: ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2821: ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2822: ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2823: ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2824: ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2825: ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2826: ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2827: ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1.55 markus 2828:
2829: /* rekeying */
1.321 djm 2830: ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.100 markus 2831:
2832: /* global request reply messages */
1.321 djm 2833: ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2834: ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1.232 djm 2835: }
2836:
2837: void
2838: client_stop_mux(void)
2839: {
2840: if (options.control_path != NULL && muxserver_sock != -1)
2841: unlink(options.control_path);
2842: /*
1.247 dtucker 2843: * If we are in persist mode, or don't have a shell, signal that we
2844: * should close when all active channels are closed.
1.232 djm 2845: */
1.366 djm 2846: if (options.control_persist || options.session_type == SESSION_TYPE_NONE) {
1.232 djm 2847: session_closed = 1;
1.235 djm 2848: setproctitle("[stopped mux]");
2849: }
1.113 markus 2850: }
2851:
2852: /* client specific fatal cleanup */
2853: void
1.114 markus 2854: cleanup_exit(int i)
1.113 markus 2855: {
1.233 djm 2856: leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.192 djm 2857: if (options.control_path != NULL && muxserver_sock != -1)
1.123 djm 2858: unlink(options.control_path);
1.223 djm 2859: ssh_kill_proxy_command();
1.114 markus 2860: _exit(i);
1.1 deraadt 2861: }