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