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