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