blob: 0648162341f7104a0ac352b4798e8221ccb087b3 [file] [log] [blame]
djm@openbsd.org894221a2017-03-10 05:01:13 +00001/* $OpenBSD: clientloop.c,v 1.291 2017/03/10 05:01:13 djm Exp $ */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002/*
Damien Miller95def091999-11-25 00:26:21 +11003 * Author: Tatu Ylonen <ylo@cs.hut.fi>
Damien Miller95def091999-11-25 00:26:21 +11004 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
Damien Miller95def091999-11-25 00:26:21 +11006 * The main loop for the interactive session (client side).
Damien Miller4af51302000-04-16 11:18:38 +10007 *
Damien Millere4340be2000-09-16 13:29:08 +11008 * 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.
36 *
37 *
Damien Miller1383bd82000-04-06 12:32:37 +100038 * SSH2 support added by Markus Friedl.
Ben Lindstrom44697232001-07-04 03:32:30 +000039 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
Damien Millere4340be2000-09-16 13:29:08 +110040 *
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.
Damien Miller95def091999-11-25 00:26:21 +110060 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100061
62#include "includes.h"
Damien Miller17e91c02006-03-15 11:28:34 +110063
Damien Millerf17883e2006-03-15 11:45:54 +110064#include <sys/types.h>
Damien Miller9aec9192006-08-05 10:57:45 +100065#include <sys/ioctl.h>
Damien Millerf17883e2006-03-15 11:45:54 +110066#ifdef HAVE_SYS_STAT_H
67# include <sys/stat.h>
68#endif
Damien Miller9aec9192006-08-05 10:57:45 +100069#ifdef HAVE_SYS_TIME_H
70# include <sys/time.h>
71#endif
Damien Millere3b60b52006-07-10 21:08:03 +100072#include <sys/socket.h>
Damien Miller99bd21e2006-03-15 11:11:28 +110073
Damien Millerc7b06362006-03-15 11:53:45 +110074#include <ctype.h>
Darren Tucker39972492006-07-12 22:22:46 +100075#include <errno.h>
Damien Miller6645e7a2006-03-15 14:42:54 +110076#ifdef HAVE_PATHS_H
Damien Miller03e20032006-03-15 11:16:59 +110077#include <paths.h>
Damien Miller6645e7a2006-03-15 14:42:54 +110078#endif
Damien Miller6ff3cad2006-03-15 11:52:09 +110079#include <signal.h>
Damien Millerded319c2006-09-01 15:38:36 +100080#include <stdarg.h>
Damien Millera7a73ee2006-08-05 11:37:59 +100081#include <stdio.h>
Damien Millere7a1e5c2006-08-05 11:34:19 +100082#include <stdlib.h>
Damien Millere3476ed2006-07-24 14:13:33 +100083#include <string.h>
Damien Miller99bd21e2006-03-15 11:11:28 +110084#include <termios.h>
Damien Millerd7834352006-08-05 12:39:39 +100085#include <pwd.h>
Damien Millere6b3b612006-07-24 14:01:23 +100086#include <unistd.h>
deraadt@openbsd.org087266e2015-01-20 23:14:00 +000087#include <limits.h>
Damien Millerd4a8b7e1999-10-27 13:42:43 +100088
Damien Millerb84886b2008-05-19 15:05:07 +100089#include "openbsd-compat/sys-queue.h"
Damien Millerd7834352006-08-05 12:39:39 +100090#include "xmalloc.h"
Damien Millerd4a8b7e1999-10-27 13:42:43 +100091#include "ssh.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +000092#include "ssh1.h"
93#include "ssh2.h"
Damien Millerd4a8b7e1999-10-27 13:42:43 +100094#include "packet.h"
95#include "buffer.h"
Damien Millerb38eff82000-04-01 11:09:21 +100096#include "compat.h"
Ben Lindstromc7637672001-06-09 00:36:26 +000097#include "channels.h"
Damien Millerb38eff82000-04-01 11:09:21 +100098#include "dispatch.h"
Damien Miller0bc1bd82000-11-13 22:57:25 +110099#include "key.h"
Damien Millerd7834352006-08-05 12:39:39 +1000100#include "cipher.h"
Ben Lindstromf28f6342001-04-04 02:03:04 +0000101#include "kex.h"
markus@openbsd.org3a1638d2015-07-10 06:21:53 +0000102#include "myproposal.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +0000103#include "log.h"
Damien Miller7acefbb2014-07-18 14:11:24 +1000104#include "misc.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +0000105#include "readconf.h"
Ben Lindstrombf555ba2001-01-18 02:04:35 +0000106#include "clientloop.h"
Damien Milleraeb31d62005-12-13 19:29:36 +1100107#include "sshconnect.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +0000108#include "authfd.h"
109#include "atomicio.h"
Darren Tucker06f2bd82004-05-13 16:06:46 +1000110#include "sshpty.h"
Damien Miller0e220db2004-06-15 10:34:08 +1000111#include "match.h"
112#include "msg.h"
djm@openbsd.org141efe42015-01-14 20:05:27 +0000113#include "ssherr.h"
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000114#include "hostfile.h"
Damien Miller69b69aa2000-10-28 14:19:58 +1100115
116/* import options */
117extern Options options;
118
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000119/* Flag indicating that stdin should be redirected from /dev/null. */
120extern int stdin_null_flag;
121
Damien Millerd6965512003-12-17 16:31:53 +1100122/* Flag indicating that no shell has been requested */
123extern int no_shell_flag;
124
djm@openbsd.org368dd972016-07-23 02:54:08 +0000125/* Flag indicating that ssh should daemonise after authentication is complete */
126extern int fork_after_authentication_flag;
127
Damien Miller0e220db2004-06-15 10:34:08 +1000128/* Control socket */
Damien Millere1537f92010-01-26 13:26:22 +1100129extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
Damien Miller0e220db2004-06-15 10:34:08 +1000130
Damien Miller5428f641999-11-25 11:54:57 +1100131/*
132 * Name of the host we are connecting to. This is the name given on the
133 * command line, or the HostName specified for the user-supplied name in a
134 * configuration file.
135 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000136extern char *host;
137
Damien Miller5428f641999-11-25 11:54:57 +1100138/*
139 * Flag to indicate that we have received a window change signal which has
140 * not yet been processed. This will cause a message indicating the new
141 * window size to be sent to the server a little later. This is volatile
142 * because this is updated in a signal handler.
143 */
Ben Lindstrom5e71c542001-12-06 16:48:14 +0000144static volatile sig_atomic_t received_window_change_signal = 0;
145static volatile sig_atomic_t received_signal = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000146
Damien Miller788f2122005-11-05 15:14:59 +1100147/* Flag indicating whether the user's terminal is in non-blocking mode. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000148static int in_non_blocking_mode = 0;
149
Damien Millere11e1ea2010-08-03 16:04:46 +1000150/* Time when backgrounded control master using ControlPersist should exit */
151static time_t control_persist_exit_time = 0;
152
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000153/* Common data for the client loop code. */
Damien Millere1537f92010-01-26 13:26:22 +1100154volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000155static int escape_char1; /* Escape character. (proto1 only) */
156static int escape_pending1; /* Last character was an escape (proto1 only) */
Damien Miller95def091999-11-25 00:26:21 +1100157static int last_was_cr; /* Last character was a newline. */
Darren Tucker4d5cd332008-06-13 04:51:14 +1000158static int exit_status; /* Used to store the command exit status. */
159static int stdin_eof; /* EOF has been encountered on stderr. */
Damien Miller95def091999-11-25 00:26:21 +1100160static Buffer stdin_buffer; /* Buffer for stdin data. */
161static Buffer stdout_buffer; /* Buffer for stdout data. */
162static Buffer stderr_buffer; /* Buffer for stderr data. */
Damien Miller1ab6a512010-06-26 10:02:24 +1000163static u_int buffer_high; /* Soft max buffer size. */
Damien Miller95def091999-11-25 00:26:21 +1100164static int connection_in; /* Connection to server (input). */
165static int connection_out; /* Connection to server (output). */
Ben Lindstrombe2cc432001-04-04 23:46:07 +0000166static int need_rekeying; /* Set to non-zero if rekeying is requested. */
Damien Miller1ab6a512010-06-26 10:02:24 +1000167static int session_closed; /* In SSH2: login session closed. */
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000168static u_int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000169
Ben Lindstrombba81212001-06-25 05:01:22 +0000170static void client_init_dispatch(void);
Damien Miller1383bd82000-04-06 12:32:37 +1000171int session_ident = -1;
172
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000173/* Track escape per proto2 channel */
174struct escape_filter_ctx {
175 int escape_pending;
176 int escape_char;
177};
178
179/* Context for channel confirmation replies */
Damien Miller5771ed72008-05-19 15:35:33 +1000180struct channel_reply_ctx {
181 const char *request_type;
Damien Miller555f3b82011-05-15 08:48:05 +1000182 int id;
183 enum confirm_action action;
Damien Miller5771ed72008-05-19 15:35:33 +1000184};
185
Darren Tucker9f407c42008-06-13 04:50:27 +1000186/* Global request success/failure callbacks */
187struct global_confirm {
188 TAILQ_ENTRY(global_confirm) entry;
189 global_confirm_cb *cb;
190 void *ctx;
191 int ref_count;
192};
193TAILQ_HEAD(global_confirms, global_confirm);
194static struct global_confirms global_confirms =
195 TAILQ_HEAD_INITIALIZER(global_confirms);
196
Damien Miller0e220db2004-06-15 10:34:08 +1000197void ssh_process_session2_setup(int, int, int, Buffer *);
198
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000199/* Restores stdin to blocking mode. */
200
Ben Lindstrombba81212001-06-25 05:01:22 +0000201static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +0000202leave_non_blocking(void)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000203{
Damien Miller95def091999-11-25 00:26:21 +1100204 if (in_non_blocking_mode) {
Damien Miller03e66f62004-06-15 15:47:51 +1000205 unset_nonblock(fileno(stdin));
Damien Miller95def091999-11-25 00:26:21 +1100206 in_non_blocking_mode = 0;
Damien Miller95def091999-11-25 00:26:21 +1100207 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000208}
209
Damien Miller95def091999-11-25 00:26:21 +1100210/* Puts stdin terminal in non-blocking mode. */
211
Ben Lindstrombba81212001-06-25 05:01:22 +0000212static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +0000213enter_non_blocking(void)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000214{
Damien Miller95def091999-11-25 00:26:21 +1100215 in_non_blocking_mode = 1;
Damien Miller232711f2004-06-15 10:35:30 +1000216 set_nonblock(fileno(stdin));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000217}
218
Damien Miller5428f641999-11-25 11:54:57 +1100219/*
220 * Signal handler for the window change signal (SIGWINCH). This just sets a
221 * flag indicating that the window has changed.
222 */
Damien Millerf0b15df2006-03-26 13:59:20 +1100223/*ARGSUSED */
Ben Lindstrombba81212001-06-25 05:01:22 +0000224static void
Damien Miller95def091999-11-25 00:26:21 +1100225window_change_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000226{
Damien Miller95def091999-11-25 00:26:21 +1100227 received_window_change_signal = 1;
228 signal(SIGWINCH, window_change_handler);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000229}
230
Damien Miller5428f641999-11-25 11:54:57 +1100231/*
232 * Signal handler for signals that cause the program to terminate. These
233 * signals must be trapped to restore terminal modes.
234 */
Damien Millerf0b15df2006-03-26 13:59:20 +1100235/*ARGSUSED */
Ben Lindstrombba81212001-06-25 05:01:22 +0000236static void
Damien Miller95def091999-11-25 00:26:21 +1100237signal_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000238{
Ben Lindstromec46e0b2001-06-09 01:27:31 +0000239 received_signal = sig;
240 quit_pending = 1;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000241}
242
Damien Miller5428f641999-11-25 11:54:57 +1100243/*
244 * Returns current time in seconds from Jan 1, 1970 with the maximum
245 * available resolution.
246 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000247
Ben Lindstrombba81212001-06-25 05:01:22 +0000248static double
Ben Lindstrom31ca54a2001-02-09 02:11:24 +0000249get_current_time(void)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000250{
Damien Miller95def091999-11-25 00:26:21 +1100251 struct timeval tv;
252 gettimeofday(&tv, NULL);
253 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000254}
255
Damien Millere11e1ea2010-08-03 16:04:46 +1000256/*
257 * Sets control_persist_exit_time to the absolute time when the
258 * backgrounded control master should exit due to expiry of the
259 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
260 * control master process, or if there is no ControlPersist timeout.
261 */
262static void
263set_control_persist_exit_time(void)
264{
265 if (muxserver_sock == -1 || !options.control_persist
Damien Miller6c3eec72011-05-05 14:16:22 +1000266 || options.control_persist_timeout == 0) {
Damien Millere11e1ea2010-08-03 16:04:46 +1000267 /* not using a ControlPersist timeout */
268 control_persist_exit_time = 0;
Damien Miller6c3eec72011-05-05 14:16:22 +1000269 } else if (channel_still_open()) {
Damien Millere11e1ea2010-08-03 16:04:46 +1000270 /* some client connections are still open */
271 if (control_persist_exit_time > 0)
272 debug2("%s: cancel scheduled exit", __func__);
273 control_persist_exit_time = 0;
274 } else if (control_persist_exit_time <= 0) {
275 /* a client connection has recently closed */
Darren Tuckerb759c9c2013-06-02 07:46:16 +1000276 control_persist_exit_time = monotime() +
Damien Millere11e1ea2010-08-03 16:04:46 +1000277 (time_t)options.control_persist_timeout;
278 debug2("%s: schedule exit in %d seconds", __func__,
279 options.control_persist_timeout);
280 }
281 /* else we are already counting down to the timeout */
282}
283
Damien Miller8d60be52012-02-11 08:18:17 +1100284#define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
285static int
286client_x11_display_valid(const char *display)
287{
288 size_t i, dlen;
289
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000290 if (display == NULL)
291 return 0;
292
Damien Miller8d60be52012-02-11 08:18:17 +1100293 dlen = strlen(display);
294 for (i = 0; i < dlen; i++) {
Damien Millerfdb23062013-11-21 13:57:15 +1100295 if (!isalnum((u_char)display[i]) &&
Damien Miller8d60be52012-02-11 08:18:17 +1100296 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
297 debug("Invalid character '%c' in DISPLAY", display[i]);
298 return 0;
299 }
300 }
301 return 1;
302}
303
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000304#define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
305#define X11_TIMEOUT_SLACK 60
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000306int
Damien Miller17e7ed02005-06-17 12:54:33 +1000307client_x11_get_proto(const char *display, const char *xauth_path,
Damien Miller1ab6a512010-06-26 10:02:24 +1000308 u_int trusted, u_int timeout, char **_proto, char **_data)
Damien Miller17e7ed02005-06-17 12:54:33 +1000309{
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000310 char cmd[1024], line[512], xdisplay[512];
311 char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
Damien Miller17e7ed02005-06-17 12:54:33 +1000312 static char proto[512], data[512];
313 FILE *f;
tedu@openbsd.org10363562016-09-17 18:00:27 +0000314 int got_data = 0, generated = 0, do_unlink = 0, r;
Damien Miller17e7ed02005-06-17 12:54:33 +1000315 struct stat st;
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000316 u_int now, x11_timeout_real;
Damien Miller17e7ed02005-06-17 12:54:33 +1000317
Damien Miller17e7ed02005-06-17 12:54:33 +1000318 *_proto = proto;
319 *_data = data;
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000320 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
Damien Miller17e7ed02005-06-17 12:54:33 +1000321
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000322 if (!client_x11_display_valid(display)) {
millert@openbsd.org5658ef22016-02-01 21:18:17 +0000323 if (display != NULL)
324 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
325 display);
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000326 return -1;
327 }
328 if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
329 debug("No xauth program.");
330 xauth_path = NULL;
331 }
332
333 if (xauth_path != NULL) {
Damien Miller17e7ed02005-06-17 12:54:33 +1000334 /*
335 * Handle FamilyLocal case where $DISPLAY does
336 * not match an authorization entry. For this we
337 * just try "xauth list unix:displaynum.screennum".
338 * XXX: "localhost" match to determine FamilyLocal
339 * is not perfect.
340 */
341 if (strncmp(display, "localhost:", 10) == 0) {
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000342 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
343 display + 10)) < 0 ||
344 (size_t)r >= sizeof(xdisplay)) {
345 error("%s: display name too long", __func__);
346 return -1;
347 }
Damien Miller17e7ed02005-06-17 12:54:33 +1000348 display = xdisplay;
349 }
350 if (trusted == 0) {
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000351 /*
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000352 * Generate an untrusted X11 auth cookie.
353 *
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000354 * The authentication cookie should briefly outlive
355 * ssh's willingness to forward X11 connections to
356 * avoid nasty fail-open behaviour in the X server.
357 */
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000358 mktemp_proto(xauthdir, sizeof(xauthdir));
359 if (mkdtemp(xauthdir) == NULL) {
360 error("%s: mkdtemp: %s",
361 __func__, strerror(errno));
362 return -1;
363 }
364 do_unlink = 1;
365 if ((r = snprintf(xauthfile, sizeof(xauthfile),
366 "%s/xauthfile", xauthdir)) < 0 ||
367 (size_t)r >= sizeof(xauthfile)) {
368 error("%s: xauthfile path too long", __func__);
369 unlink(xauthfile);
370 rmdir(xauthdir);
371 return -1;
372 }
373
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000374 if (timeout >= UINT_MAX - X11_TIMEOUT_SLACK)
375 x11_timeout_real = UINT_MAX;
376 else
377 x11_timeout_real = timeout + X11_TIMEOUT_SLACK;
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000378 if ((r = snprintf(cmd, sizeof(cmd),
379 "%s -f %s generate %s " SSH_X11_PROTO
380 " untrusted timeout %u 2>" _PATH_DEVNULL,
381 xauth_path, xauthfile, display,
382 x11_timeout_real)) < 0 ||
383 (size_t)r >= sizeof(cmd))
384 fatal("%s: cmd too long", __func__);
385 debug2("%s: %s", __func__, cmd);
386 if (x11_refuse_time == 0) {
387 now = monotime() + 1;
388 if (UINT_MAX - timeout < now)
389 x11_refuse_time = UINT_MAX;
390 else
391 x11_refuse_time = now + timeout;
392 channel_set_x11_refuse_time(x11_refuse_time);
Damien Miller17e7ed02005-06-17 12:54:33 +1000393 }
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000394 if (system(cmd) == 0)
395 generated = 1;
Damien Miller17e7ed02005-06-17 12:54:33 +1000396 }
Darren Tucker513d13a2007-08-15 19:13:41 +1000397
398 /*
399 * When in untrusted mode, we read the cookie only if it was
400 * successfully generated as an untrusted one in the step
401 * above.
402 */
403 if (trusted || generated) {
404 snprintf(cmd, sizeof(cmd),
405 "%s %s%s list %s 2>" _PATH_DEVNULL,
406 xauth_path,
407 generated ? "-f " : "" ,
408 generated ? xauthfile : "",
409 display);
410 debug2("x11_get_proto: %s", cmd);
411 f = popen(cmd, "r");
412 if (f && fgets(line, sizeof(line), f) &&
413 sscanf(line, "%*s %511s %511s", proto, data) == 2)
414 got_data = 1;
415 if (f)
416 pclose(f);
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000417 }
Damien Miller17e7ed02005-06-17 12:54:33 +1000418 }
419
420 if (do_unlink) {
421 unlink(xauthfile);
422 rmdir(xauthdir);
423 }
Damien Miller17e7ed02005-06-17 12:54:33 +1000424
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000425 /* Don't fall back to fake X11 data for untrusted forwarding */
426 if (!trusted && !got_data) {
427 error("Warning: untrusted X11 forwarding setup failed: "
428 "xauth key data not generated");
429 return -1;
430 }
431
Damien Miller17e7ed02005-06-17 12:54:33 +1000432 /*
433 * If we didn't get authentication data, just make up some
434 * data. The forwarding code will check the validity of the
435 * response anyway, and substitute this data. The X11
436 * server, however, will ignore this fake data and use
437 * whatever authentication mechanisms it was using otherwise
438 * for the local connection.
439 */
440 if (!got_data) {
tedu@openbsd.org10363562016-09-17 18:00:27 +0000441 u_int8_t rnd[16];
442 u_int i;
Damien Miller17e7ed02005-06-17 12:54:33 +1000443
444 logit("Warning: No xauth data; "
445 "using fake authentication data for X11 forwarding.");
446 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
tedu@openbsd.org10363562016-09-17 18:00:27 +0000447 arc4random_buf(rnd, sizeof(rnd));
448 for (i = 0; i < sizeof(rnd); i++) {
Damien Miller17e7ed02005-06-17 12:54:33 +1000449 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
tedu@openbsd.org10363562016-09-17 18:00:27 +0000450 rnd[i]);
Damien Miller17e7ed02005-06-17 12:54:33 +1000451 }
452 }
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000453
454 return 0;
Damien Miller17e7ed02005-06-17 12:54:33 +1000455}
456
Damien Miller5428f641999-11-25 11:54:57 +1100457/*
458 * This is called when the interactive is entered. This checks if there is
459 * an EOF coming on stdin. We must check this explicitly, as select() does
460 * not appear to wake up when redirecting from /dev/null.
461 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000462
Ben Lindstrombba81212001-06-25 05:01:22 +0000463static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +0000464client_check_initial_eof_on_stdin(void)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000465{
Damien Miller95def091999-11-25 00:26:21 +1100466 int len;
467 char buf[1];
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000468
Damien Miller5428f641999-11-25 11:54:57 +1100469 /*
470 * If standard input is to be "redirected from /dev/null", we simply
471 * mark that we have seen an EOF and send an EOF message to the
472 * server. Otherwise, we try to read a single character; it appears
473 * that for some files, such /dev/null, select() never wakes up for
474 * read for this descriptor, which means that we never get EOF. This
475 * way we will get the EOF if stdin comes from /dev/null or similar.
476 */
Damien Miller95def091999-11-25 00:26:21 +1100477 if (stdin_null_flag) {
478 /* Fake EOF on stdin. */
479 debug("Sending eof.");
480 stdin_eof = 1;
481 packet_start(SSH_CMSG_EOF);
482 packet_send();
483 } else {
Damien Miller95def091999-11-25 00:26:21 +1100484 enter_non_blocking();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000485
Damien Miller95def091999-11-25 00:26:21 +1100486 /* Check for immediate EOF on stdin. */
487 len = read(fileno(stdin), buf, 1);
488 if (len == 0) {
Darren Tucker4d5cd332008-06-13 04:51:14 +1000489 /*
490 * EOF. Record that we have seen it and send
491 * EOF to server.
492 */
Damien Miller95def091999-11-25 00:26:21 +1100493 debug("Sending eof.");
494 stdin_eof = 1;
495 packet_start(SSH_CMSG_EOF);
496 packet_send();
497 } else if (len > 0) {
Damien Miller5428f641999-11-25 11:54:57 +1100498 /*
499 * Got data. We must store the data in the buffer,
500 * and also process it as an escape character if
501 * appropriate.
502 */
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000503 if ((u_char) buf[0] == escape_char1)
504 escape_pending1 = 1;
Ben Lindstrome9613cf2001-03-05 06:14:02 +0000505 else
Damien Miller95def091999-11-25 00:26:21 +1100506 buffer_append(&stdin_buffer, buf, 1);
Damien Miller95def091999-11-25 00:26:21 +1100507 }
Damien Miller95def091999-11-25 00:26:21 +1100508 leave_non_blocking();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000509 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000510}
511
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000512
Damien Miller5428f641999-11-25 11:54:57 +1100513/*
514 * Make packets from buffered stdin data, and buffer them for sending to the
515 * connection.
516 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000517
Ben Lindstrombba81212001-06-25 05:01:22 +0000518static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +0000519client_make_packets_from_stdin_data(void)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000520{
Ben Lindstrom46c16222000-12-22 01:43:59 +0000521 u_int len;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000522
Damien Miller95def091999-11-25 00:26:21 +1100523 /* Send buffered stdin data to the server. */
524 while (buffer_len(&stdin_buffer) > 0 &&
Damien Miller9f0f5c62001-12-21 14:45:46 +1100525 packet_not_very_much_data_to_write()) {
Damien Miller95def091999-11-25 00:26:21 +1100526 len = buffer_len(&stdin_buffer);
527 /* Keep the packets at reasonable size. */
528 if (len > packet_get_maxsize())
529 len = packet_get_maxsize();
530 packet_start(SSH_CMSG_STDIN_DATA);
531 packet_put_string(buffer_ptr(&stdin_buffer), len);
532 packet_send();
533 buffer_consume(&stdin_buffer, len);
534 /* If we have a pending EOF, send it now. */
535 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
536 packet_start(SSH_CMSG_EOF);
537 packet_send();
538 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000539 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000540}
541
Damien Miller5428f641999-11-25 11:54:57 +1100542/*
543 * Checks if the client window has changed, and sends a packet about it to
544 * the server if so. The actual change is detected elsewhere (by a software
545 * interrupt on Unix); this just checks the flag and sends a message if
546 * appropriate.
547 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000548
Ben Lindstrombba81212001-06-25 05:01:22 +0000549static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +0000550client_check_window_change(void)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000551{
Damien Miller1383bd82000-04-06 12:32:37 +1000552 struct winsize ws;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000553
Damien Miller1383bd82000-04-06 12:32:37 +1000554 if (! received_window_change_signal)
555 return;
556 /** XXX race */
557 received_window_change_signal = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000558
Damien Millerd3444942000-09-30 14:20:03 +1100559 debug2("client_check_window_change: changed");
Damien Miller1383bd82000-04-06 12:32:37 +1000560
561 if (compat20) {
Damien Miller0e220db2004-06-15 10:34:08 +1000562 channel_send_window_changes();
Damien Miller1383bd82000-04-06 12:32:37 +1000563 } else {
Damien Miller0e220db2004-06-15 10:34:08 +1000564 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
565 return;
Damien Miller1383bd82000-04-06 12:32:37 +1000566 packet_start(SSH_CMSG_WINDOW_SIZE);
Damien Miller71a73672006-03-26 14:04:36 +1100567 packet_put_int((u_int)ws.ws_row);
568 packet_put_int((u_int)ws.ws_col);
569 packet_put_int((u_int)ws.ws_xpixel);
570 packet_put_int((u_int)ws.ws_ypixel);
Damien Miller1383bd82000-04-06 12:32:37 +1000571 packet_send();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000572 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000573}
574
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +0000575static int
Damien Miller509b0102003-12-17 16:33:10 +1100576client_global_request_reply(int type, u_int32_t seq, void *ctxt)
577{
Darren Tucker9f407c42008-06-13 04:50:27 +1000578 struct global_confirm *gc;
579
580 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +0000581 return 0;
Darren Tucker9f407c42008-06-13 04:50:27 +1000582 if (gc->cb != NULL)
583 gc->cb(type, seq, gc->ctx);
584 if (--gc->ref_count <= 0) {
585 TAILQ_REMOVE(&global_confirms, gc, entry);
Damien Miller1d2c4562014-02-04 11:18:20 +1100586 explicit_bzero(gc, sizeof(*gc));
Darren Tuckera627d422013-06-02 07:31:17 +1000587 free(gc);
Darren Tucker9f407c42008-06-13 04:50:27 +1000588 }
589
Darren Tuckerf7288d72009-06-21 18:12:20 +1000590 packet_set_alive_timeouts(0);
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +0000591 return 0;
Damien Miller509b0102003-12-17 16:33:10 +1100592}
593
594static void
595server_alive_check(void)
596{
Darren Tuckerf7288d72009-06-21 18:12:20 +1000597 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
Damien Millerb73b6fd2011-01-11 17:18:56 +1100598 logit("Timeout, server %s not responding.", host);
Damien Miller985a4482006-10-24 03:02:41 +1000599 cleanup_exit(255);
600 }
Damien Miller509b0102003-12-17 16:33:10 +1100601 packet_start(SSH2_MSG_GLOBAL_REQUEST);
602 packet_put_cstring("keepalive@openssh.com");
603 packet_put_char(1); /* boolean: want reply */
604 packet_send();
Darren Tucker9f407c42008-06-13 04:50:27 +1000605 /* Insert an empty placeholder to maintain ordering */
606 client_register_global_confirm(NULL, NULL);
Damien Miller509b0102003-12-17 16:33:10 +1100607}
608
Damien Miller5428f641999-11-25 11:54:57 +1100609/*
610 * Waits until the client can do something (some data becomes available on
611 * one of the file descriptors).
612 */
Ben Lindstrombba81212001-06-25 05:01:22 +0000613static void
Damien Miller5e953212001-01-30 09:14:00 +1100614client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
Darren Tuckerc7a6fc42004-08-13 21:18:00 +1000615 int *maxfdp, u_int *nallocp, int rekeying)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000616{
Damien Miller509b0102003-12-17 16:33:10 +1100617 struct timeval tv, *tvp;
Damien Millere11e1ea2010-08-03 16:04:46 +1000618 int timeout_secs;
Darren Tuckerb759c9c2013-06-02 07:46:16 +1000619 time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
Damien Miller509b0102003-12-17 16:33:10 +1100620 int ret;
621
Damien Miller5e953212001-01-30 09:14:00 +1100622 /* Add any selections by the channel mechanism. */
Damien Millera6508752012-04-22 11:21:10 +1000623 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
624 &minwait_secs, rekeying);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000625
Damien Miller1383bd82000-04-06 12:32:37 +1000626 if (!compat20) {
627 /* Read from the connection, unless our buffers are full. */
628 if (buffer_len(&stdout_buffer) < buffer_high &&
629 buffer_len(&stderr_buffer) < buffer_high &&
630 channel_not_very_much_buffered_data())
Damien Miller5e953212001-01-30 09:14:00 +1100631 FD_SET(connection_in, *readsetp);
Damien Miller1383bd82000-04-06 12:32:37 +1000632 /*
633 * Read from stdin, unless we have seen EOF or have very much
634 * buffered data to send to the server.
635 */
636 if (!stdin_eof && packet_not_very_much_data_to_write())
Damien Miller5e953212001-01-30 09:14:00 +1100637 FD_SET(fileno(stdin), *readsetp);
Damien Miller1383bd82000-04-06 12:32:37 +1000638
639 /* Select stdout/stderr if have data in buffer. */
640 if (buffer_len(&stdout_buffer) > 0)
Damien Miller5e953212001-01-30 09:14:00 +1100641 FD_SET(fileno(stdout), *writesetp);
Damien Miller1383bd82000-04-06 12:32:37 +1000642 if (buffer_len(&stderr_buffer) > 0)
Damien Miller5e953212001-01-30 09:14:00 +1100643 FD_SET(fileno(stderr), *writesetp);
Damien Miller1383bd82000-04-06 12:32:37 +1000644 } else {
Ben Lindstromc8b3f472001-05-17 03:19:40 +0000645 /* channel_prepare_select could have closed the last channel */
Damien Miller164a7f42001-10-12 11:36:09 +1000646 if (session_closed && !channel_still_open() &&
647 !packet_have_data_to_write()) {
648 /* clear mask since we did not call select() */
Damien Miller79faeff2001-11-12 11:06:32 +1100649 memset(*readsetp, 0, *nallocp);
650 memset(*writesetp, 0, *nallocp);
Damien Miller164a7f42001-10-12 11:36:09 +1000651 return;
Ben Lindstromc8b3f472001-05-17 03:19:40 +0000652 } else {
653 FD_SET(connection_in, *readsetp);
654 }
Damien Miller1383bd82000-04-06 12:32:37 +1000655 }
656
Damien Miller95def091999-11-25 00:26:21 +1100657 /* Select server connection if have data to write to the server. */
658 if (packet_have_data_to_write())
Damien Miller5e953212001-01-30 09:14:00 +1100659 FD_SET(connection_out, *writesetp);
Damien Miller95def091999-11-25 00:26:21 +1100660
Damien Miller5428f641999-11-25 11:54:57 +1100661 /*
662 * Wait for something to happen. This will suspend the process until
663 * some selected descriptor can be read, written, or has some other
Damien Millere11e1ea2010-08-03 16:04:46 +1000664 * event pending, or a timeout expires.
Damien Miller5428f641999-11-25 11:54:57 +1100665 */
Damien Miller95def091999-11-25 00:26:21 +1100666
Damien Millere11e1ea2010-08-03 16:04:46 +1000667 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
Darren Tuckerc53c2af2013-05-16 20:28:16 +1000668 if (options.server_alive_interval > 0 && compat20) {
Damien Millere11e1ea2010-08-03 16:04:46 +1000669 timeout_secs = options.server_alive_interval;
Darren Tuckerc53c2af2013-05-16 20:28:16 +1000670 server_alive_time = now + options.server_alive_interval;
671 }
672 if (options.rekey_interval > 0 && compat20 && !rekeying)
deraadt@openbsd.org9136ec12016-09-12 01:22:38 +0000673 timeout_secs = MINIMUM(timeout_secs, packet_get_rekey_timeout());
Damien Millere11e1ea2010-08-03 16:04:46 +1000674 set_control_persist_exit_time();
675 if (control_persist_exit_time > 0) {
deraadt@openbsd.org9136ec12016-09-12 01:22:38 +0000676 timeout_secs = MINIMUM(timeout_secs,
Darren Tuckerc53c2af2013-05-16 20:28:16 +1000677 control_persist_exit_time - now);
Damien Millere11e1ea2010-08-03 16:04:46 +1000678 if (timeout_secs < 0)
679 timeout_secs = 0;
680 }
Damien Millera6508752012-04-22 11:21:10 +1000681 if (minwait_secs != 0)
deraadt@openbsd.org9136ec12016-09-12 01:22:38 +0000682 timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs);
Damien Millere11e1ea2010-08-03 16:04:46 +1000683 if (timeout_secs == INT_MAX)
Damien Miller509b0102003-12-17 16:33:10 +1100684 tvp = NULL;
Darren Tuckerfc959702004-07-17 16:12:08 +1000685 else {
Damien Millere11e1ea2010-08-03 16:04:46 +1000686 tv.tv_sec = timeout_secs;
Damien Miller509b0102003-12-17 16:33:10 +1100687 tv.tv_usec = 0;
688 tvp = &tv;
689 }
Damien Millere11e1ea2010-08-03 16:04:46 +1000690
Damien Miller509b0102003-12-17 16:33:10 +1100691 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
692 if (ret < 0) {
Damien Miller95def091999-11-25 00:26:21 +1100693 char buf[100];
Ben Lindstromf9452512001-02-15 03:12:08 +0000694
695 /*
696 * We have to clear the select masks, because we return.
697 * We have to return, because the mainloop checks for the flags
698 * set by the signal handlers.
699 */
Damien Miller79faeff2001-11-12 11:06:32 +1100700 memset(*readsetp, 0, *nallocp);
701 memset(*writesetp, 0, *nallocp);
Ben Lindstromf9452512001-02-15 03:12:08 +0000702
Damien Miller95def091999-11-25 00:26:21 +1100703 if (errno == EINTR)
704 return;
705 /* Note: we might still have data in the buffers. */
706 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
707 buffer_append(&stderr_buffer, buf, strlen(buf));
Damien Miller95def091999-11-25 00:26:21 +1100708 quit_pending = 1;
Darren Tuckerc53c2af2013-05-16 20:28:16 +1000709 } else if (ret == 0) {
710 /*
711 * Timeout. Could have been either keepalive or rekeying.
712 * Keepalive we check here, rekeying is checked in clientloop.
713 */
Darren Tuckerb759c9c2013-06-02 07:46:16 +1000714 if (server_alive_time != 0 && server_alive_time <= monotime())
Darren Tuckerc53c2af2013-05-16 20:28:16 +1000715 server_alive_check();
716 }
717
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000718}
719
Ben Lindstrombba81212001-06-25 05:01:22 +0000720static void
Damien Millerad833b32000-08-23 10:46:23 +1000721client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000722{
Damien Miller95def091999-11-25 00:26:21 +1100723 /* Flush stdout and stderr buffers. */
Damien Millerad833b32000-08-23 10:46:23 +1000724 if (buffer_len(bout) > 0)
Darren Tucker4d5cd332008-06-13 04:51:14 +1000725 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
726 buffer_len(bout));
Damien Millerad833b32000-08-23 10:46:23 +1000727 if (buffer_len(berr) > 0)
Darren Tucker4d5cd332008-06-13 04:51:14 +1000728 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
729 buffer_len(berr));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000730
Damien Miller21771e22011-05-15 08:45:50 +1000731 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000732
Damien Miller5428f641999-11-25 11:54:57 +1100733 /*
734 * Free (and clear) the buffer to reduce the amount of data that gets
735 * written to swap.
736 */
Damien Millerad833b32000-08-23 10:46:23 +1000737 buffer_free(bin);
738 buffer_free(bout);
739 buffer_free(berr);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000740
Damien Miller95def091999-11-25 00:26:21 +1100741 /* Send the suspend signal to the program itself. */
742 kill(getpid(), SIGTSTP);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000743
Darren Tucker5d78de62004-11-05 20:35:44 +1100744 /* Reset window sizes in case they have changed */
745 received_window_change_signal = 1;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000746
Damien Miller95def091999-11-25 00:26:21 +1100747 /* OK, we have been continued by the user. Reinitialize buffers. */
Damien Millerad833b32000-08-23 10:46:23 +1000748 buffer_init(bin);
749 buffer_init(bout);
750 buffer_init(berr);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000751
Damien Miller21771e22011-05-15 08:45:50 +1000752 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000753}
754
Ben Lindstrombba81212001-06-25 05:01:22 +0000755static void
Damien Miller90fdfaf2006-03-26 14:25:37 +1100756client_process_net_input(fd_set *readset)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000757{
markus@openbsd.orga3068632016-01-14 16:17:39 +0000758 int len;
Darren Tucker86e30a02009-08-28 11:21:06 +1000759 char buf[SSH_IOBUFSZ];
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000760
Damien Miller5428f641999-11-25 11:54:57 +1100761 /*
762 * Read input from the server, and add any such data to the buffer of
763 * the packet subsystem.
764 */
Damien Miller95def091999-11-25 00:26:21 +1100765 if (FD_ISSET(connection_in, readset)) {
766 /* Read as much as possible. */
markus@openbsd.orga3068632016-01-14 16:17:39 +0000767 len = read(connection_in, buf, sizeof(buf));
768 if (len == 0) {
Darren Tucker4d5cd332008-06-13 04:51:14 +1000769 /*
770 * Received EOF. The remote host has closed the
771 * connection.
772 */
773 snprintf(buf, sizeof buf,
774 "Connection to %.300s closed by remote host.\r\n",
775 host);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000776 buffer_append(&stderr_buffer, buf, strlen(buf));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000777 quit_pending = 1;
778 return;
Damien Miller95def091999-11-25 00:26:21 +1100779 }
Damien Miller5428f641999-11-25 11:54:57 +1100780 /*
781 * There is a kernel bug on Solaris that causes select to
782 * sometimes wake up even though there is no data available.
783 */
Damien Millerd8968ad2008-07-04 23:10:49 +1000784 if (len < 0 &&
785 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
Damien Miller95def091999-11-25 00:26:21 +1100786 len = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000787
Damien Miller95def091999-11-25 00:26:21 +1100788 if (len < 0) {
Darren Tucker4d5cd332008-06-13 04:51:14 +1000789 /*
790 * An error has encountered. Perhaps there is a
791 * network problem.
792 */
793 snprintf(buf, sizeof buf,
794 "Read from remote host %.300s: %.100s\r\n",
795 host, strerror(errno));
Damien Miller95def091999-11-25 00:26:21 +1100796 buffer_append(&stderr_buffer, buf, strlen(buf));
Damien Miller95def091999-11-25 00:26:21 +1100797 quit_pending = 1;
798 return;
799 }
800 packet_process_incoming(buf, len);
801 }
Damien Miller1383bd82000-04-06 12:32:37 +1000802}
803
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000804static void
Damien Miller5771ed72008-05-19 15:35:33 +1000805client_status_confirm(int type, Channel *c, void *ctx)
Damien Miller0e220db2004-06-15 10:34:08 +1000806{
Damien Miller5771ed72008-05-19 15:35:33 +1000807 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
808 char errmsg[256];
809 int tochan;
Darren Tuckerfc959702004-07-17 16:12:08 +1000810
Damien Miller555f3b82011-05-15 08:48:05 +1000811 /*
812 * If a TTY was explicitly requested, then a failure to allocate
813 * one is fatal.
814 */
815 if (cr->action == CONFIRM_TTY &&
816 (options.request_tty == REQUEST_TTY_FORCE ||
817 options.request_tty == REQUEST_TTY_YES))
818 cr->action = CONFIRM_CLOSE;
819
Damien Miller5771ed72008-05-19 15:35:33 +1000820 /* XXX supress on mux _client_ quietmode */
821 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
Damien Millere1537f92010-01-26 13:26:22 +1100822 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
Damien Miller0e220db2004-06-15 10:34:08 +1000823
Damien Miller5771ed72008-05-19 15:35:33 +1000824 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
825 debug2("%s request accepted on channel %d",
826 cr->request_type, c->self);
827 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
828 if (tochan) {
829 snprintf(errmsg, sizeof(errmsg),
830 "%s request failed\r\n", cr->request_type);
831 } else {
832 snprintf(errmsg, sizeof(errmsg),
833 "%s request failed on channel %d",
834 cr->request_type, c->self);
835 }
836 /* If error occurred on primary session channel, then exit */
Damien Miller555f3b82011-05-15 08:48:05 +1000837 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
Damien Miller5771ed72008-05-19 15:35:33 +1000838 fatal("%s", errmsg);
Damien Miller555f3b82011-05-15 08:48:05 +1000839 /*
840 * If error occurred on mux client, append to
841 * their stderr.
842 */
843 if (tochan) {
844 buffer_append(&c->extended, errmsg,
845 strlen(errmsg));
846 } else
Damien Miller5771ed72008-05-19 15:35:33 +1000847 error("%s", errmsg);
Damien Miller555f3b82011-05-15 08:48:05 +1000848 if (cr->action == CONFIRM_TTY) {
849 /*
850 * If a TTY allocation error occurred, then arrange
851 * for the correct TTY to leave raw mode.
852 */
853 if (c->self == session_ident)
854 leave_raw_mode(0);
855 else
856 mux_tty_alloc_failed(c);
857 } else if (cr->action == CONFIRM_CLOSE) {
Damien Miller5771ed72008-05-19 15:35:33 +1000858 chan_read_failed(c);
859 chan_write_failed(c);
860 }
Damien Miller0e220db2004-06-15 10:34:08 +1000861 }
Darren Tuckera627d422013-06-02 07:31:17 +1000862 free(cr);
Damien Miller5771ed72008-05-19 15:35:33 +1000863}
Damien Miller0e220db2004-06-15 10:34:08 +1000864
Damien Miller5771ed72008-05-19 15:35:33 +1000865static void
866client_abandon_status_confirm(Channel *c, void *ctx)
867{
Darren Tuckera627d422013-06-02 07:31:17 +1000868 free(ctx);
Damien Miller5771ed72008-05-19 15:35:33 +1000869}
870
Damien Miller6d7b4372011-06-23 08:31:57 +1000871void
Damien Miller555f3b82011-05-15 08:48:05 +1000872client_expect_confirm(int id, const char *request,
873 enum confirm_action action)
Damien Miller5771ed72008-05-19 15:35:33 +1000874{
Damien Miller6c81fee2013-11-08 12:19:55 +1100875 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
Damien Miller5771ed72008-05-19 15:35:33 +1000876
877 cr->request_type = request;
Damien Miller555f3b82011-05-15 08:48:05 +1000878 cr->action = action;
Damien Miller5771ed72008-05-19 15:35:33 +1000879
880 channel_register_status_confirm(id, client_status_confirm,
881 client_abandon_status_confirm, cr);
Damien Miller0e220db2004-06-15 10:34:08 +1000882}
883
Darren Tucker9f407c42008-06-13 04:50:27 +1000884void
885client_register_global_confirm(global_confirm_cb *cb, void *ctx)
886{
Damien Millerb9d3bee2008-07-16 22:40:52 +1000887 struct global_confirm *gc, *last_gc;
Darren Tucker9f407c42008-06-13 04:50:27 +1000888
889 /* Coalesce identical callbacks */
Damien Millerb9d3bee2008-07-16 22:40:52 +1000890 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
891 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
892 if (++last_gc->ref_count >= INT_MAX)
893 fatal("%s: last_gc->ref_count = %d",
894 __func__, last_gc->ref_count);
Darren Tucker9f407c42008-06-13 04:50:27 +1000895 return;
896 }
897
Damien Miller6c81fee2013-11-08 12:19:55 +1100898 gc = xcalloc(1, sizeof(*gc));
Darren Tucker9f407c42008-06-13 04:50:27 +1000899 gc->cb = cb;
900 gc->ctx = ctx;
901 gc->ref_count = 1;
902 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
903}
904
Damien Miller0e220db2004-06-15 10:34:08 +1000905static void
Ben Lindstrom681d9322002-03-22 03:53:00 +0000906process_cmdline(void)
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000907{
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000908 void (*handler)(int);
Damien Miller7acefbb2014-07-18 14:11:24 +1000909 char *s, *cmd;
910 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
911 struct Forward fwd;
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000912
Damien Miller1d2c4562014-02-04 11:18:20 +1100913 memset(&fwd, 0, sizeof(fwd));
Darren Tucker23ae8ca2007-12-02 23:12:30 +1100914
Damien Miller21771e22011-05-15 08:45:50 +1000915 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Ben Lindstrom5a6abda2002-06-09 19:41:48 +0000916 handler = signal(SIGINT, SIG_IGN);
Ben Lindstrom681d9322002-03-22 03:53:00 +0000917 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000918 if (s == NULL)
919 goto out;
Damien Millerfdb23062013-11-21 13:57:15 +1100920 while (isspace((u_char)*s))
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000921 s++;
Darren Tuckere7066df2004-05-24 10:18:05 +1000922 if (*s == '-')
923 s++; /* Skip cmdline '-', if any */
Darren Tuckere1675822004-05-24 10:13:07 +1000924 if (*s == '\0')
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000925 goto out;
Darren Tuckere7066df2004-05-24 10:18:05 +1000926
Darren Tucker1973c882004-05-24 10:34:36 +1000927 if (*s == 'h' || *s == 'H' || *s == '?') {
Darren Tuckere7066df2004-05-24 10:18:05 +1000928 logit("Commands:");
Damien Miller43020952006-07-10 20:16:12 +1000929 logit(" -L[bind_address:]port:host:hostport "
930 "Request local forward");
931 logit(" -R[bind_address:]port:host:hostport "
932 "Request remote forward");
Damien Miller0164cb82008-11-05 16:30:31 +1100933 logit(" -D[bind_address:]port "
934 "Request dynamic forward");
Damien Millerff773642011-09-22 21:39:48 +1000935 logit(" -KL[bind_address:]port "
936 "Cancel local forward");
Damien Miller57e8ad32006-07-10 20:20:52 +1000937 logit(" -KR[bind_address:]port "
Damien Miller43020952006-07-10 20:16:12 +1000938 "Cancel remote forward");
Damien Millerff773642011-09-22 21:39:48 +1000939 logit(" -KD[bind_address:]port "
940 "Cancel dynamic forward");
Damien Millerd27b9472005-12-13 19:29:02 +1100941 if (!options.permit_local_command)
942 goto out;
Damien Miller43020952006-07-10 20:16:12 +1000943 logit(" !args "
944 "Execute local command");
Damien Millerd27b9472005-12-13 19:29:02 +1100945 goto out;
946 }
947
948 if (*s == '!' && options.permit_local_command) {
949 s++;
950 ssh_local_cmd(s);
Darren Tuckere7066df2004-05-24 10:18:05 +1000951 goto out;
952 }
953
954 if (*s == 'K') {
955 delete = 1;
956 s++;
957 }
Damien Miller0164cb82008-11-05 16:30:31 +1100958 if (*s == 'L')
959 local = 1;
960 else if (*s == 'R')
961 remote = 1;
962 else if (*s == 'D')
963 dynamic = 1;
964 else {
Damien Miller996acd22003-04-09 20:59:48 +1000965 logit("Invalid command.");
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000966 goto out;
967 }
Damien Miller0164cb82008-11-05 16:30:31 +1100968
Damien Millerff773642011-09-22 21:39:48 +1000969 if (delete && !compat20) {
Damien Miller996acd22003-04-09 20:59:48 +1000970 logit("Not supported for SSH protocol version 1.");
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000971 goto out;
972 }
Darren Tuckere7066df2004-05-24 10:18:05 +1000973
Damien Millerfdb23062013-11-21 13:57:15 +1100974 while (isspace((u_char)*++s))
Darren Tucker03b1cdb2007-03-21 20:46:03 +1100975 ;
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000976
Damien Millere1537f92010-01-26 13:26:22 +1100977 /* XXX update list of forwards in options */
Darren Tuckere7066df2004-05-24 10:18:05 +1000978 if (delete) {
Damien Miller7acefbb2014-07-18 14:11:24 +1000979 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
980 if (!parse_forward(&fwd, s, 1, 0)) {
981 logit("Bad forwarding close specification.");
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000982 goto out;
983 }
Damien Millerff773642011-09-22 21:39:48 +1000984 if (remote)
Damien Miller7acefbb2014-07-18 14:11:24 +1000985 ok = channel_request_rforward_cancel(&fwd) == 0;
Damien Millerff773642011-09-22 21:39:48 +1000986 else if (dynamic)
Damien Miller7acefbb2014-07-18 14:11:24 +1000987 ok = channel_cancel_lport_listener(&fwd,
988 0, &options.fwd_opts) > 0;
Damien Millerff773642011-09-22 21:39:48 +1000989 else
Damien Miller7acefbb2014-07-18 14:11:24 +1000990 ok = channel_cancel_lport_listener(&fwd,
991 CHANNEL_CANCEL_PORT_STATIC,
992 &options.fwd_opts) > 0;
Damien Millerff773642011-09-22 21:39:48 +1000993 if (!ok) {
dtucker@openbsd.org9390b002017-01-29 21:35:23 +0000994 logit("Unknown port forwarding.");
Damien Millerff773642011-09-22 21:39:48 +1000995 goto out;
996 }
997 logit("Canceled forwarding.");
Darren Tuckere7066df2004-05-24 10:18:05 +1000998 } else {
Damien Miller4bf648f2009-02-14 16:28:21 +1100999 if (!parse_forward(&fwd, s, dynamic, remote)) {
Darren Tuckere7066df2004-05-24 10:18:05 +10001000 logit("Bad forwarding specification.");
1001 goto out;
1002 }
Damien Miller0164cb82008-11-05 16:30:31 +11001003 if (local || dynamic) {
Damien Miller7acefbb2014-07-18 14:11:24 +10001004 if (!channel_setup_local_fwd_listener(&fwd,
1005 &options.fwd_opts)) {
Darren Tuckere7066df2004-05-24 10:18:05 +10001006 logit("Port forwarding failed.");
1007 goto out;
1008 }
Damien Millerf91ee4c2005-03-01 21:24:33 +11001009 } else {
Damien Miller7acefbb2014-07-18 14:11:24 +10001010 if (channel_request_remote_forwarding(&fwd) < 0) {
Darren Tuckere7d4b192006-07-12 22:17:10 +10001011 logit("Port forwarding failed.");
1012 goto out;
1013 }
Damien Millerf91ee4c2005-03-01 21:24:33 +11001014 }
Darren Tuckere7066df2004-05-24 10:18:05 +10001015 logit("Forwarding port.");
1016 }
1017
Ben Lindstrom5589f4b2002-03-22 03:24:32 +00001018out:
1019 signal(SIGINT, handler);
Damien Miller21771e22011-05-15 08:45:50 +10001020 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Darren Tuckera627d422013-06-02 07:31:17 +10001021 free(cmd);
1022 free(fwd.listen_host);
Damien Miller7acefbb2014-07-18 14:11:24 +10001023 free(fwd.listen_path);
Darren Tuckera627d422013-06-02 07:31:17 +10001024 free(fwd.connect_host);
Damien Miller7acefbb2014-07-18 14:11:24 +10001025 free(fwd.connect_path);
Ben Lindstrom5589f4b2002-03-22 03:24:32 +00001026}
1027
Darren Tucker92a39cf2012-09-07 11:20:20 +10001028/* reasons to suppress output of an escape command in help output */
1029#define SUPPRESS_NEVER 0 /* never suppress, always show */
1030#define SUPPRESS_PROTO1 1 /* don't show in protocol 1 sessions */
1031#define SUPPRESS_MUXCLIENT 2 /* don't show in mux client sessions */
1032#define SUPPRESS_MUXMASTER 4 /* don't show in mux master sessions */
1033#define SUPPRESS_SYSLOG 8 /* don't show when logging to syslog */
1034struct escape_help_text {
1035 const char *cmd;
1036 const char *text;
1037 unsigned int flags;
1038};
1039static struct escape_help_text esc_txt[] = {
1040 {".", "terminate session", SUPPRESS_MUXMASTER},
1041 {".", "terminate connection (and any multiplexed sessions)",
1042 SUPPRESS_MUXCLIENT},
1043 {"B", "send a BREAK to the remote system", SUPPRESS_PROTO1},
1044 {"C", "open a command line", SUPPRESS_MUXCLIENT},
1045 {"R", "request rekey", SUPPRESS_PROTO1},
Darren Tuckerca0d0fd2012-09-07 11:22:24 +10001046 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
Darren Tucker92a39cf2012-09-07 11:20:20 +10001047 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
1048 {"#", "list forwarded connections", SUPPRESS_NEVER},
1049 {"&", "background ssh (when waiting for connections to terminate)",
1050 SUPPRESS_MUXCLIENT},
1051 {"?", "this message", SUPPRESS_NEVER},
1052};
1053
1054static void
1055print_escape_help(Buffer *b, int escape_char, int protocol2, int mux_client,
1056 int using_stderr)
1057{
1058 unsigned int i, suppress_flags;
1059 char string[1024];
1060
1061 snprintf(string, sizeof string, "%c?\r\n"
1062 "Supported escape sequences:\r\n", escape_char);
1063 buffer_append(b, string, strlen(string));
1064
1065 suppress_flags = (protocol2 ? 0 : SUPPRESS_PROTO1) |
1066 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
1067 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1068 (using_stderr ? 0 : SUPPRESS_SYSLOG);
1069
1070 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
1071 if (esc_txt[i].flags & suppress_flags)
1072 continue;
Darren Tuckerca0d0fd2012-09-07 11:22:24 +10001073 snprintf(string, sizeof string, " %c%-3s - %s\r\n",
Darren Tucker92a39cf2012-09-07 11:20:20 +10001074 escape_char, esc_txt[i].cmd, esc_txt[i].text);
1075 buffer_append(b, string, strlen(string));
1076 }
1077
1078 snprintf(string, sizeof string,
Darren Tuckerca0d0fd2012-09-07 11:22:24 +10001079 " %c%c - send the escape character by typing it twice\r\n"
Darren Tucker92a39cf2012-09-07 11:20:20 +10001080 "(Note that escapes are only recognized immediately after "
1081 "newline.)\r\n", escape_char, escape_char);
1082 buffer_append(b, string, strlen(string));
1083}
1084
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001085/*
1086 * Process the characters one by one, call with c==NULL for proto1 case.
1087 */
Ben Lindstrombba81212001-06-25 05:01:22 +00001088static int
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001089process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
1090 char *buf, int len)
Damien Millerad833b32000-08-23 10:46:23 +10001091{
1092 char string[1024];
1093 pid_t pid;
1094 int bytes = 0;
Ben Lindstrom46c16222000-12-22 01:43:59 +00001095 u_int i;
1096 u_char ch;
Damien Millerad833b32000-08-23 10:46:23 +10001097 char *s;
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001098 int *escape_pendingp, escape_char;
1099 struct escape_filter_ctx *efc;
Damien Millerad833b32000-08-23 10:46:23 +10001100
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001101 if (c == NULL) {
1102 escape_pendingp = &escape_pending1;
1103 escape_char = escape_char1;
1104 } else {
1105 if (c->filter_ctx == NULL)
1106 return 0;
1107 efc = (struct escape_filter_ctx *)c->filter_ctx;
1108 escape_pendingp = &efc->escape_pending;
1109 escape_char = efc->escape_char;
1110 }
1111
Damien Millereccb9de2005-06-17 12:59:34 +10001112 if (len <= 0)
1113 return (0);
1114
1115 for (i = 0; i < (u_int)len; i++) {
Damien Millerad833b32000-08-23 10:46:23 +10001116 /* Get one character at a time. */
1117 ch = buf[i];
1118
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001119 if (*escape_pendingp) {
Damien Millerad833b32000-08-23 10:46:23 +10001120 /* We have previously seen an escape character. */
1121 /* Clear the flag now. */
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001122 *escape_pendingp = 0;
Damien Millerad833b32000-08-23 10:46:23 +10001123
1124 /* Process the escaped character. */
1125 switch (ch) {
1126 case '.':
1127 /* Terminate the connection. */
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001128 snprintf(string, sizeof string, "%c.\r\n",
1129 escape_char);
Damien Millerad833b32000-08-23 10:46:23 +10001130 buffer_append(berr, string, strlen(string));
Damien Millerad833b32000-08-23 10:46:23 +10001131
Damien Millere1537f92010-01-26 13:26:22 +11001132 if (c && c->ctl_chan != -1) {
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001133 chan_read_failed(c);
1134 chan_write_failed(c);
Darren Tuckerea8342c2013-06-06 08:11:40 +10001135 if (c->detach_user)
1136 c->detach_user(c->self, NULL);
Damien Miller36187092013-06-10 13:07:11 +10001137 c->type = SSH_CHANNEL_ABANDONED;
1138 buffer_clear(&c->input);
1139 chan_ibuf_empty(c);
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001140 return 0;
1141 } else
1142 quit_pending = 1;
Damien Millerad833b32000-08-23 10:46:23 +10001143 return -1;
1144
1145 case 'Z' - 64:
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001146 /* XXX support this for mux clients */
Damien Millere1537f92010-01-26 13:26:22 +11001147 if (c && c->ctl_chan != -1) {
Darren Tuckerf111d402012-09-07 11:21:42 +10001148 char b[16];
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001149 noescape:
Darren Tuckerf111d402012-09-07 11:21:42 +10001150 if (ch == 'Z' - 64)
1151 snprintf(b, sizeof b, "^Z");
1152 else
1153 snprintf(b, sizeof b, "%c", ch);
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001154 snprintf(string, sizeof string,
Darren Tuckerf111d402012-09-07 11:21:42 +10001155 "%c%s escape not available to "
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001156 "multiplexed sessions\r\n",
Darren Tuckerf111d402012-09-07 11:21:42 +10001157 escape_char, b);
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001158 buffer_append(berr, string,
1159 strlen(string));
1160 continue;
1161 }
Darren Tucker4d5cd332008-06-13 04:51:14 +10001162 /* Suspend the program. Inform the user */
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001163 snprintf(string, sizeof string,
1164 "%c^Z [suspend ssh]\r\n", escape_char);
Damien Millerad833b32000-08-23 10:46:23 +10001165 buffer_append(berr, string, strlen(string));
Damien Millerad833b32000-08-23 10:46:23 +10001166
1167 /* Restore terminal modes and suspend. */
1168 client_suspend_self(bin, bout, berr);
1169
1170 /* We have been continued. */
1171 continue;
1172
Damien Miller54c45982003-05-15 10:20:13 +10001173 case 'B':
1174 if (compat20) {
1175 snprintf(string, sizeof string,
1176 "%cB\r\n", escape_char);
1177 buffer_append(berr, string,
1178 strlen(string));
Damien Miller70182522013-09-14 09:49:19 +10001179 channel_request_start(c->self,
Damien Miller54c45982003-05-15 10:20:13 +10001180 "break", 0);
1181 packet_put_int(1000);
1182 packet_send();
1183 }
1184 continue;
1185
Ben Lindstromf28f6342001-04-04 02:03:04 +00001186 case 'R':
Ben Lindstrom11bd8992001-04-05 23:34:29 +00001187 if (compat20) {
1188 if (datafellows & SSH_BUG_NOREKEY)
Darren Tucker4d5cd332008-06-13 04:51:14 +10001189 logit("Server does not "
1190 "support re-keying");
Ben Lindstrom11bd8992001-04-05 23:34:29 +00001191 else
1192 need_rekeying = 1;
1193 }
Ben Lindstromf28f6342001-04-04 02:03:04 +00001194 continue;
1195
Darren Tucker50a48d02012-09-06 21:25:37 +10001196 case 'V':
1197 /* FALLTHROUGH */
1198 case 'v':
1199 if (c && c->ctl_chan != -1)
1200 goto noescape;
1201 if (!log_is_on_stderr()) {
1202 snprintf(string, sizeof string,
1203 "%c%c [Logging to syslog]\r\n",
1204 escape_char, ch);
1205 buffer_append(berr, string,
1206 strlen(string));
1207 continue;
1208 }
1209 if (ch == 'V' && options.log_level >
1210 SYSLOG_LEVEL_QUIET)
1211 log_change_level(--options.log_level);
1212 if (ch == 'v' && options.log_level <
1213 SYSLOG_LEVEL_DEBUG3)
1214 log_change_level(++options.log_level);
1215 snprintf(string, sizeof string,
1216 "%c%c [LogLevel %s]\r\n", escape_char, ch,
1217 log_level_name(options.log_level));
1218 buffer_append(berr, string, strlen(string));
1219 continue;
1220
Damien Millerad833b32000-08-23 10:46:23 +10001221 case '&':
Damien Millere1537f92010-01-26 13:26:22 +11001222 if (c && c->ctl_chan != -1)
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001223 goto noescape;
Damien Millerad833b32000-08-23 10:46:23 +10001224 /*
Darren Tucker4d5cd332008-06-13 04:51:14 +10001225 * Detach the program (continue to serve
1226 * connections, but put in background and no
1227 * more new connections).
Damien Millerad833b32000-08-23 10:46:23 +10001228 */
Damien Miller96507ef2001-11-12 10:52:25 +11001229 /* Restore tty modes. */
Damien Miller21771e22011-05-15 08:45:50 +10001230 leave_raw_mode(
1231 options.request_tty == REQUEST_TTY_FORCE);
Damien Miller96507ef2001-11-12 10:52:25 +11001232
1233 /* Stop listening for new connections. */
1234 channel_stop_listening();
1235
1236 snprintf(string, sizeof string,
1237 "%c& [backgrounded]\n", escape_char);
1238 buffer_append(berr, string, strlen(string));
1239
1240 /* Fork into background. */
1241 pid = fork();
1242 if (pid < 0) {
1243 error("fork: %.100s", strerror(errno));
1244 continue;
1245 }
1246 if (pid != 0) { /* This is the parent. */
1247 /* The parent just exits. */
1248 exit(0);
1249 }
1250 /* The child continues serving connections. */
1251 if (compat20) {
1252 buffer_append(bin, "\004", 1);
1253 /* fake EOF on stdin */
1254 return -1;
1255 } else if (!stdin_eof) {
Damien Millerad833b32000-08-23 10:46:23 +10001256 /*
Darren Tucker4d5cd332008-06-13 04:51:14 +10001257 * Sending SSH_CMSG_EOF alone does not
1258 * always appear to be enough. So we
1259 * try to send an EOF character first.
Damien Millerad833b32000-08-23 10:46:23 +10001260 */
1261 packet_start(SSH_CMSG_STDIN_DATA);
1262 packet_put_string("\004", 1);
1263 packet_send();
1264 /* Close stdin. */
1265 stdin_eof = 1;
1266 if (buffer_len(bin) == 0) {
1267 packet_start(SSH_CMSG_EOF);
1268 packet_send();
1269 }
1270 }
Damien Miller96507ef2001-11-12 10:52:25 +11001271 continue;
Damien Millerad833b32000-08-23 10:46:23 +10001272
1273 case '?':
Darren Tucker92a39cf2012-09-07 11:20:20 +10001274 print_escape_help(berr, escape_char, compat20,
1275 (c && c->ctl_chan != -1),
1276 log_is_on_stderr());
Damien Millerad833b32000-08-23 10:46:23 +10001277 continue;
1278
1279 case '#':
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001280 snprintf(string, sizeof string, "%c#\r\n",
1281 escape_char);
Damien Millerad833b32000-08-23 10:46:23 +10001282 buffer_append(berr, string, strlen(string));
1283 s = channel_open_message();
1284 buffer_append(berr, s, strlen(s));
Darren Tuckera627d422013-06-02 07:31:17 +10001285 free(s);
Damien Millerad833b32000-08-23 10:46:23 +10001286 continue;
1287
Ben Lindstrom5589f4b2002-03-22 03:24:32 +00001288 case 'C':
Damien Millere1537f92010-01-26 13:26:22 +11001289 if (c && c->ctl_chan != -1)
Damien Miller586b0052008-12-09 14:11:32 +11001290 goto noescape;
Ben Lindstrom681d9322002-03-22 03:53:00 +00001291 process_cmdline();
Ben Lindstrom5589f4b2002-03-22 03:24:32 +00001292 continue;
1293
Damien Millerad833b32000-08-23 10:46:23 +10001294 default:
1295 if (ch != escape_char) {
1296 buffer_put_char(bin, escape_char);
1297 bytes++;
1298 }
1299 /* Escaped characters fall through here */
1300 break;
1301 }
1302 } else {
1303 /*
Darren Tucker4d5cd332008-06-13 04:51:14 +10001304 * The previous character was not an escape char.
1305 * Check if this is an escape.
Damien Millerad833b32000-08-23 10:46:23 +10001306 */
1307 if (last_was_cr && ch == escape_char) {
Darren Tucker4d5cd332008-06-13 04:51:14 +10001308 /*
1309 * It is. Set the flag and continue to
1310 * next character.
1311 */
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001312 *escape_pendingp = 1;
Damien Millerad833b32000-08-23 10:46:23 +10001313 continue;
1314 }
1315 }
1316
1317 /*
1318 * Normal character. Record whether it was a newline,
1319 * and append it to the buffer.
1320 */
1321 last_was_cr = (ch == '\r' || ch == '\n');
1322 buffer_put_char(bin, ch);
1323 bytes++;
1324 }
1325 return bytes;
1326}
1327
Ben Lindstrombba81212001-06-25 05:01:22 +00001328static void
Damien Miller90fdfaf2006-03-26 14:25:37 +11001329client_process_input(fd_set *readset)
Damien Miller1383bd82000-04-06 12:32:37 +10001330{
Damien Miller166fca82000-04-20 07:42:21 +10001331 int len;
Darren Tucker86e30a02009-08-28 11:21:06 +10001332 char buf[SSH_IOBUFSZ];
Damien Miller1383bd82000-04-06 12:32:37 +10001333
Damien Miller95def091999-11-25 00:26:21 +11001334 /* Read input from stdin. */
1335 if (FD_ISSET(fileno(stdin), readset)) {
1336 /* Read as much as possible. */
1337 len = read(fileno(stdin), buf, sizeof(buf));
Damien Millerd8968ad2008-07-04 23:10:49 +10001338 if (len < 0 &&
1339 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
Ben Lindstrom4c8cff12001-04-17 18:09:42 +00001340 return; /* we'll try again later */
Damien Miller95def091999-11-25 00:26:21 +11001341 if (len <= 0) {
Damien Miller5428f641999-11-25 11:54:57 +11001342 /*
1343 * Received EOF or error. They are treated
1344 * similarly, except that an error message is printed
1345 * if it was an error condition.
1346 */
Damien Miller95def091999-11-25 00:26:21 +11001347 if (len < 0) {
Darren Tucker4d5cd332008-06-13 04:51:14 +10001348 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1349 strerror(errno));
Damien Miller95def091999-11-25 00:26:21 +11001350 buffer_append(&stderr_buffer, buf, strlen(buf));
Damien Miller95def091999-11-25 00:26:21 +11001351 }
1352 /* Mark that we have seen EOF. */
1353 stdin_eof = 1;
Damien Miller5428f641999-11-25 11:54:57 +11001354 /*
1355 * Send an EOF message to the server unless there is
1356 * data in the buffer. If there is data in the
1357 * buffer, no message will be sent now. Code
1358 * elsewhere will send the EOF when the buffer
1359 * becomes empty if stdin_eof is set.
1360 */
Damien Miller95def091999-11-25 00:26:21 +11001361 if (buffer_len(&stdin_buffer) == 0) {
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001362 packet_start(SSH_CMSG_EOF);
1363 packet_send();
Damien Miller95def091999-11-25 00:26:21 +11001364 }
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001365 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
Damien Miller5428f641999-11-25 11:54:57 +11001366 /*
1367 * Normal successful read, and no escape character.
1368 * Just append the data to buffer.
1369 */
Damien Miller95def091999-11-25 00:26:21 +11001370 buffer_append(&stdin_buffer, buf, len);
Damien Miller95def091999-11-25 00:26:21 +11001371 } else {
Damien Miller5428f641999-11-25 11:54:57 +11001372 /*
Darren Tucker4d5cd332008-06-13 04:51:14 +10001373 * Normal, successful read. But we have an escape
1374 * character and have to process the characters one
1375 * by one.
Damien Miller5428f641999-11-25 11:54:57 +11001376 */
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001377 if (process_escapes(NULL, &stdin_buffer,
1378 &stdout_buffer, &stderr_buffer, buf, len) == -1)
Damien Millerad833b32000-08-23 10:46:23 +10001379 return;
Damien Miller95def091999-11-25 00:26:21 +11001380 }
1381 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001382}
1383
Ben Lindstrombba81212001-06-25 05:01:22 +00001384static void
Damien Miller90fdfaf2006-03-26 14:25:37 +11001385client_process_output(fd_set *writeset)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001386{
Damien Miller95def091999-11-25 00:26:21 +11001387 int len;
1388 char buf[100];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001389
Damien Miller95def091999-11-25 00:26:21 +11001390 /* Write buffered output to stdout. */
1391 if (FD_ISSET(fileno(stdout), writeset)) {
1392 /* Write as much data as possible. */
1393 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
Damien Miller037a0dc1999-12-07 15:38:31 +11001394 buffer_len(&stdout_buffer));
Damien Miller95def091999-11-25 00:26:21 +11001395 if (len <= 0) {
Damien Millerd8968ad2008-07-04 23:10:49 +10001396 if (errno == EINTR || errno == EAGAIN ||
1397 errno == EWOULDBLOCK)
Damien Miller95def091999-11-25 00:26:21 +11001398 len = 0;
1399 else {
Damien Miller5428f641999-11-25 11:54:57 +11001400 /*
1401 * An error or EOF was encountered. Put an
1402 * error message to stderr buffer.
1403 */
Darren Tucker4d5cd332008-06-13 04:51:14 +10001404 snprintf(buf, sizeof buf,
1405 "write stdout: %.50s\r\n", strerror(errno));
Damien Miller95def091999-11-25 00:26:21 +11001406 buffer_append(&stderr_buffer, buf, strlen(buf));
Damien Miller95def091999-11-25 00:26:21 +11001407 quit_pending = 1;
1408 return;
1409 }
1410 }
1411 /* Consume printed data from the buffer. */
1412 buffer_consume(&stdout_buffer, len);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001413 }
Damien Miller95def091999-11-25 00:26:21 +11001414 /* Write buffered output to stderr. */
1415 if (FD_ISSET(fileno(stderr), writeset)) {
1416 /* Write as much data as possible. */
1417 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
Damien Miller037a0dc1999-12-07 15:38:31 +11001418 buffer_len(&stderr_buffer));
Damien Miller95def091999-11-25 00:26:21 +11001419 if (len <= 0) {
Damien Millerd8968ad2008-07-04 23:10:49 +10001420 if (errno == EINTR || errno == EAGAIN ||
1421 errno == EWOULDBLOCK)
Damien Miller95def091999-11-25 00:26:21 +11001422 len = 0;
1423 else {
Darren Tucker4d5cd332008-06-13 04:51:14 +10001424 /*
1425 * EOF or error, but can't even print
1426 * error message.
1427 */
Damien Miller95def091999-11-25 00:26:21 +11001428 quit_pending = 1;
1429 return;
1430 }
1431 }
1432 /* Consume printed characters from the buffer. */
1433 buffer_consume(&stderr_buffer, len);
1434 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001435}
1436
Damien Miller5428f641999-11-25 11:54:57 +11001437/*
Damien Millerb38eff82000-04-01 11:09:21 +10001438 * Get packets from the connection input buffer, and process them as long as
1439 * there are packets available.
1440 *
1441 * Any unknown packets received during the actual
1442 * session cause the session to terminate. This is
1443 * intended to make debugging easier since no
1444 * confirmations are sent. Any compatible protocol
1445 * extensions must be negotiated during the
1446 * preparatory phase.
1447 */
1448
Ben Lindstrombba81212001-06-25 05:01:22 +00001449static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +00001450client_process_buffered_input_packets(void)
Damien Millerb38eff82000-04-01 11:09:21 +10001451{
markus@openbsd.org57d10cb2015-01-19 20:16:15 +00001452 dispatch_run(DISPATCH_NONBLOCK, &quit_pending, active_state);
Damien Millerb38eff82000-04-01 11:09:21 +10001453}
1454
Damien Millerad833b32000-08-23 10:46:23 +10001455/* scan buf[] for '~' before sending data to the peer */
1456
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001457/* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1458void *
1459client_new_escape_filter_ctx(int escape_char)
1460{
1461 struct escape_filter_ctx *ret;
1462
Damien Miller6c81fee2013-11-08 12:19:55 +11001463 ret = xcalloc(1, sizeof(*ret));
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001464 ret->escape_pending = 0;
1465 ret->escape_char = escape_char;
1466 return (void *)ret;
1467}
1468
Darren Tucker84c56f52008-06-13 04:55:46 +10001469/* Free the escape filter context on channel free */
1470void
1471client_filter_cleanup(int cid, void *ctx)
1472{
Darren Tuckera627d422013-06-02 07:31:17 +10001473 free(ctx);
Darren Tucker84c56f52008-06-13 04:55:46 +10001474}
1475
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001476int
1477client_simple_escape_filter(Channel *c, char *buf, int len)
Damien Millerad833b32000-08-23 10:46:23 +10001478{
Damien Miller5771ed72008-05-19 15:35:33 +10001479 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1480 return 0;
1481
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001482 return process_escapes(c, &c->input, &c->output, &c->extended,
1483 buf, len);
Damien Millerad833b32000-08-23 10:46:23 +10001484}
1485
Ben Lindstrombba81212001-06-25 05:01:22 +00001486static void
Ben Lindstrom4c3f77d2001-04-05 23:37:36 +00001487client_channel_closed(int id, void *arg)
1488{
Damien Miller3ec27592001-10-12 11:35:04 +10001489 channel_cancel_cleanup(id);
Ben Lindstrom4c3f77d2001-04-05 23:37:36 +00001490 session_closed = 1;
Damien Miller21771e22011-05-15 08:45:50 +10001491 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Ben Lindstrom4c3f77d2001-04-05 23:37:36 +00001492}
1493
Damien Millerb38eff82000-04-01 11:09:21 +10001494/*
Damien Miller5428f641999-11-25 11:54:57 +11001495 * Implements the interactive session with the server. This is called after
1496 * the user has been authenticated, and a command has been started on the
Ben Lindstrom2b1f71b2001-06-05 20:32:21 +00001497 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1498 * used as an escape character for terminating or suspending the session.
Damien Miller5428f641999-11-25 11:54:57 +11001499 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001500
Damien Miller4af51302000-04-16 11:18:38 +10001501int
Damien Millerad833b32000-08-23 10:46:23 +10001502client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001503{
Damien Miller5e953212001-01-30 09:14:00 +11001504 fd_set *readset = NULL, *writeset = NULL;
Damien Miller95def091999-11-25 00:26:21 +11001505 double start_time, total_time;
djm@openbsd.org19bcf2e2016-02-08 10:57:07 +00001506 int r, max_fd = 0, max_fd2 = 0, len;
Damien Millerb61f3fc2008-07-11 17:36:48 +10001507 u_int64_t ibytes, obytes;
Darren Tuckerc7a6fc42004-08-13 21:18:00 +10001508 u_int nalloc = 0;
Damien Miller95def091999-11-25 00:26:21 +11001509 char buf[100];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001510
Damien Miller95def091999-11-25 00:26:21 +11001511 debug("Entering interactive session.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001512
semarie@openbsd.orgd7d2bc92015-12-26 07:46:03 +00001513 if (options.control_master &&
djm@openbsd.org368dd972016-07-23 02:54:08 +00001514 !option_clear_or_none(options.control_path)) {
semarie@openbsd.orgd7d2bc92015-12-26 07:46:03 +00001515 debug("pledge: id");
tb@openbsd.org372807c2016-07-11 21:38:13 +00001516 if (pledge("stdio rpath wpath cpath unix inet dns recvfd proc exec id tty",
semarie@openbsd.orgd7d2bc92015-12-26 07:46:03 +00001517 NULL) == -1)
1518 fatal("%s pledge(): %s", __func__, strerror(errno));
1519
1520 } else if (options.forward_x11 || options.permit_local_command) {
semarie@openbsd.orgb91926a2015-12-03 17:00:18 +00001521 debug("pledge: exec");
1522 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1523 NULL) == -1)
1524 fatal("%s pledge(): %s", __func__, strerror(errno));
1525
1526 } else if (options.update_hostkeys) {
1527 debug("pledge: filesystem full");
1528 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1529 NULL) == -1)
1530 fatal("%s pledge(): %s", __func__, strerror(errno));
1531
djm@openbsd.org368dd972016-07-23 02:54:08 +00001532 } else if (!option_clear_or_none(options.proxy_command) ||
1533 fork_after_authentication_flag) {
semarie@openbsd.orgb91926a2015-12-03 17:00:18 +00001534 debug("pledge: proc");
1535 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1536 fatal("%s pledge(): %s", __func__, strerror(errno));
1537
semarie@openbsd.orgb91926a2015-12-03 17:00:18 +00001538 } else {
1539 debug("pledge: network");
1540 if (pledge("stdio unix inet dns tty", NULL) == -1)
1541 fatal("%s pledge(): %s", __func__, strerror(errno));
1542 }
1543
Damien Miller95def091999-11-25 00:26:21 +11001544 start_time = get_current_time();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001545
Damien Miller95def091999-11-25 00:26:21 +11001546 /* Initialize variables. */
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001547 escape_pending1 = 0;
Damien Miller95def091999-11-25 00:26:21 +11001548 last_was_cr = 1;
1549 exit_status = -1;
1550 stdin_eof = 0;
1551 buffer_high = 64 * 1024;
1552 connection_in = packet_get_connection_in();
1553 connection_out = packet_get_connection_out();
deraadt@openbsd.org9136ec12016-09-12 01:22:38 +00001554 max_fd = MAXIMUM(connection_in, connection_out);
Damien Miller5e953212001-01-30 09:14:00 +11001555
1556 if (!compat20) {
Ben Lindstrom302ea6f2001-04-16 02:01:25 +00001557 /* enable nonblocking unless tty */
1558 if (!isatty(fileno(stdin)))
1559 set_nonblock(fileno(stdin));
1560 if (!isatty(fileno(stdout)))
1561 set_nonblock(fileno(stdout));
1562 if (!isatty(fileno(stderr)))
1563 set_nonblock(fileno(stderr));
deraadt@openbsd.org9136ec12016-09-12 01:22:38 +00001564 max_fd = MAXIMUM(max_fd, fileno(stdin));
1565 max_fd = MAXIMUM(max_fd, fileno(stdout));
1566 max_fd = MAXIMUM(max_fd, fileno(stderr));
Damien Miller5e953212001-01-30 09:14:00 +11001567 }
Damien Miller95def091999-11-25 00:26:21 +11001568 quit_pending = 0;
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001569 escape_char1 = escape_char_arg;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001570
Damien Miller95def091999-11-25 00:26:21 +11001571 /* Initialize buffers. */
1572 buffer_init(&stdin_buffer);
1573 buffer_init(&stdout_buffer);
1574 buffer_init(&stderr_buffer);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001575
Damien Millerb38eff82000-04-01 11:09:21 +10001576 client_init_dispatch();
1577
Ben Lindstromf49dbff2002-12-23 02:01:55 +00001578 /*
1579 * Set signal handlers, (e.g. to restore non-blocking mode)
1580 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1581 */
Darren Tucker07336da2004-11-05 20:02:16 +11001582 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1583 signal(SIGHUP, signal_handler);
Ben Lindstromf49dbff2002-12-23 02:01:55 +00001584 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1585 signal(SIGINT, signal_handler);
1586 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1587 signal(SIGQUIT, signal_handler);
1588 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1589 signal(SIGTERM, signal_handler);
Darren Tucker5d78de62004-11-05 20:35:44 +11001590 signal(SIGWINCH, window_change_handler);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001591
Damien Miller95def091999-11-25 00:26:21 +11001592 if (have_pty)
Damien Miller21771e22011-05-15 08:45:50 +10001593 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001594
Ben Lindstrom5b828322001-02-09 01:34:36 +00001595 if (compat20) {
1596 session_ident = ssh2_chan_id;
Damien Miller6c3eec72011-05-05 14:16:22 +10001597 if (session_ident != -1) {
1598 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1599 channel_register_filter(session_ident,
1600 client_simple_escape_filter, NULL,
1601 client_filter_cleanup,
1602 client_new_escape_filter_ctx(
1603 escape_char_arg));
1604 }
Ben Lindstrom4c3f77d2001-04-05 23:37:36 +00001605 channel_register_cleanup(session_ident,
Damien Miller39eda6e2005-11-05 14:52:50 +11001606 client_channel_closed, 0);
Damien Miller6c3eec72011-05-05 14:16:22 +10001607 }
Ben Lindstrom5b828322001-02-09 01:34:36 +00001608 } else {
1609 /* Check if we should immediately send eof on stdin. */
Damien Miller1383bd82000-04-06 12:32:37 +10001610 client_check_initial_eof_on_stdin();
Ben Lindstrom5b828322001-02-09 01:34:36 +00001611 }
Damien Millerad833b32000-08-23 10:46:23 +10001612
Damien Miller95def091999-11-25 00:26:21 +11001613 /* Main loop of the client for the interactive session mode. */
1614 while (!quit_pending) {
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001615
Damien Miller5428f641999-11-25 11:54:57 +11001616 /* Process buffered packets sent by the server. */
Damien Miller95def091999-11-25 00:26:21 +11001617 client_process_buffered_input_packets();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001618
Ben Lindstrom4c3f77d2001-04-05 23:37:36 +00001619 if (compat20 && session_closed && !channel_still_open())
Damien Miller1383bd82000-04-06 12:32:37 +10001620 break;
Ben Lindstrom4c3f77d2001-04-05 23:37:36 +00001621
djm@openbsd.org19bcf2e2016-02-08 10:57:07 +00001622 if (ssh_packet_is_rekeying(active_state)) {
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001623 debug("rekeying in progress");
djm@openbsd.org19bcf2e2016-02-08 10:57:07 +00001624 } else if (need_rekeying) {
1625 /* manual rekey request */
1626 debug("need rekeying");
1627 if ((r = kex_start_rekex(active_state)) != 0)
1628 fatal("%s: kex_start_rekex: %s", __func__,
1629 ssh_err(r));
1630 need_rekeying = 0;
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001631 } else {
1632 /*
1633 * Make packets of buffered stdin data, and buffer
1634 * them for sending to the server.
1635 */
1636 if (!compat20)
1637 client_make_packets_from_stdin_data();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001638
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001639 /*
1640 * Make packets from buffered channel data, and
1641 * enqueue them for sending to the server.
1642 */
1643 if (packet_not_very_much_data_to_write())
1644 channel_output_poll();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001645
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001646 /*
1647 * Check if the window size has changed, and buffer a
1648 * message about it to the server if so.
1649 */
1650 client_check_window_change();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001651
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001652 if (quit_pending)
1653 break;
1654 }
Damien Miller5428f641999-11-25 11:54:57 +11001655 /*
1656 * Wait until we have something to do (something becomes
1657 * available on one of the descriptors).
1658 */
Ben Lindstrom16d29d52001-07-18 16:01:46 +00001659 max_fd2 = max_fd;
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001660 client_wait_until_can_do_something(&readset, &writeset,
djm@openbsd.org19bcf2e2016-02-08 10:57:07 +00001661 &max_fd2, &nalloc, ssh_packet_is_rekeying(active_state));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001662
Damien Miller95def091999-11-25 00:26:21 +11001663 if (quit_pending)
1664 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001665
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001666 /* Do channel operations unless rekeying in progress. */
djm@openbsd.org19bcf2e2016-02-08 10:57:07 +00001667 if (!ssh_packet_is_rekeying(active_state))
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001668 channel_after_select(readset, writeset);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001669
Damien Miller1383bd82000-04-06 12:32:37 +10001670 /* Buffer input from the connection. */
Damien Miller5e953212001-01-30 09:14:00 +11001671 client_process_net_input(readset);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001672
Damien Miller1383bd82000-04-06 12:32:37 +10001673 if (quit_pending)
1674 break;
1675
1676 if (!compat20) {
1677 /* Buffer data from stdin */
Damien Miller5e953212001-01-30 09:14:00 +11001678 client_process_input(readset);
Damien Miller1383bd82000-04-06 12:32:37 +10001679 /*
1680 * Process output to stdout and stderr. Output to
1681 * the connection is processed elsewhere (above).
1682 */
Damien Miller5e953212001-01-30 09:14:00 +11001683 client_process_output(writeset);
Damien Miller1383bd82000-04-06 12:32:37 +10001684 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001685
Darren Tucker4d5cd332008-06-13 04:51:14 +10001686 /*
1687 * Send as much buffered packet data as possible to the
1688 * sender.
1689 */
Damien Miller5e953212001-01-30 09:14:00 +11001690 if (FD_ISSET(connection_out, writeset))
Damien Miller95def091999-11-25 00:26:21 +11001691 packet_write_poll();
Damien Millere11e1ea2010-08-03 16:04:46 +10001692
1693 /*
1694 * If we are a backgrounded control master, and the
1695 * timeout has expired without any active client
1696 * connections, then quit.
1697 */
1698 if (control_persist_exit_time > 0) {
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001699 if (monotime() >= control_persist_exit_time) {
Damien Millere11e1ea2010-08-03 16:04:46 +10001700 debug("ControlPersist timeout expired");
1701 break;
1702 }
1703 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001704 }
Darren Tuckera627d422013-06-02 07:31:17 +10001705 free(readset);
1706 free(writeset);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001707
Damien Miller95def091999-11-25 00:26:21 +11001708 /* Terminate the session. */
1709
1710 /* Stop watching for window change. */
Darren Tucker5d78de62004-11-05 20:35:44 +11001711 signal(SIGWINCH, SIG_DFL);
Damien Miller95def091999-11-25 00:26:21 +11001712
Darren Tuckerde0c0252009-07-06 07:17:35 +10001713 if (compat20) {
1714 packet_start(SSH2_MSG_DISCONNECT);
1715 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1716 packet_put_cstring("disconnected by user");
Damien Miller8ddc71c2010-03-22 05:54:02 +11001717 packet_put_cstring(""); /* language tag */
Darren Tuckerde0c0252009-07-06 07:17:35 +10001718 packet_send();
1719 packet_write_wait();
1720 }
Darren Tucker12b4a652009-06-21 18:14:48 +10001721
Ben Lindstrom601e4362001-06-21 03:19:23 +00001722 channel_free_all();
Damien Miller95def091999-11-25 00:26:21 +11001723
Ben Lindstromec46e0b2001-06-09 01:27:31 +00001724 if (have_pty)
Damien Miller21771e22011-05-15 08:45:50 +10001725 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Ben Lindstromc93e84c2001-05-12 00:08:37 +00001726
1727 /* restore blocking io */
1728 if (!isatty(fileno(stdin)))
1729 unset_nonblock(fileno(stdin));
1730 if (!isatty(fileno(stdout)))
1731 unset_nonblock(fileno(stdout));
1732 if (!isatty(fileno(stderr)))
1733 unset_nonblock(fileno(stderr));
1734
Damien Millerd6965512003-12-17 16:31:53 +11001735 /*
1736 * If there was no shell or command requested, there will be no remote
1737 * exit status to be returned. In that case, clear error code if the
1738 * connection was deliberately terminated at this end.
1739 */
1740 if (no_shell_flag && received_signal == SIGTERM) {
1741 received_signal = 0;
1742 exit_status = 0;
1743 }
1744
Darren Tucker9a2c4cd2003-09-22 21:16:05 +10001745 if (received_signal)
Ben Lindstromf8f065b2001-12-06 17:52:16 +00001746 fatal("Killed by signal %d.", (int) received_signal);
Ben Lindstromec46e0b2001-06-09 01:27:31 +00001747
1748 /*
1749 * In interactive mode (with pseudo tty) display a message indicating
1750 * that the connection has been closed.
1751 */
1752 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
Darren Tucker4d5cd332008-06-13 04:51:14 +10001753 snprintf(buf, sizeof buf,
1754 "Connection to %.64s closed.\r\n", host);
Ben Lindstromec46e0b2001-06-09 01:27:31 +00001755 buffer_append(&stderr_buffer, buf, strlen(buf));
1756 }
1757
Damien Miller95def091999-11-25 00:26:21 +11001758 /* Output any buffered data for stdout. */
Damien Millercfd6e4f2011-01-16 23:18:33 +11001759 if (buffer_len(&stdout_buffer) > 0) {
Damien Miller4791f9d2011-01-16 23:16:53 +11001760 len = atomicio(vwrite, fileno(stdout),
1761 buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
Damien Millercfd6e4f2011-01-16 23:18:33 +11001762 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
Damien Miller95def091999-11-25 00:26:21 +11001763 error("Write failed flushing stdout buffer.");
Damien Millercfd6e4f2011-01-16 23:18:33 +11001764 else
1765 buffer_consume(&stdout_buffer, len);
Damien Miller95def091999-11-25 00:26:21 +11001766 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001767
Damien Miller95def091999-11-25 00:26:21 +11001768 /* Output any buffered data for stderr. */
Damien Millercfd6e4f2011-01-16 23:18:33 +11001769 if (buffer_len(&stderr_buffer) > 0) {
Damien Miller4791f9d2011-01-16 23:16:53 +11001770 len = atomicio(vwrite, fileno(stderr),
1771 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
Damien Millercfd6e4f2011-01-16 23:18:33 +11001772 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
Damien Miller95def091999-11-25 00:26:21 +11001773 error("Write failed flushing stderr buffer.");
Damien Millercfd6e4f2011-01-16 23:18:33 +11001774 else
1775 buffer_consume(&stderr_buffer, len);
Damien Miller95def091999-11-25 00:26:21 +11001776 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001777
Damien Miller95def091999-11-25 00:26:21 +11001778 /* Clear and free any buffers. */
jsg@openbsd.org458abc22016-01-23 05:31:35 +00001779 explicit_bzero(buf, sizeof(buf));
Damien Miller95def091999-11-25 00:26:21 +11001780 buffer_free(&stdin_buffer);
1781 buffer_free(&stdout_buffer);
1782 buffer_free(&stderr_buffer);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001783
Damien Miller95def091999-11-25 00:26:21 +11001784 /* Report bytes transferred, and transfer rates. */
1785 total_time = get_current_time() - start_time;
markus@openbsd.org091c3022015-01-19 19:52:16 +00001786 packet_get_bytes(&ibytes, &obytes);
Damien Millerb61f3fc2008-07-11 17:36:48 +10001787 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
Damien Miller821de0a2011-01-11 17:20:29 +11001788 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
Damien Miller95def091999-11-25 00:26:21 +11001789 if (total_time > 0)
Damien Millerb61f3fc2008-07-11 17:36:48 +10001790 verbose("Bytes per second: sent %.1f, received %.1f",
1791 obytes / total_time, ibytes / total_time);
Damien Miller95def091999-11-25 00:26:21 +11001792 /* Return the exit status of the program. */
1793 debug("Exit status %d", exit_status);
1794 return exit_status;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001795}
Damien Millerb38eff82000-04-01 11:09:21 +10001796
1797/*********/
1798
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001799static int
Damien Miller630d6f42002-01-22 23:17:30 +11001800client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
Damien Millerb38eff82000-04-01 11:09:21 +10001801{
Ben Lindstrom46c16222000-12-22 01:43:59 +00001802 u_int data_len;
Damien Millerb38eff82000-04-01 11:09:21 +10001803 char *data = packet_get_string(&data_len);
Damien Miller48b03fc2002-01-22 23:11:40 +11001804 packet_check_eom();
Damien Millerb38eff82000-04-01 11:09:21 +10001805 buffer_append(&stdout_buffer, data, data_len);
Damien Millera5103f42014-02-04 11:20:14 +11001806 explicit_bzero(data, data_len);
Darren Tuckera627d422013-06-02 07:31:17 +10001807 free(data);
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001808 return 0;
Damien Millerb38eff82000-04-01 11:09:21 +10001809}
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001810static int
Damien Miller630d6f42002-01-22 23:17:30 +11001811client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
Damien Millerb38eff82000-04-01 11:09:21 +10001812{
Ben Lindstrom46c16222000-12-22 01:43:59 +00001813 u_int data_len;
Damien Millerb38eff82000-04-01 11:09:21 +10001814 char *data = packet_get_string(&data_len);
Damien Miller48b03fc2002-01-22 23:11:40 +11001815 packet_check_eom();
Damien Millerb38eff82000-04-01 11:09:21 +10001816 buffer_append(&stderr_buffer, data, data_len);
Damien Millera5103f42014-02-04 11:20:14 +11001817 explicit_bzero(data, data_len);
Darren Tuckera627d422013-06-02 07:31:17 +10001818 free(data);
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001819 return 0;
Damien Millerb38eff82000-04-01 11:09:21 +10001820}
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001821static int
Damien Miller630d6f42002-01-22 23:17:30 +11001822client_input_exit_status(int type, u_int32_t seq, void *ctxt)
Damien Millerb38eff82000-04-01 11:09:21 +10001823{
Damien Millerb38eff82000-04-01 11:09:21 +10001824 exit_status = packet_get_int();
Damien Miller48b03fc2002-01-22 23:11:40 +11001825 packet_check_eom();
Damien Millerb38eff82000-04-01 11:09:21 +10001826 /* Acknowledge the exit. */
1827 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1828 packet_send();
1829 /*
1830 * Must wait for packet to be sent since we are
1831 * exiting the loop.
1832 */
1833 packet_write_wait();
1834 /* Flag that we want to exit. */
1835 quit_pending = 1;
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001836 return 0;
Damien Millerb38eff82000-04-01 11:09:21 +10001837}
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00001838
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001839static int
Darren Tucker5dcdd212003-10-02 16:17:00 +10001840client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1841{
1842 Channel *c = NULL;
djm@openbsd.org141efe42015-01-14 20:05:27 +00001843 int r, remote_id, sock;
Darren Tucker5dcdd212003-10-02 16:17:00 +10001844
1845 /* Read the remote channel number from the message. */
1846 remote_id = packet_get_int();
1847 packet_check_eom();
1848
1849 /*
1850 * Get a connection to the local authentication agent (this may again
1851 * get forwarded).
1852 */
djm@openbsd.org141efe42015-01-14 20:05:27 +00001853 if ((r = ssh_get_authentication_socket(&sock)) != 0 &&
1854 r != SSH_ERR_AGENT_NOT_PRESENT)
1855 debug("%s: ssh_get_authentication_socket: %s",
1856 __func__, ssh_err(r));
1857
Darren Tucker5dcdd212003-10-02 16:17:00 +10001858
1859 /*
1860 * If we could not connect the agent, send an error message back to
1861 * the server. This should never happen unless the agent dies,
1862 * because authentication forwarding is only enabled if we have an
1863 * agent.
1864 */
1865 if (sock >= 0) {
1866 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1867 -1, 0, 0, 0, "authentication agent connection", 1);
1868 c->remote_id = remote_id;
1869 c->force_drain = 1;
1870 }
1871 if (c == NULL) {
1872 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1873 packet_put_int(remote_id);
1874 } else {
1875 /* Send a confirmation to the remote host. */
1876 debug("Forwarding authentication connection.");
1877 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1878 packet_put_int(remote_id);
1879 packet_put_int(c->self);
1880 }
1881 packet_send();
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001882 return 0;
Darren Tucker5dcdd212003-10-02 16:17:00 +10001883}
Damien Millerb38eff82000-04-01 11:09:21 +10001884
Ben Lindstrombba81212001-06-25 05:01:22 +00001885static Channel *
markus@openbsd.org8d057842016-09-30 09:19:13 +00001886client_request_forwarded_tcpip(const char *request_type, int rchan,
1887 u_int rwindow, u_int rmaxpack)
Damien Miller0bc1bd82000-11-13 22:57:25 +11001888{
Ben Lindstroma962c2f2002-07-04 00:14:17 +00001889 Channel *c = NULL;
markus@openbsd.org8d057842016-09-30 09:19:13 +00001890 struct sshbuf *b = NULL;
Damien Miller0bc1bd82000-11-13 22:57:25 +11001891 char *listen_address, *originator_address;
Damien Miller3dc71ad2009-01-28 16:31:22 +11001892 u_short listen_port, originator_port;
markus@openbsd.org8d057842016-09-30 09:19:13 +00001893 int r;
Damien Miller0bc1bd82000-11-13 22:57:25 +11001894
1895 /* Get rest of the packet */
1896 listen_address = packet_get_string(NULL);
1897 listen_port = packet_get_int();
1898 originator_address = packet_get_string(NULL);
1899 originator_port = packet_get_int();
Damien Miller48b03fc2002-01-22 23:11:40 +11001900 packet_check_eom();
Damien Miller0bc1bd82000-11-13 22:57:25 +11001901
Damien Miller7acefbb2014-07-18 14:11:24 +10001902 debug("%s: listen %s port %d, originator %s port %d", __func__,
1903 listen_address, listen_port, originator_address, originator_port);
Damien Miller0bc1bd82000-11-13 22:57:25 +11001904
Damien Miller4b3ed642014-07-02 15:29:40 +10001905 c = channel_connect_by_listen_address(listen_address, listen_port,
Damien Millerbd740252008-05-19 15:37:09 +10001906 "forwarded-tcpip", originator_address);
1907
markus@openbsd.org8d057842016-09-30 09:19:13 +00001908 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1909 if ((b = sshbuf_new()) == NULL) {
1910 error("%s: alloc reply", __func__);
1911 goto out;
1912 }
1913 /* reconstruct and send to muxclient */
1914 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1915 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1916 (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1917 (r = sshbuf_put_u32(b, rchan)) != 0 ||
1918 (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1919 (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1920 (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1921 (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1922 (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1923 (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1924 (r = sshbuf_put_stringb(&c->output, b)) != 0) {
1925 error("%s: compose for muxclient %s", __func__,
1926 ssh_err(r));
1927 goto out;
1928 }
1929 }
1930
1931 out:
1932 sshbuf_free(b);
Darren Tuckera627d422013-06-02 07:31:17 +10001933 free(originator_address);
1934 free(listen_address);
Damien Miller0bc1bd82000-11-13 22:57:25 +11001935 return c;
1936}
1937
Ben Lindstroma962c2f2002-07-04 00:14:17 +00001938static Channel *
Damien Miller7acefbb2014-07-18 14:11:24 +10001939client_request_forwarded_streamlocal(const char *request_type, int rchan)
1940{
1941 Channel *c = NULL;
1942 char *listen_path;
1943
1944 /* Get the remote path. */
1945 listen_path = packet_get_string(NULL);
1946 /* XXX: Skip reserved field for now. */
1947 if (packet_get_string_ptr(NULL) == NULL)
1948 fatal("%s: packet_get_string_ptr failed", __func__);
1949 packet_check_eom();
1950
1951 debug("%s: %s", __func__, listen_path);
1952
1953 c = channel_connect_by_listen_path(listen_path,
1954 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1955 free(listen_path);
1956 return c;
1957}
1958
1959static Channel *
Damien Miller0bc1bd82000-11-13 22:57:25 +11001960client_request_x11(const char *request_type, int rchan)
1961{
1962 Channel *c = NULL;
1963 char *originator;
Damien Miller3dc71ad2009-01-28 16:31:22 +11001964 u_short originator_port;
Ben Lindstrom99c73b32001-05-05 04:09:47 +00001965 int sock;
Damien Miller0bc1bd82000-11-13 22:57:25 +11001966
1967 if (!options.forward_x11) {
1968 error("Warning: ssh server tried X11 forwarding.");
Darren Tucker4d5cd332008-06-13 04:51:14 +10001969 error("Warning: this is probably a break-in attempt by a "
1970 "malicious server.");
Damien Miller0bc1bd82000-11-13 22:57:25 +11001971 return NULL;
1972 }
djm@openbsd.org1bf477d2015-07-01 02:26:31 +00001973 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
Damien Miller1ab6a512010-06-26 10:02:24 +10001974 verbose("Rejected X11 connection after ForwardX11Timeout "
1975 "expired");
1976 return NULL;
1977 }
Damien Miller0bc1bd82000-11-13 22:57:25 +11001978 originator = packet_get_string(NULL);
1979 if (datafellows & SSH_BUG_X11FWD) {
1980 debug2("buggy server: x11 request w/o originator_port");
1981 originator_port = 0;
1982 } else {
1983 originator_port = packet_get_int();
1984 }
Damien Miller48b03fc2002-01-22 23:11:40 +11001985 packet_check_eom();
Damien Miller0bc1bd82000-11-13 22:57:25 +11001986 /* XXX check permission */
Damien Millerd83ff352001-01-30 09:19:34 +11001987 debug("client_request_x11: request from %s %d", originator,
1988 originator_port);
Darren Tuckera627d422013-06-02 07:31:17 +10001989 free(originator);
Ben Lindstrom99c73b32001-05-05 04:09:47 +00001990 sock = x11_connect_display();
1991 if (sock < 0)
1992 return NULL;
1993 c = channel_new("x11",
1994 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
Damien Millerb1ca8bb2003-05-14 13:45:42 +10001995 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
Ben Lindstrom944c4f02001-09-18 05:51:13 +00001996 c->force_drain = 1;
Damien Miller0bc1bd82000-11-13 22:57:25 +11001997 return c;
1998}
1999
Ben Lindstroma962c2f2002-07-04 00:14:17 +00002000static Channel *
Damien Miller0bc1bd82000-11-13 22:57:25 +11002001client_request_agent(const char *request_type, int rchan)
2002{
2003 Channel *c = NULL;
djm@openbsd.org141efe42015-01-14 20:05:27 +00002004 int r, sock;
Damien Miller0bc1bd82000-11-13 22:57:25 +11002005
2006 if (!options.forward_agent) {
2007 error("Warning: ssh server tried agent forwarding.");
Darren Tucker4d5cd332008-06-13 04:51:14 +10002008 error("Warning: this is probably a break-in attempt by a "
2009 "malicious server.");
Damien Miller0bc1bd82000-11-13 22:57:25 +11002010 return NULL;
2011 }
djm@openbsd.org141efe42015-01-14 20:05:27 +00002012 if ((r = ssh_get_authentication_socket(&sock)) != 0) {
2013 if (r != SSH_ERR_AGENT_NOT_PRESENT)
2014 debug("%s: ssh_get_authentication_socket: %s",
2015 __func__, ssh_err(r));
Ben Lindstrom99c73b32001-05-05 04:09:47 +00002016 return NULL;
djm@openbsd.org141efe42015-01-14 20:05:27 +00002017 }
Ben Lindstrom99c73b32001-05-05 04:09:47 +00002018 c = channel_new("authentication agent connection",
2019 SSH_CHANNEL_OPEN, sock, sock, -1,
Darren Tucker5baa1702007-12-29 09:37:10 +11002020 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
Damien Millerb1ca8bb2003-05-14 13:45:42 +10002021 "authentication agent connection", 1);
Ben Lindstrom944c4f02001-09-18 05:51:13 +00002022 c->force_drain = 1;
Damien Miller0bc1bd82000-11-13 22:57:25 +11002023 return c;
2024}
2025
Damien Millerb3ce9fe2007-08-08 14:32:41 +10002026int
2027client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
2028{
2029 Channel *c;
2030 int fd;
2031
2032 if (tun_mode == SSH_TUNMODE_NO)
2033 return 0;
2034
2035 if (!compat20) {
Damien Millerb3f2c9f2009-01-28 16:15:30 +11002036 error("Tunnel forwarding is not supported for protocol 1");
Damien Millerb3ce9fe2007-08-08 14:32:41 +10002037 return -1;
2038 }
2039
2040 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
2041
2042 /* Open local tunnel device */
2043 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
2044 error("Tunnel device open failed.");
2045 return -1;
2046 }
2047
2048 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
2049 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
2050 c->datagram = 1;
2051
2052#if defined(SSH_TUN_FILTER)
2053 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
2054 channel_register_filter(c->self, sys_tun_infilter,
Darren Tucker1cf65ae2008-06-13 05:09:18 +10002055 sys_tun_outfilter, NULL, NULL);
Damien Millerb3ce9fe2007-08-08 14:32:41 +10002056#endif
2057
2058 packet_start(SSH2_MSG_CHANNEL_OPEN);
2059 packet_put_cstring("tun@openssh.com");
2060 packet_put_int(c->self);
2061 packet_put_int(c->local_window_max);
2062 packet_put_int(c->local_maxpacket);
2063 packet_put_int(tun_mode);
2064 packet_put_int(remote_tun);
2065 packet_send();
2066
2067 return 0;
2068}
2069
Damien Millerbd483e72000-04-30 10:00:53 +10002070/* XXXX move to generic input handler */
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00002071static int
Damien Miller630d6f42002-01-22 23:17:30 +11002072client_input_channel_open(int type, u_int32_t seq, void *ctxt)
Damien Millerbd483e72000-04-30 10:00:53 +10002073{
2074 Channel *c = NULL;
2075 char *ctype;
Damien Millerbd483e72000-04-30 10:00:53 +10002076 int rchan;
Ben Lindstrom4fed2be2002-06-25 23:17:36 +00002077 u_int rmaxpack, rwindow, len;
Damien Millerbd483e72000-04-30 10:00:53 +10002078
2079 ctype = packet_get_string(&len);
2080 rchan = packet_get_int();
2081 rwindow = packet_get_int();
2082 rmaxpack = packet_get_int();
2083
Damien Millere247cc42000-05-07 12:03:14 +10002084 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
Damien Millerbd483e72000-04-30 10:00:53 +10002085 ctype, rchan, rwindow, rmaxpack);
2086
Damien Miller0bc1bd82000-11-13 22:57:25 +11002087 if (strcmp(ctype, "forwarded-tcpip") == 0) {
markus@openbsd.org8d057842016-09-30 09:19:13 +00002088 c = client_request_forwarded_tcpip(ctype, rchan, rwindow,
2089 rmaxpack);
Damien Miller7acefbb2014-07-18 14:11:24 +10002090 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
2091 c = client_request_forwarded_streamlocal(ctype, rchan);
Damien Miller0bc1bd82000-11-13 22:57:25 +11002092 } else if (strcmp(ctype, "x11") == 0) {
2093 c = client_request_x11(ctype, rchan);
2094 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
2095 c = client_request_agent(ctype, rchan);
Damien Millerbd483e72000-04-30 10:00:53 +10002096 }
markus@openbsd.org8d057842016-09-30 09:19:13 +00002097 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
2098 debug3("proxied to downstream: %s", ctype);
2099 } else if (c != NULL) {
Damien Millerbd483e72000-04-30 10:00:53 +10002100 debug("confirm %s", ctype);
2101 c->remote_id = rchan;
2102 c->remote_window = rwindow;
2103 c->remote_maxpacket = rmaxpack;
Ben Lindstroma69d89b2001-05-09 00:01:18 +00002104 if (c->type != SSH_CHANNEL_CONNECTING) {
2105 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
2106 packet_put_int(c->remote_id);
2107 packet_put_int(c->self);
2108 packet_put_int(c->local_window);
2109 packet_put_int(c->local_maxpacket);
2110 packet_send();
2111 }
Damien Millerbd483e72000-04-30 10:00:53 +10002112 } else {
2113 debug("failure %s", ctype);
2114 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
2115 packet_put_int(rchan);
2116 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
Ben Lindstromf3436742001-04-29 19:52:00 +00002117 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
Ben Lindstroma69d89b2001-05-09 00:01:18 +00002118 packet_put_cstring("open failed");
Ben Lindstromf3436742001-04-29 19:52:00 +00002119 packet_put_cstring("");
2120 }
Damien Millerbd483e72000-04-30 10:00:53 +10002121 packet_send();
2122 }
Darren Tuckera627d422013-06-02 07:31:17 +10002123 free(ctype);
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00002124 return 0;
Damien Millerbd483e72000-04-30 10:00:53 +10002125}
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002126
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00002127static int
Damien Miller630d6f42002-01-22 23:17:30 +11002128client_input_channel_req(int type, u_int32_t seq, void *ctxt)
Ben Lindstrom5b828322001-02-09 01:34:36 +00002129{
2130 Channel *c = NULL;
Damien Miller0e220db2004-06-15 10:34:08 +10002131 int exitval, id, reply, success = 0;
Ben Lindstrom5b828322001-02-09 01:34:36 +00002132 char *rtype;
2133
2134 id = packet_get_int();
markus@openbsd.org8d057842016-09-30 09:19:13 +00002135 c = channel_lookup(id);
2136 if (channel_proxy_upstream(c, type, seq, ctxt))
2137 return 0;
Ben Lindstrom5b828322001-02-09 01:34:36 +00002138 rtype = packet_get_string(NULL);
2139 reply = packet_get_char();
2140
2141 debug("client_input_channel_req: channel %d rtype %s reply %d",
2142 id, rtype, reply);
2143
Damien Miller3bbd8782004-06-18 22:23:22 +10002144 if (id == -1) {
2145 error("client_input_channel_req: request for channel -1");
markus@openbsd.org8d057842016-09-30 09:19:13 +00002146 } else if (c == NULL) {
Darren Tucker4d5cd332008-06-13 04:51:14 +10002147 error("client_input_channel_req: channel %d: "
2148 "unknown channel", id);
Damien Millerbab9bd42008-05-19 16:06:47 +10002149 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
2150 packet_check_eom();
2151 chan_rcvd_eow(c);
Ben Lindstrom5b828322001-02-09 01:34:36 +00002152 } else if (strcmp(rtype, "exit-status") == 0) {
Damien Miller0e220db2004-06-15 10:34:08 +10002153 exitval = packet_get_int();
Damien Millere1537f92010-01-26 13:26:22 +11002154 if (c->ctl_chan != -1) {
2155 mux_exit_message(c, exitval);
Damien Miller0e220db2004-06-15 10:34:08 +10002156 success = 1;
Darren Tucker29440822010-01-08 17:08:35 +11002157 } else if (id == session_ident) {
2158 /* Record exit value of local session */
2159 success = 1;
2160 exit_status = exitval;
2161 } else {
Damien Miller36f57eb2010-01-30 17:28:34 +11002162 /* Probably for a mux channel that has already closed */
2163 debug("%s: no sink for exit-status on channel %d",
2164 __func__, id);
Damien Miller0e220db2004-06-15 10:34:08 +10002165 }
Damien Miller48b03fc2002-01-22 23:11:40 +11002166 packet_check_eom();
Ben Lindstrom5b828322001-02-09 01:34:36 +00002167 }
Damien Millerc5893782014-05-15 13:48:49 +10002168 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
Ben Lindstrom5b828322001-02-09 01:34:36 +00002169 packet_start(success ?
2170 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
Damien Miller8533c782008-12-08 09:54:40 +11002171 packet_put_int(c->remote_id);
Ben Lindstrom5b828322001-02-09 01:34:36 +00002172 packet_send();
2173 }
Darren Tuckera627d422013-06-02 07:31:17 +10002174 free(rtype);
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00002175 return 0;
Ben Lindstrom5b828322001-02-09 01:34:36 +00002176}
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002177
djm@openbsd.org523463a2015-02-16 22:13:32 +00002178struct hostkeys_update_ctx {
2179 /* The hostname and (optionally) IP address string for the server */
2180 char *host_str, *ip_str;
2181
2182 /*
2183 * Keys received from the server and a flag for each indicating
2184 * whether they already exist in known_hosts.
2185 * keys_seen is filled in by hostkeys_find() and later (for new
2186 * keys) by client_global_hostkeys_private_confirm().
2187 */
2188 struct sshkey **keys;
2189 int *keys_seen;
2190 size_t nkeys;
2191
2192 size_t nnew;
2193
2194 /*
2195 * Keys that are in known_hosts, but were not present in the update
2196 * from the server (i.e. scheduled to be deleted).
2197 * Filled in by hostkeys_find().
2198 */
2199 struct sshkey **old_keys;
2200 size_t nold;
2201};
2202
2203static void
2204hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
2205{
2206 size_t i;
2207
2208 if (ctx == NULL)
2209 return;
2210 for (i = 0; i < ctx->nkeys; i++)
2211 sshkey_free(ctx->keys[i]);
2212 free(ctx->keys);
2213 free(ctx->keys_seen);
2214 for (i = 0; i < ctx->nold; i++)
2215 sshkey_free(ctx->old_keys[i]);
2216 free(ctx->old_keys);
2217 free(ctx->host_str);
2218 free(ctx->ip_str);
2219 free(ctx);
2220}
2221
2222static int
2223hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
2224{
2225 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2226 size_t i;
2227 struct sshkey **tmp;
2228
2229 if (l->status != HKF_STATUS_MATCHED || l->key == NULL ||
2230 l->key->type == KEY_RSA1)
2231 return 0;
2232
2233 /* Mark off keys we've already seen for this host */
2234 for (i = 0; i < ctx->nkeys; i++) {
2235 if (sshkey_equal(l->key, ctx->keys[i])) {
2236 debug3("%s: found %s key at %s:%ld", __func__,
2237 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
2238 ctx->keys_seen[i] = 1;
2239 return 0;
2240 }
2241 }
2242 /* This line contained a key that not offered by the server */
2243 debug3("%s: deprecated %s key at %s:%ld", __func__,
2244 sshkey_ssh_name(l->key), l->path, l->linenum);
2245 if ((tmp = reallocarray(ctx->old_keys, ctx->nold + 1,
2246 sizeof(*ctx->old_keys))) == NULL)
2247 fatal("%s: reallocarray failed nold = %zu",
2248 __func__, ctx->nold);
2249 ctx->old_keys = tmp;
2250 ctx->old_keys[ctx->nold++] = l->key;
2251 l->key = NULL;
2252
2253 return 0;
2254}
2255
2256static void
2257update_known_hosts(struct hostkeys_update_ctx *ctx)
2258{
djm@openbsd.orgf2293a62015-02-23 16:33:25 +00002259 int r, was_raw = 0;
2260 int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
djm@openbsd.org523463a2015-02-16 22:13:32 +00002261 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
2262 char *fp, *response;
2263 size_t i;
2264
2265 for (i = 0; i < ctx->nkeys; i++) {
2266 if (ctx->keys_seen[i] != 2)
2267 continue;
2268 if ((fp = sshkey_fingerprint(ctx->keys[i],
2269 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2270 fatal("%s: sshkey_fingerprint failed", __func__);
2271 do_log2(loglevel, "Learned new hostkey: %s %s",
2272 sshkey_type(ctx->keys[i]), fp);
2273 free(fp);
2274 }
2275 for (i = 0; i < ctx->nold; i++) {
2276 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
2277 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2278 fatal("%s: sshkey_fingerprint failed", __func__);
2279 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
2280 sshkey_type(ctx->old_keys[i]), fp);
2281 free(fp);
2282 }
2283 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
djm@openbsd.orgf2293a62015-02-23 16:33:25 +00002284 if (get_saved_tio() != NULL) {
2285 leave_raw_mode(1);
2286 was_raw = 1;
2287 }
djm@openbsd.org523463a2015-02-16 22:13:32 +00002288 response = NULL;
2289 for (i = 0; !quit_pending && i < 3; i++) {
2290 free(response);
2291 response = read_passphrase("Accept updated hostkeys? "
2292 "(yes/no): ", RP_ECHO);
2293 if (strcasecmp(response, "yes") == 0)
2294 break;
2295 else if (quit_pending || response == NULL ||
2296 strcasecmp(response, "no") == 0) {
2297 options.update_hostkeys = 0;
2298 break;
2299 } else {
2300 do_log2(loglevel, "Please enter "
2301 "\"yes\" or \"no\"");
2302 }
2303 }
2304 if (quit_pending || i >= 3 || response == NULL)
2305 options.update_hostkeys = 0;
2306 free(response);
djm@openbsd.orgf2293a62015-02-23 16:33:25 +00002307 if (was_raw)
2308 enter_raw_mode(1);
djm@openbsd.org523463a2015-02-16 22:13:32 +00002309 }
2310
2311 /*
2312 * Now that all the keys are verified, we can go ahead and replace
2313 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
2314 * cancel the operation).
2315 */
2316 if (options.update_hostkeys != 0 &&
2317 (r = hostfile_replace_entries(options.user_hostfiles[0],
2318 ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
2319 options.hash_known_hosts, 0,
2320 options.fingerprint_hash)) != 0)
2321 error("%s: hostfile_replace_entries failed: %s",
2322 __func__, ssh_err(r));
2323}
2324
2325static void
2326client_global_hostkeys_private_confirm(int type, u_int32_t seq, void *_ctx)
2327{
2328 struct ssh *ssh = active_state; /* XXX */
2329 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2330 size_t i, ndone;
2331 struct sshbuf *signdata;
2332 int r;
2333 const u_char *sig;
2334 size_t siglen;
2335
2336 if (ctx->nnew == 0)
2337 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
2338 if (type != SSH2_MSG_REQUEST_SUCCESS) {
2339 error("Server failed to confirm ownership of "
2340 "private host keys");
2341 hostkeys_update_ctx_free(ctx);
2342 return;
2343 }
2344 if ((signdata = sshbuf_new()) == NULL)
2345 fatal("%s: sshbuf_new failed", __func__);
2346 /* Don't want to accidentally accept an unbound signature */
2347 if (ssh->kex->session_id_len == 0)
2348 fatal("%s: ssh->kex->session_id_len == 0", __func__);
2349 /*
2350 * Expect a signature for each of the ctx->nnew private keys we
2351 * haven't seen before. They will be in the same order as the
2352 * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
2353 */
2354 for (ndone = i = 0; i < ctx->nkeys; i++) {
2355 if (ctx->keys_seen[i])
2356 continue;
2357 /* Prepare data to be signed: session ID, unique string, key */
2358 sshbuf_reset(signdata);
djm@openbsd.org44732de2015-02-20 22:17:21 +00002359 if ( (r = sshbuf_put_cstring(signdata,
2360 "hostkeys-prove-00@openssh.com")) != 0 ||
2361 (r = sshbuf_put_string(signdata, ssh->kex->session_id,
djm@openbsd.org523463a2015-02-16 22:13:32 +00002362 ssh->kex->session_id_len)) != 0 ||
djm@openbsd.org523463a2015-02-16 22:13:32 +00002363 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
2364 fatal("%s: failed to prepare signature: %s",
2365 __func__, ssh_err(r));
2366 /* Extract and verify signature */
2367 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
2368 error("%s: couldn't parse message: %s",
2369 __func__, ssh_err(r));
2370 goto out;
2371 }
2372 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
2373 sshbuf_ptr(signdata), sshbuf_len(signdata), 0)) != 0) {
2374 error("%s: server gave bad signature for %s key %zu",
2375 __func__, sshkey_type(ctx->keys[i]), i);
2376 goto out;
2377 }
2378 /* Key is good. Mark it as 'seen' */
2379 ctx->keys_seen[i] = 2;
2380 ndone++;
2381 }
2382 if (ndone != ctx->nnew)
2383 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
2384 ndone, ctx->nnew); /* Shouldn't happen */
2385 ssh_packet_check_eom(ssh);
2386
2387 /* Make the edits to known_hosts */
2388 update_known_hosts(ctx);
2389 out:
2390 hostkeys_update_ctx_free(ctx);
2391}
2392
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002393/*
djm@openbsd.org894221a2017-03-10 05:01:13 +00002394 * Returns non-zero if the key is accepted by HostkeyAlgorithms.
2395 * Made slightly less trivial by the multiple RSA signature algorithm names.
2396 */
2397static int
2398key_accepted_by_hostkeyalgs(const struct sshkey *key)
2399{
2400 const char *ktype = sshkey_ssh_name(key);
2401 const char *hostkeyalgs = options.hostkeyalgorithms != NULL ?
2402 options.hostkeyalgorithms : KEX_DEFAULT_PK_ALG;
2403
2404 if (key == NULL || key->type == KEY_UNSPEC)
2405 return 0;
2406 if (key->type == KEY_RSA &&
2407 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
2408 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
2409 return 1;
2410 return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
2411}
2412
2413/*
djm@openbsd.org44732de2015-02-20 22:17:21 +00002414 * Handle hostkeys-00@openssh.com global request to inform the client of all
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002415 * the server's hostkeys. The keys are checked against the user's
2416 * HostkeyAlgorithms preference before they are accepted.
2417 */
2418static int
2419client_input_hostkeys(void)
2420{
djm@openbsd.org523463a2015-02-16 22:13:32 +00002421 struct ssh *ssh = active_state; /* XXX */
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002422 const u_char *blob = NULL;
djm@openbsd.org523463a2015-02-16 22:13:32 +00002423 size_t i, len = 0;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002424 struct sshbuf *buf = NULL;
djm@openbsd.org523463a2015-02-16 22:13:32 +00002425 struct sshkey *key = NULL, **tmp;
2426 int r;
2427 char *fp;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002428 static int hostkeys_seen = 0; /* XXX use struct ssh */
djm@openbsd.org6c5c9492015-02-16 22:08:57 +00002429 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
djm@openbsd.orga63cfa22015-02-25 19:54:02 +00002430 struct hostkeys_update_ctx *ctx = NULL;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002431
2432 if (hostkeys_seen)
2433 fatal("%s: server already sent hostkeys", __func__);
djm@openbsd.org523463a2015-02-16 22:13:32 +00002434 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2435 options.batch_mode)
2436 return 1; /* won't ask in batchmode, so don't even try */
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002437 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2438 return 1;
djm@openbsd.orga63cfa22015-02-25 19:54:02 +00002439
2440 ctx = xcalloc(1, sizeof(*ctx));
djm@openbsd.org523463a2015-02-16 22:13:32 +00002441 while (ssh_packet_remaining(ssh) > 0) {
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002442 sshkey_free(key);
2443 key = NULL;
djm@openbsd.org523463a2015-02-16 22:13:32 +00002444 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2445 error("%s: couldn't parse message: %s",
2446 __func__, ssh_err(r));
2447 goto out;
2448 }
djm@openbsd.org44732de2015-02-20 22:17:21 +00002449 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2450 error("%s: parse key: %s", __func__, ssh_err(r));
2451 goto out;
2452 }
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002453 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2454 SSH_FP_DEFAULT);
2455 debug3("%s: received %s key %s", __func__,
2456 sshkey_type(key), fp);
2457 free(fp);
markus@openbsd.org3a1638d2015-07-10 06:21:53 +00002458
djm@openbsd.org894221a2017-03-10 05:01:13 +00002459 if (!key_accepted_by_hostkeyalgs(key)) {
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002460 debug3("%s: %s key not permitted by HostkeyAlgorithms",
2461 __func__, sshkey_ssh_name(key));
2462 continue;
2463 }
djm@openbsd.org523463a2015-02-16 22:13:32 +00002464 /* Skip certs */
2465 if (sshkey_is_cert(key)) {
2466 debug3("%s: %s key is a certificate; skipping",
2467 __func__, sshkey_ssh_name(key));
2468 continue;
2469 }
2470 /* Ensure keys are unique */
2471 for (i = 0; i < ctx->nkeys; i++) {
2472 if (sshkey_equal(key, ctx->keys[i])) {
2473 error("%s: received duplicated %s host key",
2474 __func__, sshkey_ssh_name(key));
2475 goto out;
2476 }
2477 }
2478 /* Key is good, record it */
2479 if ((tmp = reallocarray(ctx->keys, ctx->nkeys + 1,
2480 sizeof(*ctx->keys))) == NULL)
2481 fatal("%s: reallocarray failed nkeys = %zu",
2482 __func__, ctx->nkeys);
2483 ctx->keys = tmp;
2484 ctx->keys[ctx->nkeys++] = key;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002485 key = NULL;
2486 }
2487
djm@openbsd.org523463a2015-02-16 22:13:32 +00002488 if (ctx->nkeys == 0) {
djm@openbsd.org44732de2015-02-20 22:17:21 +00002489 debug("%s: server sent no hostkeys", __func__);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002490 goto out;
2491 }
djm@openbsd.org44732de2015-02-20 22:17:21 +00002492
djm@openbsd.org523463a2015-02-16 22:13:32 +00002493 if ((ctx->keys_seen = calloc(ctx->nkeys,
2494 sizeof(*ctx->keys_seen))) == NULL)
2495 fatal("%s: calloc failed", __func__);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002496
djm@openbsd.org6c5c9492015-02-16 22:08:57 +00002497 get_hostfile_hostname_ipaddr(host,
2498 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
djm@openbsd.org523463a2015-02-16 22:13:32 +00002499 options.port, &ctx->host_str,
2500 options.check_host_ip ? &ctx->ip_str : NULL);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002501
djm@openbsd.org523463a2015-02-16 22:13:32 +00002502 /* Find which keys we already know about. */
2503 if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2504 ctx, ctx->host_str, ctx->ip_str,
2505 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2506 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002507 goto out;
2508 }
2509
djm@openbsd.org523463a2015-02-16 22:13:32 +00002510 /* Figure out if we have any new keys to add */
2511 ctx->nnew = 0;
2512 for (i = 0; i < ctx->nkeys; i++) {
2513 if (!ctx->keys_seen[i])
2514 ctx->nnew++;
2515 }
2516
2517 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2518 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2519
2520 if (ctx->nnew == 0 && ctx->nold != 0) {
2521 /* We have some keys to remove. Just do it. */
2522 update_known_hosts(ctx);
2523 } else if (ctx->nnew != 0) {
2524 /*
2525 * We have received hitherto-unseen keys from the server.
2526 * Ask the server to confirm ownership of the private halves.
2527 */
2528 debug3("%s: asking server to prove ownership for %zu keys",
2529 __func__, ctx->nnew);
2530 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2531 (r = sshpkt_put_cstring(ssh,
djm@openbsd.org44732de2015-02-20 22:17:21 +00002532 "hostkeys-prove-00@openssh.com")) != 0 ||
djm@openbsd.org523463a2015-02-16 22:13:32 +00002533 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2534 fatal("%s: cannot prepare packet: %s",
2535 __func__, ssh_err(r));
2536 if ((buf = sshbuf_new()) == NULL)
2537 fatal("%s: sshbuf_new", __func__);
2538 for (i = 0; i < ctx->nkeys; i++) {
2539 if (ctx->keys_seen[i])
2540 continue;
2541 sshbuf_reset(buf);
2542 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2543 fatal("%s: sshkey_putb: %s",
2544 __func__, ssh_err(r));
2545 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2546 fatal("%s: sshpkt_put_string: %s",
2547 __func__, ssh_err(r));
2548 }
2549 if ((r = sshpkt_send(ssh)) != 0)
2550 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2551 client_register_global_confirm(
2552 client_global_hostkeys_private_confirm, ctx);
2553 ctx = NULL; /* will be freed in callback */
2554 }
2555
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002556 /* Success */
2557 out:
djm@openbsd.org523463a2015-02-16 22:13:32 +00002558 hostkeys_update_ctx_free(ctx);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002559 sshkey_free(key);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002560 sshbuf_free(buf);
djm@openbsd.org523463a2015-02-16 22:13:32 +00002561 /*
2562 * NB. Return success for all cases. The server doesn't need to know
2563 * what the client does with its hosts file.
2564 */
2565 return 1;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002566}
2567
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00002568static int
Damien Millerc3fa4072002-01-22 23:21:58 +11002569client_input_global_request(int type, u_int32_t seq, void *ctxt)
2570{
2571 char *rtype;
2572 int want_reply;
2573 int success = 0;
2574
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002575 rtype = packet_get_cstring(NULL);
Damien Millerc3fa4072002-01-22 23:21:58 +11002576 want_reply = packet_get_char();
Damien Miller509b0102003-12-17 16:33:10 +11002577 debug("client_input_global_request: rtype %s want_reply %d",
2578 rtype, want_reply);
djm@openbsd.org44732de2015-02-20 22:17:21 +00002579 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002580 success = client_input_hostkeys();
Damien Millerc3fa4072002-01-22 23:21:58 +11002581 if (want_reply) {
2582 packet_start(success ?
2583 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2584 packet_send();
2585 packet_write_wait();
2586 }
Darren Tuckera627d422013-06-02 07:31:17 +10002587 free(rtype);
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00002588 return 0;
Damien Millerc3fa4072002-01-22 23:21:58 +11002589}
Damien Millerbd483e72000-04-30 10:00:53 +10002590
Damien Miller0e220db2004-06-15 10:34:08 +10002591void
Darren Tuckerfc959702004-07-17 16:12:08 +10002592client_session2_setup(int id, int want_tty, int want_subsystem,
Damien Miller5771ed72008-05-19 15:35:33 +10002593 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
Damien Miller0e220db2004-06-15 10:34:08 +10002594{
2595 int len;
Darren Tucker5d78de62004-11-05 20:35:44 +11002596 Channel *c = NULL;
Damien Miller0e220db2004-06-15 10:34:08 +10002597
2598 debug2("%s: id %d", __func__, id);
2599
Darren Tucker5d78de62004-11-05 20:35:44 +11002600 if ((c = channel_lookup(id)) == NULL)
2601 fatal("client_session2_setup: channel %d: unknown channel", id);
2602
Damien Miller0dac6fb2010-11-20 15:19:38 +11002603 packet_set_interactive(want_tty,
2604 options.ip_qos_interactive, options.ip_qos_bulk);
2605
Damien Miller0e220db2004-06-15 10:34:08 +10002606 if (want_tty) {
2607 struct winsize ws;
Damien Miller0e220db2004-06-15 10:34:08 +10002608
2609 /* Store window size in the packet. */
2610 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2611 memset(&ws, 0, sizeof(ws));
2612
Damien Miller5771ed72008-05-19 15:35:33 +10002613 channel_request_start(id, "pty-req", 1);
Damien Miller555f3b82011-05-15 08:48:05 +10002614 client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
Damien Miller0e220db2004-06-15 10:34:08 +10002615 packet_put_cstring(term != NULL ? term : "");
Damien Miller71a73672006-03-26 14:04:36 +11002616 packet_put_int((u_int)ws.ws_col);
2617 packet_put_int((u_int)ws.ws_row);
2618 packet_put_int((u_int)ws.ws_xpixel);
2619 packet_put_int((u_int)ws.ws_ypixel);
Darren Tuckerdf189fb2008-06-08 12:55:32 +10002620 if (tiop == NULL)
2621 tiop = get_saved_tio();
2622 tty_make_modes(-1, tiop);
Damien Miller0e220db2004-06-15 10:34:08 +10002623 packet_send();
2624 /* XXX wait for reply */
Darren Tucker5d78de62004-11-05 20:35:44 +11002625 c->client_tty = 1;
Damien Miller0e220db2004-06-15 10:34:08 +10002626 }
2627
2628 /* Transfer any environment variables from client to server */
Damien Miller3756dce2004-06-18 01:17:29 +10002629 if (options.num_send_env != 0 && env != NULL) {
Damien Miller0e220db2004-06-15 10:34:08 +10002630 int i, j, matched;
Damien Miller0e220db2004-06-15 10:34:08 +10002631 char *name, *val;
2632
2633 debug("Sending environment.");
Damien Miller3756dce2004-06-18 01:17:29 +10002634 for (i = 0; env[i] != NULL; i++) {
Damien Miller0e220db2004-06-15 10:34:08 +10002635 /* Split */
Damien Miller3756dce2004-06-18 01:17:29 +10002636 name = xstrdup(env[i]);
Damien Miller0e220db2004-06-15 10:34:08 +10002637 if ((val = strchr(name, '=')) == NULL) {
Darren Tuckera627d422013-06-02 07:31:17 +10002638 free(name);
Damien Miller0e220db2004-06-15 10:34:08 +10002639 continue;
2640 }
2641 *val++ = '\0';
2642
2643 matched = 0;
2644 for (j = 0; j < options.num_send_env; j++) {
2645 if (match_pattern(name, options.send_env[j])) {
2646 matched = 1;
2647 break;
2648 }
2649 }
2650 if (!matched) {
2651 debug3("Ignored env %s", name);
Darren Tuckera627d422013-06-02 07:31:17 +10002652 free(name);
Damien Miller0e220db2004-06-15 10:34:08 +10002653 continue;
2654 }
2655
2656 debug("Sending env %s = %s", name, val);
2657 channel_request_start(id, "env", 0);
2658 packet_put_cstring(name);
2659 packet_put_cstring(val);
2660 packet_send();
Darren Tuckera627d422013-06-02 07:31:17 +10002661 free(name);
Damien Miller0e220db2004-06-15 10:34:08 +10002662 }
2663 }
2664
2665 len = buffer_len(cmd);
2666 if (len > 0) {
2667 if (len > 900)
2668 len = 900;
2669 if (want_subsystem) {
Damien Miller5771ed72008-05-19 15:35:33 +10002670 debug("Sending subsystem: %.*s",
2671 len, (u_char*)buffer_ptr(cmd));
2672 channel_request_start(id, "subsystem", 1);
Damien Miller555f3b82011-05-15 08:48:05 +10002673 client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
Damien Miller0e220db2004-06-15 10:34:08 +10002674 } else {
Damien Miller5771ed72008-05-19 15:35:33 +10002675 debug("Sending command: %.*s",
2676 len, (u_char*)buffer_ptr(cmd));
2677 channel_request_start(id, "exec", 1);
Damien Miller555f3b82011-05-15 08:48:05 +10002678 client_expect_confirm(id, "exec", CONFIRM_CLOSE);
Damien Miller0e220db2004-06-15 10:34:08 +10002679 }
2680 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2681 packet_send();
2682 } else {
Damien Miller5771ed72008-05-19 15:35:33 +10002683 channel_request_start(id, "shell", 1);
Damien Miller555f3b82011-05-15 08:48:05 +10002684 client_expect_confirm(id, "shell", CONFIRM_CLOSE);
Damien Miller0e220db2004-06-15 10:34:08 +10002685 packet_send();
2686 }
2687}
2688
Ben Lindstrombba81212001-06-25 05:01:22 +00002689static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +00002690client_init_dispatch_20(void)
Damien Miller1383bd82000-04-06 12:32:37 +10002691{
Ben Lindstrom8ac91062001-04-04 17:57:54 +00002692 dispatch_init(&dispatch_protocol_error);
Damien Miller2797f7f2002-04-23 21:09:44 +10002693
Damien Miller1383bd82000-04-06 12:32:37 +10002694 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2695 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2696 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2697 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
Damien Millerbd483e72000-04-30 10:00:53 +10002698 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
Damien Miller1383bd82000-04-06 12:32:37 +10002699 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2700 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
Ben Lindstrom5b828322001-02-09 01:34:36 +00002701 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
Damien Miller1383bd82000-04-06 12:32:37 +10002702 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
Damien Millerb84886b2008-05-19 15:05:07 +10002703 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2704 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
Damien Millerc3fa4072002-01-22 23:21:58 +11002705 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
Ben Lindstrom8ac91062001-04-04 17:57:54 +00002706
2707 /* rekeying */
2708 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
Damien Miller2797f7f2002-04-23 21:09:44 +10002709
2710 /* global request reply messages */
2711 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2712 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
Damien Miller1383bd82000-04-06 12:32:37 +10002713}
Darren Tucker4d5cd332008-06-13 04:51:14 +10002714
Ben Lindstrombba81212001-06-25 05:01:22 +00002715static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +00002716client_init_dispatch_13(void)
Damien Millerb38eff82000-04-01 11:09:21 +10002717{
2718 dispatch_init(NULL);
2719 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2720 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2721 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
Damien Millerb38eff82000-04-01 11:09:21 +10002722 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2723 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2724 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
Damien Millerb38eff82000-04-01 11:09:21 +10002725 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2726 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2727 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
Damien Miller69b69aa2000-10-28 14:19:58 +11002728
2729 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
Darren Tucker5dcdd212003-10-02 16:17:00 +10002730 &client_input_agent_open : &deny_input_open);
Damien Miller69b69aa2000-10-28 14:19:58 +11002731 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2732 &x11_input_open : &deny_input_open);
Damien Millerb38eff82000-04-01 11:09:21 +10002733}
Darren Tucker4d5cd332008-06-13 04:51:14 +10002734
Ben Lindstrombba81212001-06-25 05:01:22 +00002735static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +00002736client_init_dispatch_15(void)
Damien Millerb38eff82000-04-01 11:09:21 +10002737{
2738 client_init_dispatch_13();
2739 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2740 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2741}
Darren Tucker4d5cd332008-06-13 04:51:14 +10002742
Ben Lindstromdb47f382001-07-04 05:10:27 +00002743static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +00002744client_init_dispatch(void)
Damien Millerb38eff82000-04-01 11:09:21 +10002745{
Damien Miller1383bd82000-04-06 12:32:37 +10002746 if (compat20)
2747 client_init_dispatch_20();
2748 else if (compat13)
Damien Millerb38eff82000-04-01 11:09:21 +10002749 client_init_dispatch_13();
2750 else
2751 client_init_dispatch_15();
2752}
Darren Tucker9a2c4cd2003-09-22 21:16:05 +10002753
Damien Miller6c3eec72011-05-05 14:16:22 +10002754void
2755client_stop_mux(void)
2756{
2757 if (options.control_path != NULL && muxserver_sock != -1)
2758 unlink(options.control_path);
2759 /*
Darren Tucker48bf4b02012-09-07 16:38:53 +10002760 * If we are in persist mode, or don't have a shell, signal that we
2761 * should close when all active channels are closed.
Damien Miller6c3eec72011-05-05 14:16:22 +10002762 */
Darren Tucker48bf4b02012-09-07 16:38:53 +10002763 if (options.control_persist || no_shell_flag) {
Damien Miller6c3eec72011-05-05 14:16:22 +10002764 session_closed = 1;
Damien Miller4ac99c32011-06-20 14:43:31 +10002765 setproctitle("[stopped mux]");
2766 }
Damien Miller6c3eec72011-05-05 14:16:22 +10002767}
2768
Darren Tucker9a2c4cd2003-09-22 21:16:05 +10002769/* client specific fatal cleanup */
2770void
Darren Tucker3e33cec2003-10-02 16:12:36 +10002771cleanup_exit(int i)
Darren Tucker9a2c4cd2003-09-22 21:16:05 +10002772{
Damien Miller21771e22011-05-15 08:45:50 +10002773 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Darren Tucker9a2c4cd2003-09-22 21:16:05 +10002774 leave_non_blocking();
Damien Millerb1cbfa22008-05-19 16:00:08 +10002775 if (options.control_path != NULL && muxserver_sock != -1)
Damien Miller0e220db2004-06-15 10:34:08 +10002776 unlink(options.control_path);
Damien Millera41ccca2010-10-07 22:07:32 +11002777 ssh_kill_proxy_command();
Darren Tucker3e33cec2003-10-02 16:12:36 +10002778 _exit(i);
Darren Tucker9a2c4cd2003-09-22 21:16:05 +10002779}