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