blob: 367b682fff10959b47b999cd394d9a983ab16fe2 [file] [log] [blame]
naddy@openbsd.org768405f2017-05-03 21:08:09 +00001/* $OpenBSD: clientloop.c,v 1.296 2017/05/03 21:08:09 naddy 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 "ssh2.h"
Damien Millerd4a8b7e1999-10-27 13:42:43 +100093#include "packet.h"
94#include "buffer.h"
Damien Millerb38eff82000-04-01 11:09:21 +100095#include "compat.h"
Ben Lindstromc7637672001-06-09 00:36:26 +000096#include "channels.h"
Damien Millerb38eff82000-04-01 11:09:21 +100097#include "dispatch.h"
Damien Miller0bc1bd82000-11-13 22:57:25 +110098#include "key.h"
Damien Millerd7834352006-08-05 12:39:39 +100099#include "cipher.h"
Ben Lindstromf28f6342001-04-04 02:03:04 +0000100#include "kex.h"
markus@openbsd.org3a1638d2015-07-10 06:21:53 +0000101#include "myproposal.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +0000102#include "log.h"
Damien Miller7acefbb2014-07-18 14:11:24 +1000103#include "misc.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +0000104#include "readconf.h"
Ben Lindstrombf555ba2001-01-18 02:04:35 +0000105#include "clientloop.h"
Damien Milleraeb31d62005-12-13 19:29:36 +1100106#include "sshconnect.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +0000107#include "authfd.h"
108#include "atomicio.h"
Darren Tucker06f2bd82004-05-13 16:06:46 +1000109#include "sshpty.h"
Damien Miller0e220db2004-06-15 10:34:08 +1000110#include "match.h"
111#include "msg.h"
djm@openbsd.org141efe42015-01-14 20:05:27 +0000112#include "ssherr.h"
djm@openbsd.org8d4f8722015-01-26 03:04:45 +0000113#include "hostfile.h"
Damien Miller69b69aa2000-10-28 14:19:58 +1100114
115/* import options */
116extern Options options;
117
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000118/* Flag indicating that stdin should be redirected from /dev/null. */
119extern int stdin_null_flag;
120
Damien Millerd6965512003-12-17 16:31:53 +1100121/* Flag indicating that no shell has been requested */
122extern int no_shell_flag;
123
djm@openbsd.org368dd972016-07-23 02:54:08 +0000124/* Flag indicating that ssh should daemonise after authentication is complete */
125extern int fork_after_authentication_flag;
126
Damien Miller0e220db2004-06-15 10:34:08 +1000127/* Control socket */
Damien Millere1537f92010-01-26 13:26:22 +1100128extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
Damien Miller0e220db2004-06-15 10:34:08 +1000129
Damien Miller5428f641999-11-25 11:54:57 +1100130/*
131 * Name of the host we are connecting to. This is the name given on the
132 * command line, or the HostName specified for the user-supplied name in a
133 * configuration file.
134 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000135extern char *host;
136
Damien Miller5428f641999-11-25 11:54:57 +1100137/*
138 * Flag to indicate that we have received a window change signal which has
139 * not yet been processed. This will cause a message indicating the new
140 * window size to be sent to the server a little later. This is volatile
141 * because this is updated in a signal handler.
142 */
Ben Lindstrom5e71c542001-12-06 16:48:14 +0000143static volatile sig_atomic_t received_window_change_signal = 0;
144static volatile sig_atomic_t received_signal = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000145
Damien Miller788f2122005-11-05 15:14:59 +1100146/* Flag indicating whether the user's terminal is in non-blocking mode. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000147static int in_non_blocking_mode = 0;
148
Damien Millere11e1ea2010-08-03 16:04:46 +1000149/* Time when backgrounded control master using ControlPersist should exit */
150static time_t control_persist_exit_time = 0;
151
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000152/* Common data for the client loop code. */
Damien Millere1537f92010-01-26 13:26:22 +1100153volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
Damien Miller95def091999-11-25 00:26:21 +1100154static int last_was_cr; /* Last character was a newline. */
Darren Tucker4d5cd332008-06-13 04:51:14 +1000155static int exit_status; /* Used to store the command exit status. */
djm@openbsd.org05164352017-04-30 23:21:54 +0000156static Buffer stderr_buffer; /* Used for final exit message. */
Damien Miller95def091999-11-25 00:26:21 +1100157static int connection_in; /* Connection to server (input). */
158static int connection_out; /* Connection to server (output). */
Ben Lindstrombe2cc432001-04-04 23:46:07 +0000159static int need_rekeying; /* Set to non-zero if rekeying is requested. */
Damien Miller1ab6a512010-06-26 10:02:24 +1000160static int session_closed; /* In SSH2: login session closed. */
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000161static u_int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000162
Ben Lindstrombba81212001-06-25 05:01:22 +0000163static void client_init_dispatch(void);
Damien Miller1383bd82000-04-06 12:32:37 +1000164int session_ident = -1;
165
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000166/* Track escape per proto2 channel */
167struct escape_filter_ctx {
168 int escape_pending;
169 int escape_char;
170};
171
172/* Context for channel confirmation replies */
Damien Miller5771ed72008-05-19 15:35:33 +1000173struct channel_reply_ctx {
174 const char *request_type;
Damien Miller555f3b82011-05-15 08:48:05 +1000175 int id;
176 enum confirm_action action;
Damien Miller5771ed72008-05-19 15:35:33 +1000177};
178
Darren Tucker9f407c42008-06-13 04:50:27 +1000179/* Global request success/failure callbacks */
180struct global_confirm {
181 TAILQ_ENTRY(global_confirm) entry;
182 global_confirm_cb *cb;
183 void *ctx;
184 int ref_count;
185};
186TAILQ_HEAD(global_confirms, global_confirm);
187static struct global_confirms global_confirms =
188 TAILQ_HEAD_INITIALIZER(global_confirms);
189
Damien Miller0e220db2004-06-15 10:34:08 +1000190void ssh_process_session2_setup(int, int, int, Buffer *);
191
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000192/* Restores stdin to blocking mode. */
193
Ben Lindstrombba81212001-06-25 05:01:22 +0000194static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +0000195leave_non_blocking(void)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000196{
Damien Miller95def091999-11-25 00:26:21 +1100197 if (in_non_blocking_mode) {
Damien Miller03e66f62004-06-15 15:47:51 +1000198 unset_nonblock(fileno(stdin));
Damien Miller95def091999-11-25 00:26:21 +1100199 in_non_blocking_mode = 0;
Damien Miller95def091999-11-25 00:26:21 +1100200 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000201}
202
Damien Miller5428f641999-11-25 11:54:57 +1100203/*
204 * Signal handler for the window change signal (SIGWINCH). This just sets a
205 * flag indicating that the window has changed.
206 */
Damien Millerf0b15df2006-03-26 13:59:20 +1100207/*ARGSUSED */
Ben Lindstrombba81212001-06-25 05:01:22 +0000208static void
Damien Miller95def091999-11-25 00:26:21 +1100209window_change_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000210{
Damien Miller95def091999-11-25 00:26:21 +1100211 received_window_change_signal = 1;
212 signal(SIGWINCH, window_change_handler);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000213}
214
Damien Miller5428f641999-11-25 11:54:57 +1100215/*
216 * Signal handler for signals that cause the program to terminate. These
217 * signals must be trapped to restore terminal modes.
218 */
Damien Millerf0b15df2006-03-26 13:59:20 +1100219/*ARGSUSED */
Ben Lindstrombba81212001-06-25 05:01:22 +0000220static void
Damien Miller95def091999-11-25 00:26:21 +1100221signal_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000222{
Ben Lindstromec46e0b2001-06-09 01:27:31 +0000223 received_signal = sig;
224 quit_pending = 1;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000225}
226
Damien Miller5428f641999-11-25 11:54:57 +1100227/*
228 * Returns current time in seconds from Jan 1, 1970 with the maximum
229 * available resolution.
230 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000231
Ben Lindstrombba81212001-06-25 05:01:22 +0000232static double
Ben Lindstrom31ca54a2001-02-09 02:11:24 +0000233get_current_time(void)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000234{
Damien Miller95def091999-11-25 00:26:21 +1100235 struct timeval tv;
236 gettimeofday(&tv, NULL);
237 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000238}
239
Damien Millere11e1ea2010-08-03 16:04:46 +1000240/*
241 * Sets control_persist_exit_time to the absolute time when the
242 * backgrounded control master should exit due to expiry of the
243 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
244 * control master process, or if there is no ControlPersist timeout.
245 */
246static void
247set_control_persist_exit_time(void)
248{
249 if (muxserver_sock == -1 || !options.control_persist
Damien Miller6c3eec72011-05-05 14:16:22 +1000250 || options.control_persist_timeout == 0) {
Damien Millere11e1ea2010-08-03 16:04:46 +1000251 /* not using a ControlPersist timeout */
252 control_persist_exit_time = 0;
Damien Miller6c3eec72011-05-05 14:16:22 +1000253 } else if (channel_still_open()) {
Damien Millere11e1ea2010-08-03 16:04:46 +1000254 /* some client connections are still open */
255 if (control_persist_exit_time > 0)
256 debug2("%s: cancel scheduled exit", __func__);
257 control_persist_exit_time = 0;
258 } else if (control_persist_exit_time <= 0) {
259 /* a client connection has recently closed */
Darren Tuckerb759c9c2013-06-02 07:46:16 +1000260 control_persist_exit_time = monotime() +
Damien Millere11e1ea2010-08-03 16:04:46 +1000261 (time_t)options.control_persist_timeout;
262 debug2("%s: schedule exit in %d seconds", __func__,
263 options.control_persist_timeout);
264 }
265 /* else we are already counting down to the timeout */
266}
267
Damien Miller8d60be52012-02-11 08:18:17 +1100268#define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
269static int
270client_x11_display_valid(const char *display)
271{
272 size_t i, dlen;
273
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000274 if (display == NULL)
275 return 0;
276
Damien Miller8d60be52012-02-11 08:18:17 +1100277 dlen = strlen(display);
278 for (i = 0; i < dlen; i++) {
Damien Millerfdb23062013-11-21 13:57:15 +1100279 if (!isalnum((u_char)display[i]) &&
Damien Miller8d60be52012-02-11 08:18:17 +1100280 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
281 debug("Invalid character '%c' in DISPLAY", display[i]);
282 return 0;
283 }
284 }
285 return 1;
286}
287
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000288#define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
289#define X11_TIMEOUT_SLACK 60
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000290int
Damien Miller17e7ed02005-06-17 12:54:33 +1000291client_x11_get_proto(const char *display, const char *xauth_path,
Damien Miller1ab6a512010-06-26 10:02:24 +1000292 u_int trusted, u_int timeout, char **_proto, char **_data)
Damien Miller17e7ed02005-06-17 12:54:33 +1000293{
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000294 char cmd[1024], line[512], xdisplay[512];
295 char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
Damien Miller17e7ed02005-06-17 12:54:33 +1000296 static char proto[512], data[512];
297 FILE *f;
tedu@openbsd.org10363562016-09-17 18:00:27 +0000298 int got_data = 0, generated = 0, do_unlink = 0, r;
Damien Miller17e7ed02005-06-17 12:54:33 +1000299 struct stat st;
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000300 u_int now, x11_timeout_real;
Damien Miller17e7ed02005-06-17 12:54:33 +1000301
Damien Miller17e7ed02005-06-17 12:54:33 +1000302 *_proto = proto;
303 *_data = data;
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000304 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
Damien Miller17e7ed02005-06-17 12:54:33 +1000305
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000306 if (!client_x11_display_valid(display)) {
millert@openbsd.org5658ef22016-02-01 21:18:17 +0000307 if (display != NULL)
308 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
309 display);
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000310 return -1;
311 }
312 if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
313 debug("No xauth program.");
314 xauth_path = NULL;
315 }
316
317 if (xauth_path != NULL) {
Damien Miller17e7ed02005-06-17 12:54:33 +1000318 /*
319 * Handle FamilyLocal case where $DISPLAY does
320 * not match an authorization entry. For this we
321 * just try "xauth list unix:displaynum.screennum".
322 * XXX: "localhost" match to determine FamilyLocal
323 * is not perfect.
324 */
325 if (strncmp(display, "localhost:", 10) == 0) {
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000326 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
327 display + 10)) < 0 ||
328 (size_t)r >= sizeof(xdisplay)) {
329 error("%s: display name too long", __func__);
330 return -1;
331 }
Damien Miller17e7ed02005-06-17 12:54:33 +1000332 display = xdisplay;
333 }
334 if (trusted == 0) {
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000335 /*
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000336 * Generate an untrusted X11 auth cookie.
337 *
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000338 * The authentication cookie should briefly outlive
339 * ssh's willingness to forward X11 connections to
340 * avoid nasty fail-open behaviour in the X server.
341 */
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000342 mktemp_proto(xauthdir, sizeof(xauthdir));
343 if (mkdtemp(xauthdir) == NULL) {
344 error("%s: mkdtemp: %s",
345 __func__, strerror(errno));
346 return -1;
347 }
348 do_unlink = 1;
349 if ((r = snprintf(xauthfile, sizeof(xauthfile),
350 "%s/xauthfile", xauthdir)) < 0 ||
351 (size_t)r >= sizeof(xauthfile)) {
352 error("%s: xauthfile path too long", __func__);
353 unlink(xauthfile);
354 rmdir(xauthdir);
355 return -1;
356 }
357
djm@openbsd.org1bf477d2015-07-01 02:26:31 +0000358 if (timeout >= UINT_MAX - X11_TIMEOUT_SLACK)
359 x11_timeout_real = UINT_MAX;
360 else
361 x11_timeout_real = timeout + X11_TIMEOUT_SLACK;
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000362 if ((r = snprintf(cmd, sizeof(cmd),
363 "%s -f %s generate %s " SSH_X11_PROTO
364 " untrusted timeout %u 2>" _PATH_DEVNULL,
365 xauth_path, xauthfile, display,
366 x11_timeout_real)) < 0 ||
367 (size_t)r >= sizeof(cmd))
368 fatal("%s: cmd too long", __func__);
369 debug2("%s: %s", __func__, cmd);
370 if (x11_refuse_time == 0) {
371 now = monotime() + 1;
372 if (UINT_MAX - timeout < now)
373 x11_refuse_time = UINT_MAX;
374 else
375 x11_refuse_time = now + timeout;
376 channel_set_x11_refuse_time(x11_refuse_time);
Damien Miller17e7ed02005-06-17 12:54:33 +1000377 }
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000378 if (system(cmd) == 0)
379 generated = 1;
Damien Miller17e7ed02005-06-17 12:54:33 +1000380 }
Darren Tucker513d13a2007-08-15 19:13:41 +1000381
382 /*
383 * When in untrusted mode, we read the cookie only if it was
384 * successfully generated as an untrusted one in the step
385 * above.
386 */
387 if (trusted || generated) {
388 snprintf(cmd, sizeof(cmd),
389 "%s %s%s list %s 2>" _PATH_DEVNULL,
390 xauth_path,
391 generated ? "-f " : "" ,
392 generated ? xauthfile : "",
393 display);
394 debug2("x11_get_proto: %s", cmd);
395 f = popen(cmd, "r");
396 if (f && fgets(line, sizeof(line), f) &&
397 sscanf(line, "%*s %511s %511s", proto, data) == 2)
398 got_data = 1;
399 if (f)
400 pclose(f);
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000401 }
Damien Miller17e7ed02005-06-17 12:54:33 +1000402 }
403
404 if (do_unlink) {
405 unlink(xauthfile);
406 rmdir(xauthdir);
407 }
Damien Miller17e7ed02005-06-17 12:54:33 +1000408
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000409 /* Don't fall back to fake X11 data for untrusted forwarding */
410 if (!trusted && !got_data) {
411 error("Warning: untrusted X11 forwarding setup failed: "
412 "xauth key data not generated");
413 return -1;
414 }
415
Damien Miller17e7ed02005-06-17 12:54:33 +1000416 /*
417 * If we didn't get authentication data, just make up some
418 * data. The forwarding code will check the validity of the
419 * response anyway, and substitute this data. The X11
420 * server, however, will ignore this fake data and use
421 * whatever authentication mechanisms it was using otherwise
422 * for the local connection.
423 */
424 if (!got_data) {
tedu@openbsd.org10363562016-09-17 18:00:27 +0000425 u_int8_t rnd[16];
426 u_int i;
Damien Miller17e7ed02005-06-17 12:54:33 +1000427
428 logit("Warning: No xauth data; "
429 "using fake authentication data for X11 forwarding.");
430 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
tedu@openbsd.org10363562016-09-17 18:00:27 +0000431 arc4random_buf(rnd, sizeof(rnd));
432 for (i = 0; i < sizeof(rnd); i++) {
Damien Miller17e7ed02005-06-17 12:54:33 +1000433 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
tedu@openbsd.org10363562016-09-17 18:00:27 +0000434 rnd[i]);
Damien Miller17e7ed02005-06-17 12:54:33 +1000435 }
436 }
djm@openbsd.orged4ce822016-01-13 23:04:47 +0000437
438 return 0;
Damien Miller17e7ed02005-06-17 12:54:33 +1000439}
440
Damien Miller5428f641999-11-25 11:54:57 +1100441/*
Damien Miller5428f641999-11-25 11:54:57 +1100442 * Checks if the client window has changed, and sends a packet about it to
443 * the server if so. The actual change is detected elsewhere (by a software
444 * interrupt on Unix); this just checks the flag and sends a message if
445 * appropriate.
446 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000447
Ben Lindstrombba81212001-06-25 05:01:22 +0000448static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +0000449client_check_window_change(void)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000450{
djm@openbsd.org97f4d302017-04-30 23:13:25 +0000451 if (!received_window_change_signal)
Damien Miller1383bd82000-04-06 12:32:37 +1000452 return;
453 /** XXX race */
454 received_window_change_signal = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000455
djm@openbsd.org97f4d302017-04-30 23:13:25 +0000456 debug2("%s: changed", __func__);
Damien Miller1383bd82000-04-06 12:32:37 +1000457
djm@openbsd.org97f4d302017-04-30 23:13:25 +0000458 channel_send_window_changes();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000459}
460
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +0000461static int
Damien Miller509b0102003-12-17 16:33:10 +1100462client_global_request_reply(int type, u_int32_t seq, void *ctxt)
463{
Darren Tucker9f407c42008-06-13 04:50:27 +1000464 struct global_confirm *gc;
465
466 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +0000467 return 0;
Darren Tucker9f407c42008-06-13 04:50:27 +1000468 if (gc->cb != NULL)
469 gc->cb(type, seq, gc->ctx);
470 if (--gc->ref_count <= 0) {
471 TAILQ_REMOVE(&global_confirms, gc, entry);
Damien Miller1d2c4562014-02-04 11:18:20 +1100472 explicit_bzero(gc, sizeof(*gc));
Darren Tuckera627d422013-06-02 07:31:17 +1000473 free(gc);
Darren Tucker9f407c42008-06-13 04:50:27 +1000474 }
475
Darren Tuckerf7288d72009-06-21 18:12:20 +1000476 packet_set_alive_timeouts(0);
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +0000477 return 0;
Damien Miller509b0102003-12-17 16:33:10 +1100478}
479
480static void
481server_alive_check(void)
482{
Darren Tuckerf7288d72009-06-21 18:12:20 +1000483 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
Damien Millerb73b6fd2011-01-11 17:18:56 +1100484 logit("Timeout, server %s not responding.", host);
Damien Miller985a4482006-10-24 03:02:41 +1000485 cleanup_exit(255);
486 }
Damien Miller509b0102003-12-17 16:33:10 +1100487 packet_start(SSH2_MSG_GLOBAL_REQUEST);
488 packet_put_cstring("keepalive@openssh.com");
489 packet_put_char(1); /* boolean: want reply */
490 packet_send();
Darren Tucker9f407c42008-06-13 04:50:27 +1000491 /* Insert an empty placeholder to maintain ordering */
492 client_register_global_confirm(NULL, NULL);
Damien Miller509b0102003-12-17 16:33:10 +1100493}
494
Damien Miller5428f641999-11-25 11:54:57 +1100495/*
496 * Waits until the client can do something (some data becomes available on
497 * one of the file descriptors).
498 */
Ben Lindstrombba81212001-06-25 05:01:22 +0000499static void
Damien Miller5e953212001-01-30 09:14:00 +1100500client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
Darren Tuckerc7a6fc42004-08-13 21:18:00 +1000501 int *maxfdp, u_int *nallocp, int rekeying)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000502{
Damien Miller509b0102003-12-17 16:33:10 +1100503 struct timeval tv, *tvp;
Damien Millere11e1ea2010-08-03 16:04:46 +1000504 int timeout_secs;
Darren Tuckerb759c9c2013-06-02 07:46:16 +1000505 time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
Damien Miller509b0102003-12-17 16:33:10 +1100506 int ret;
507
Damien Miller5e953212001-01-30 09:14:00 +1100508 /* Add any selections by the channel mechanism. */
Damien Millera6508752012-04-22 11:21:10 +1000509 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
510 &minwait_secs, rekeying);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000511
djm@openbsd.org97f4d302017-04-30 23:13:25 +0000512 /* channel_prepare_select could have closed the last channel */
513 if (session_closed && !channel_still_open() &&
514 !packet_have_data_to_write()) {
515 /* clear mask since we did not call select() */
516 memset(*readsetp, 0, *nallocp);
517 memset(*writesetp, 0, *nallocp);
518 return;
Damien Miller1383bd82000-04-06 12:32:37 +1000519 }
520
djm@openbsd.org05164352017-04-30 23:21:54 +0000521 FD_SET(connection_in, *readsetp);
522
Damien Miller95def091999-11-25 00:26:21 +1100523 /* Select server connection if have data to write to the server. */
524 if (packet_have_data_to_write())
Damien Miller5e953212001-01-30 09:14:00 +1100525 FD_SET(connection_out, *writesetp);
Damien Miller95def091999-11-25 00:26:21 +1100526
Damien Miller5428f641999-11-25 11:54:57 +1100527 /*
528 * Wait for something to happen. This will suspend the process until
529 * some selected descriptor can be read, written, or has some other
Damien Millere11e1ea2010-08-03 16:04:46 +1000530 * event pending, or a timeout expires.
Damien Miller5428f641999-11-25 11:54:57 +1100531 */
Damien Miller95def091999-11-25 00:26:21 +1100532
Damien Millere11e1ea2010-08-03 16:04:46 +1000533 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
djm@openbsd.org97f4d302017-04-30 23:13:25 +0000534 if (options.server_alive_interval > 0) {
Damien Millere11e1ea2010-08-03 16:04:46 +1000535 timeout_secs = options.server_alive_interval;
Darren Tuckerc53c2af2013-05-16 20:28:16 +1000536 server_alive_time = now + options.server_alive_interval;
537 }
djm@openbsd.org97f4d302017-04-30 23:13:25 +0000538 if (options.rekey_interval > 0 && !rekeying)
deraadt@openbsd.org9136ec12016-09-12 01:22:38 +0000539 timeout_secs = MINIMUM(timeout_secs, packet_get_rekey_timeout());
Damien Millere11e1ea2010-08-03 16:04:46 +1000540 set_control_persist_exit_time();
541 if (control_persist_exit_time > 0) {
deraadt@openbsd.org9136ec12016-09-12 01:22:38 +0000542 timeout_secs = MINIMUM(timeout_secs,
Darren Tuckerc53c2af2013-05-16 20:28:16 +1000543 control_persist_exit_time - now);
Damien Millere11e1ea2010-08-03 16:04:46 +1000544 if (timeout_secs < 0)
545 timeout_secs = 0;
546 }
Damien Millera6508752012-04-22 11:21:10 +1000547 if (minwait_secs != 0)
deraadt@openbsd.org9136ec12016-09-12 01:22:38 +0000548 timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs);
Damien Millere11e1ea2010-08-03 16:04:46 +1000549 if (timeout_secs == INT_MAX)
Damien Miller509b0102003-12-17 16:33:10 +1100550 tvp = NULL;
Darren Tuckerfc959702004-07-17 16:12:08 +1000551 else {
Damien Millere11e1ea2010-08-03 16:04:46 +1000552 tv.tv_sec = timeout_secs;
Damien Miller509b0102003-12-17 16:33:10 +1100553 tv.tv_usec = 0;
554 tvp = &tv;
555 }
Damien Millere11e1ea2010-08-03 16:04:46 +1000556
Damien Miller509b0102003-12-17 16:33:10 +1100557 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
558 if (ret < 0) {
Damien Miller95def091999-11-25 00:26:21 +1100559 char buf[100];
Ben Lindstromf9452512001-02-15 03:12:08 +0000560
561 /*
562 * We have to clear the select masks, because we return.
563 * We have to return, because the mainloop checks for the flags
564 * set by the signal handlers.
565 */
Damien Miller79faeff2001-11-12 11:06:32 +1100566 memset(*readsetp, 0, *nallocp);
567 memset(*writesetp, 0, *nallocp);
Ben Lindstromf9452512001-02-15 03:12:08 +0000568
Damien Miller95def091999-11-25 00:26:21 +1100569 if (errno == EINTR)
570 return;
571 /* Note: we might still have data in the buffers. */
572 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
573 buffer_append(&stderr_buffer, buf, strlen(buf));
Damien Miller95def091999-11-25 00:26:21 +1100574 quit_pending = 1;
Darren Tuckerc53c2af2013-05-16 20:28:16 +1000575 } else if (ret == 0) {
576 /*
577 * Timeout. Could have been either keepalive or rekeying.
578 * Keepalive we check here, rekeying is checked in clientloop.
579 */
Darren Tuckerb759c9c2013-06-02 07:46:16 +1000580 if (server_alive_time != 0 && server_alive_time <= monotime())
Darren Tuckerc53c2af2013-05-16 20:28:16 +1000581 server_alive_check();
582 }
583
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000584}
585
Ben Lindstrombba81212001-06-25 05:01:22 +0000586static void
Damien Millerad833b32000-08-23 10:46:23 +1000587client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000588{
Damien Miller95def091999-11-25 00:26:21 +1100589 /* Flush stdout and stderr buffers. */
Damien Millerad833b32000-08-23 10:46:23 +1000590 if (buffer_len(bout) > 0)
Darren Tucker4d5cd332008-06-13 04:51:14 +1000591 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
592 buffer_len(bout));
Damien Millerad833b32000-08-23 10:46:23 +1000593 if (buffer_len(berr) > 0)
Darren Tucker4d5cd332008-06-13 04:51:14 +1000594 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
595 buffer_len(berr));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000596
Damien Miller21771e22011-05-15 08:45:50 +1000597 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000598
Damien Miller5428f641999-11-25 11:54:57 +1100599 /*
600 * Free (and clear) the buffer to reduce the amount of data that gets
601 * written to swap.
602 */
Damien Millerad833b32000-08-23 10:46:23 +1000603 buffer_free(bin);
604 buffer_free(bout);
605 buffer_free(berr);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000606
Damien Miller95def091999-11-25 00:26:21 +1100607 /* Send the suspend signal to the program itself. */
608 kill(getpid(), SIGTSTP);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000609
Darren Tucker5d78de62004-11-05 20:35:44 +1100610 /* Reset window sizes in case they have changed */
611 received_window_change_signal = 1;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000612
Damien Miller95def091999-11-25 00:26:21 +1100613 /* OK, we have been continued by the user. Reinitialize buffers. */
Damien Millerad833b32000-08-23 10:46:23 +1000614 buffer_init(bin);
615 buffer_init(bout);
616 buffer_init(berr);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000617
Damien Miller21771e22011-05-15 08:45:50 +1000618 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000619}
620
Ben Lindstrombba81212001-06-25 05:01:22 +0000621static void
Damien Miller90fdfaf2006-03-26 14:25:37 +1100622client_process_net_input(fd_set *readset)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000623{
markus@openbsd.orga3068632016-01-14 16:17:39 +0000624 int len;
Darren Tucker86e30a02009-08-28 11:21:06 +1000625 char buf[SSH_IOBUFSZ];
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000626
Damien Miller5428f641999-11-25 11:54:57 +1100627 /*
628 * Read input from the server, and add any such data to the buffer of
629 * the packet subsystem.
630 */
Damien Miller95def091999-11-25 00:26:21 +1100631 if (FD_ISSET(connection_in, readset)) {
632 /* Read as much as possible. */
markus@openbsd.orga3068632016-01-14 16:17:39 +0000633 len = read(connection_in, buf, sizeof(buf));
634 if (len == 0) {
Darren Tucker4d5cd332008-06-13 04:51:14 +1000635 /*
636 * Received EOF. The remote host has closed the
637 * connection.
638 */
639 snprintf(buf, sizeof buf,
640 "Connection to %.300s closed by remote host.\r\n",
641 host);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000642 buffer_append(&stderr_buffer, buf, strlen(buf));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000643 quit_pending = 1;
644 return;
Damien Miller95def091999-11-25 00:26:21 +1100645 }
Damien Miller5428f641999-11-25 11:54:57 +1100646 /*
647 * There is a kernel bug on Solaris that causes select to
648 * sometimes wake up even though there is no data available.
649 */
Damien Millerd8968ad2008-07-04 23:10:49 +1000650 if (len < 0 &&
651 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
Damien Miller95def091999-11-25 00:26:21 +1100652 len = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000653
Damien Miller95def091999-11-25 00:26:21 +1100654 if (len < 0) {
Darren Tucker4d5cd332008-06-13 04:51:14 +1000655 /*
656 * An error has encountered. Perhaps there is a
657 * network problem.
658 */
659 snprintf(buf, sizeof buf,
660 "Read from remote host %.300s: %.100s\r\n",
661 host, strerror(errno));
Damien Miller95def091999-11-25 00:26:21 +1100662 buffer_append(&stderr_buffer, buf, strlen(buf));
Damien Miller95def091999-11-25 00:26:21 +1100663 quit_pending = 1;
664 return;
665 }
666 packet_process_incoming(buf, len);
667 }
Damien Miller1383bd82000-04-06 12:32:37 +1000668}
669
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000670static void
Damien Miller5771ed72008-05-19 15:35:33 +1000671client_status_confirm(int type, Channel *c, void *ctx)
Damien Miller0e220db2004-06-15 10:34:08 +1000672{
Damien Miller5771ed72008-05-19 15:35:33 +1000673 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
674 char errmsg[256];
675 int tochan;
Darren Tuckerfc959702004-07-17 16:12:08 +1000676
Damien Miller555f3b82011-05-15 08:48:05 +1000677 /*
678 * If a TTY was explicitly requested, then a failure to allocate
679 * one is fatal.
680 */
681 if (cr->action == CONFIRM_TTY &&
682 (options.request_tty == REQUEST_TTY_FORCE ||
683 options.request_tty == REQUEST_TTY_YES))
684 cr->action = CONFIRM_CLOSE;
685
Damien Miller5771ed72008-05-19 15:35:33 +1000686 /* XXX supress on mux _client_ quietmode */
687 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
Damien Millere1537f92010-01-26 13:26:22 +1100688 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
Damien Miller0e220db2004-06-15 10:34:08 +1000689
Damien Miller5771ed72008-05-19 15:35:33 +1000690 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
691 debug2("%s request accepted on channel %d",
692 cr->request_type, c->self);
693 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
694 if (tochan) {
695 snprintf(errmsg, sizeof(errmsg),
696 "%s request failed\r\n", cr->request_type);
697 } else {
698 snprintf(errmsg, sizeof(errmsg),
699 "%s request failed on channel %d",
700 cr->request_type, c->self);
701 }
702 /* If error occurred on primary session channel, then exit */
Damien Miller555f3b82011-05-15 08:48:05 +1000703 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
Damien Miller5771ed72008-05-19 15:35:33 +1000704 fatal("%s", errmsg);
Damien Miller555f3b82011-05-15 08:48:05 +1000705 /*
706 * If error occurred on mux client, append to
707 * their stderr.
708 */
709 if (tochan) {
710 buffer_append(&c->extended, errmsg,
711 strlen(errmsg));
712 } else
Damien Miller5771ed72008-05-19 15:35:33 +1000713 error("%s", errmsg);
Damien Miller555f3b82011-05-15 08:48:05 +1000714 if (cr->action == CONFIRM_TTY) {
715 /*
716 * If a TTY allocation error occurred, then arrange
717 * for the correct TTY to leave raw mode.
718 */
719 if (c->self == session_ident)
720 leave_raw_mode(0);
721 else
722 mux_tty_alloc_failed(c);
723 } else if (cr->action == CONFIRM_CLOSE) {
Damien Miller5771ed72008-05-19 15:35:33 +1000724 chan_read_failed(c);
725 chan_write_failed(c);
726 }
Damien Miller0e220db2004-06-15 10:34:08 +1000727 }
Darren Tuckera627d422013-06-02 07:31:17 +1000728 free(cr);
Damien Miller5771ed72008-05-19 15:35:33 +1000729}
Damien Miller0e220db2004-06-15 10:34:08 +1000730
Damien Miller5771ed72008-05-19 15:35:33 +1000731static void
732client_abandon_status_confirm(Channel *c, void *ctx)
733{
Darren Tuckera627d422013-06-02 07:31:17 +1000734 free(ctx);
Damien Miller5771ed72008-05-19 15:35:33 +1000735}
736
Damien Miller6d7b4372011-06-23 08:31:57 +1000737void
Damien Miller555f3b82011-05-15 08:48:05 +1000738client_expect_confirm(int id, const char *request,
739 enum confirm_action action)
Damien Miller5771ed72008-05-19 15:35:33 +1000740{
Damien Miller6c81fee2013-11-08 12:19:55 +1100741 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
Damien Miller5771ed72008-05-19 15:35:33 +1000742
743 cr->request_type = request;
Damien Miller555f3b82011-05-15 08:48:05 +1000744 cr->action = action;
Damien Miller5771ed72008-05-19 15:35:33 +1000745
746 channel_register_status_confirm(id, client_status_confirm,
747 client_abandon_status_confirm, cr);
Damien Miller0e220db2004-06-15 10:34:08 +1000748}
749
Darren Tucker9f407c42008-06-13 04:50:27 +1000750void
751client_register_global_confirm(global_confirm_cb *cb, void *ctx)
752{
Damien Millerb9d3bee2008-07-16 22:40:52 +1000753 struct global_confirm *gc, *last_gc;
Darren Tucker9f407c42008-06-13 04:50:27 +1000754
755 /* Coalesce identical callbacks */
Damien Millerb9d3bee2008-07-16 22:40:52 +1000756 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
757 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
758 if (++last_gc->ref_count >= INT_MAX)
759 fatal("%s: last_gc->ref_count = %d",
760 __func__, last_gc->ref_count);
Darren Tucker9f407c42008-06-13 04:50:27 +1000761 return;
762 }
763
Damien Miller6c81fee2013-11-08 12:19:55 +1100764 gc = xcalloc(1, sizeof(*gc));
Darren Tucker9f407c42008-06-13 04:50:27 +1000765 gc->cb = cb;
766 gc->ctx = ctx;
767 gc->ref_count = 1;
768 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
769}
770
Damien Miller0e220db2004-06-15 10:34:08 +1000771static void
Ben Lindstrom681d9322002-03-22 03:53:00 +0000772process_cmdline(void)
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000773{
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000774 void (*handler)(int);
Damien Miller7acefbb2014-07-18 14:11:24 +1000775 char *s, *cmd;
776 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
777 struct Forward fwd;
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000778
Damien Miller1d2c4562014-02-04 11:18:20 +1100779 memset(&fwd, 0, sizeof(fwd));
Darren Tucker23ae8ca2007-12-02 23:12:30 +1100780
Damien Miller21771e22011-05-15 08:45:50 +1000781 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Ben Lindstrom5a6abda2002-06-09 19:41:48 +0000782 handler = signal(SIGINT, SIG_IGN);
Ben Lindstrom681d9322002-03-22 03:53:00 +0000783 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000784 if (s == NULL)
785 goto out;
Damien Millerfdb23062013-11-21 13:57:15 +1100786 while (isspace((u_char)*s))
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000787 s++;
Darren Tuckere7066df2004-05-24 10:18:05 +1000788 if (*s == '-')
789 s++; /* Skip cmdline '-', if any */
Darren Tuckere1675822004-05-24 10:13:07 +1000790 if (*s == '\0')
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000791 goto out;
Darren Tuckere7066df2004-05-24 10:18:05 +1000792
Darren Tucker1973c882004-05-24 10:34:36 +1000793 if (*s == 'h' || *s == 'H' || *s == '?') {
Darren Tuckere7066df2004-05-24 10:18:05 +1000794 logit("Commands:");
Damien Miller43020952006-07-10 20:16:12 +1000795 logit(" -L[bind_address:]port:host:hostport "
796 "Request local forward");
797 logit(" -R[bind_address:]port:host:hostport "
798 "Request remote forward");
Damien Miller0164cb82008-11-05 16:30:31 +1100799 logit(" -D[bind_address:]port "
800 "Request dynamic forward");
Damien Millerff773642011-09-22 21:39:48 +1000801 logit(" -KL[bind_address:]port "
802 "Cancel local forward");
Damien Miller57e8ad32006-07-10 20:20:52 +1000803 logit(" -KR[bind_address:]port "
Damien Miller43020952006-07-10 20:16:12 +1000804 "Cancel remote forward");
Damien Millerff773642011-09-22 21:39:48 +1000805 logit(" -KD[bind_address:]port "
806 "Cancel dynamic forward");
Damien Millerd27b9472005-12-13 19:29:02 +1100807 if (!options.permit_local_command)
808 goto out;
Damien Miller43020952006-07-10 20:16:12 +1000809 logit(" !args "
810 "Execute local command");
Damien Millerd27b9472005-12-13 19:29:02 +1100811 goto out;
812 }
813
814 if (*s == '!' && options.permit_local_command) {
815 s++;
816 ssh_local_cmd(s);
Darren Tuckere7066df2004-05-24 10:18:05 +1000817 goto out;
818 }
819
820 if (*s == 'K') {
821 delete = 1;
822 s++;
823 }
Damien Miller0164cb82008-11-05 16:30:31 +1100824 if (*s == 'L')
825 local = 1;
826 else if (*s == 'R')
827 remote = 1;
828 else if (*s == 'D')
829 dynamic = 1;
830 else {
Damien Miller996acd22003-04-09 20:59:48 +1000831 logit("Invalid command.");
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000832 goto out;
833 }
Damien Miller0164cb82008-11-05 16:30:31 +1100834
Damien Millerfdb23062013-11-21 13:57:15 +1100835 while (isspace((u_char)*++s))
Darren Tucker03b1cdb2007-03-21 20:46:03 +1100836 ;
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000837
Damien Millere1537f92010-01-26 13:26:22 +1100838 /* XXX update list of forwards in options */
Darren Tuckere7066df2004-05-24 10:18:05 +1000839 if (delete) {
Damien Miller7acefbb2014-07-18 14:11:24 +1000840 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
841 if (!parse_forward(&fwd, s, 1, 0)) {
842 logit("Bad forwarding close specification.");
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000843 goto out;
844 }
Damien Millerff773642011-09-22 21:39:48 +1000845 if (remote)
Damien Miller7acefbb2014-07-18 14:11:24 +1000846 ok = channel_request_rforward_cancel(&fwd) == 0;
Damien Millerff773642011-09-22 21:39:48 +1000847 else if (dynamic)
Damien Miller7acefbb2014-07-18 14:11:24 +1000848 ok = channel_cancel_lport_listener(&fwd,
849 0, &options.fwd_opts) > 0;
Damien Millerff773642011-09-22 21:39:48 +1000850 else
Damien Miller7acefbb2014-07-18 14:11:24 +1000851 ok = channel_cancel_lport_listener(&fwd,
852 CHANNEL_CANCEL_PORT_STATIC,
853 &options.fwd_opts) > 0;
Damien Millerff773642011-09-22 21:39:48 +1000854 if (!ok) {
dtucker@openbsd.org9390b002017-01-29 21:35:23 +0000855 logit("Unknown port forwarding.");
Damien Millerff773642011-09-22 21:39:48 +1000856 goto out;
857 }
858 logit("Canceled forwarding.");
Darren Tuckere7066df2004-05-24 10:18:05 +1000859 } else {
Damien Miller4bf648f2009-02-14 16:28:21 +1100860 if (!parse_forward(&fwd, s, dynamic, remote)) {
Darren Tuckere7066df2004-05-24 10:18:05 +1000861 logit("Bad forwarding specification.");
862 goto out;
863 }
Damien Miller0164cb82008-11-05 16:30:31 +1100864 if (local || dynamic) {
Damien Miller7acefbb2014-07-18 14:11:24 +1000865 if (!channel_setup_local_fwd_listener(&fwd,
866 &options.fwd_opts)) {
Darren Tuckere7066df2004-05-24 10:18:05 +1000867 logit("Port forwarding failed.");
868 goto out;
869 }
Damien Millerf91ee4c2005-03-01 21:24:33 +1100870 } else {
Damien Miller7acefbb2014-07-18 14:11:24 +1000871 if (channel_request_remote_forwarding(&fwd) < 0) {
Darren Tuckere7d4b192006-07-12 22:17:10 +1000872 logit("Port forwarding failed.");
873 goto out;
874 }
Damien Millerf91ee4c2005-03-01 21:24:33 +1100875 }
Darren Tuckere7066df2004-05-24 10:18:05 +1000876 logit("Forwarding port.");
877 }
878
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000879out:
880 signal(SIGINT, handler);
Damien Miller21771e22011-05-15 08:45:50 +1000881 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Darren Tuckera627d422013-06-02 07:31:17 +1000882 free(cmd);
883 free(fwd.listen_host);
Damien Miller7acefbb2014-07-18 14:11:24 +1000884 free(fwd.listen_path);
Darren Tuckera627d422013-06-02 07:31:17 +1000885 free(fwd.connect_host);
Damien Miller7acefbb2014-07-18 14:11:24 +1000886 free(fwd.connect_path);
Ben Lindstrom5589f4b2002-03-22 03:24:32 +0000887}
888
Darren Tucker92a39cf2012-09-07 11:20:20 +1000889/* reasons to suppress output of an escape command in help output */
890#define SUPPRESS_NEVER 0 /* never suppress, always show */
djm@openbsd.org97f4d302017-04-30 23:13:25 +0000891#define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */
892#define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */
893#define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */
Darren Tucker92a39cf2012-09-07 11:20:20 +1000894struct escape_help_text {
895 const char *cmd;
896 const char *text;
897 unsigned int flags;
898};
899static struct escape_help_text esc_txt[] = {
900 {".", "terminate session", SUPPRESS_MUXMASTER},
901 {".", "terminate connection (and any multiplexed sessions)",
902 SUPPRESS_MUXCLIENT},
djm@openbsd.org97f4d302017-04-30 23:13:25 +0000903 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER},
Darren Tucker92a39cf2012-09-07 11:20:20 +1000904 {"C", "open a command line", SUPPRESS_MUXCLIENT},
djm@openbsd.org97f4d302017-04-30 23:13:25 +0000905 {"R", "request rekey", SUPPRESS_NEVER},
Darren Tuckerca0d0fd2012-09-07 11:22:24 +1000906 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
Darren Tucker92a39cf2012-09-07 11:20:20 +1000907 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
908 {"#", "list forwarded connections", SUPPRESS_NEVER},
909 {"&", "background ssh (when waiting for connections to terminate)",
910 SUPPRESS_MUXCLIENT},
911 {"?", "this message", SUPPRESS_NEVER},
912};
913
914static void
djm@openbsd.org97f4d302017-04-30 23:13:25 +0000915print_escape_help(Buffer *b, int escape_char, int mux_client, int using_stderr)
Darren Tucker92a39cf2012-09-07 11:20:20 +1000916{
917 unsigned int i, suppress_flags;
918 char string[1024];
919
920 snprintf(string, sizeof string, "%c?\r\n"
921 "Supported escape sequences:\r\n", escape_char);
922 buffer_append(b, string, strlen(string));
923
djm@openbsd.org97f4d302017-04-30 23:13:25 +0000924 suppress_flags =
Darren Tucker92a39cf2012-09-07 11:20:20 +1000925 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
926 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
927 (using_stderr ? 0 : SUPPRESS_SYSLOG);
928
929 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
930 if (esc_txt[i].flags & suppress_flags)
931 continue;
Darren Tuckerca0d0fd2012-09-07 11:22:24 +1000932 snprintf(string, sizeof string, " %c%-3s - %s\r\n",
Darren Tucker92a39cf2012-09-07 11:20:20 +1000933 escape_char, esc_txt[i].cmd, esc_txt[i].text);
934 buffer_append(b, string, strlen(string));
935 }
936
937 snprintf(string, sizeof string,
Darren Tuckerca0d0fd2012-09-07 11:22:24 +1000938 " %c%c - send the escape character by typing it twice\r\n"
Darren Tucker92a39cf2012-09-07 11:20:20 +1000939 "(Note that escapes are only recognized immediately after "
940 "newline.)\r\n", escape_char, escape_char);
941 buffer_append(b, string, strlen(string));
942}
943
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000944/*
naddy@openbsd.org768405f2017-05-03 21:08:09 +0000945 * Process the characters one by one.
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000946 */
Ben Lindstrombba81212001-06-25 05:01:22 +0000947static int
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000948process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
949 char *buf, int len)
Damien Millerad833b32000-08-23 10:46:23 +1000950{
951 char string[1024];
952 pid_t pid;
953 int bytes = 0;
Ben Lindstrom46c16222000-12-22 01:43:59 +0000954 u_int i;
955 u_char ch;
Damien Millerad833b32000-08-23 10:46:23 +1000956 char *s;
djm@openbsd.org05164352017-04-30 23:21:54 +0000957 struct escape_filter_ctx *efc = c->filter_ctx == NULL ?
958 NULL : (struct escape_filter_ctx *)c->filter_ctx;
Damien Millerad833b32000-08-23 10:46:23 +1000959
djm@openbsd.org05164352017-04-30 23:21:54 +0000960 if (c->filter_ctx == NULL)
961 return 0;
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000962
Damien Millereccb9de2005-06-17 12:59:34 +1000963 if (len <= 0)
964 return (0);
965
966 for (i = 0; i < (u_int)len; i++) {
Damien Millerad833b32000-08-23 10:46:23 +1000967 /* Get one character at a time. */
968 ch = buf[i];
969
djm@openbsd.org05164352017-04-30 23:21:54 +0000970 if (efc->escape_pending) {
Damien Millerad833b32000-08-23 10:46:23 +1000971 /* We have previously seen an escape character. */
972 /* Clear the flag now. */
djm@openbsd.org05164352017-04-30 23:21:54 +0000973 efc->escape_pending = 0;
Damien Millerad833b32000-08-23 10:46:23 +1000974
975 /* Process the escaped character. */
976 switch (ch) {
977 case '.':
978 /* Terminate the connection. */
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000979 snprintf(string, sizeof string, "%c.\r\n",
djm@openbsd.org05164352017-04-30 23:21:54 +0000980 efc->escape_char);
Damien Millerad833b32000-08-23 10:46:23 +1000981 buffer_append(berr, string, strlen(string));
Damien Millerad833b32000-08-23 10:46:23 +1000982
Damien Millere1537f92010-01-26 13:26:22 +1100983 if (c && c->ctl_chan != -1) {
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000984 chan_read_failed(c);
985 chan_write_failed(c);
Darren Tuckerea8342c2013-06-06 08:11:40 +1000986 if (c->detach_user)
987 c->detach_user(c->self, NULL);
Damien Miller36187092013-06-10 13:07:11 +1000988 c->type = SSH_CHANNEL_ABANDONED;
989 buffer_clear(&c->input);
990 chan_ibuf_empty(c);
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000991 return 0;
992 } else
993 quit_pending = 1;
Damien Millerad833b32000-08-23 10:46:23 +1000994 return -1;
995
996 case 'Z' - 64:
Darren Tucker2fb66ca2008-06-13 04:49:33 +1000997 /* XXX support this for mux clients */
Damien Millere1537f92010-01-26 13:26:22 +1100998 if (c && c->ctl_chan != -1) {
Darren Tuckerf111d402012-09-07 11:21:42 +1000999 char b[16];
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001000 noescape:
Darren Tuckerf111d402012-09-07 11:21:42 +10001001 if (ch == 'Z' - 64)
1002 snprintf(b, sizeof b, "^Z");
1003 else
1004 snprintf(b, sizeof b, "%c", ch);
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001005 snprintf(string, sizeof string,
Darren Tuckerf111d402012-09-07 11:21:42 +10001006 "%c%s escape not available to "
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001007 "multiplexed sessions\r\n",
djm@openbsd.org05164352017-04-30 23:21:54 +00001008 efc->escape_char, b);
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001009 buffer_append(berr, string,
1010 strlen(string));
1011 continue;
1012 }
Darren Tucker4d5cd332008-06-13 04:51:14 +10001013 /* Suspend the program. Inform the user */
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001014 snprintf(string, sizeof string,
djm@openbsd.org05164352017-04-30 23:21:54 +00001015 "%c^Z [suspend ssh]\r\n", efc->escape_char);
Damien Millerad833b32000-08-23 10:46:23 +10001016 buffer_append(berr, string, strlen(string));
Damien Millerad833b32000-08-23 10:46:23 +10001017
1018 /* Restore terminal modes and suspend. */
1019 client_suspend_self(bin, bout, berr);
1020
1021 /* We have been continued. */
1022 continue;
1023
Damien Miller54c45982003-05-15 10:20:13 +10001024 case 'B':
djm@openbsd.org97f4d302017-04-30 23:13:25 +00001025 snprintf(string, sizeof string,
djm@openbsd.org05164352017-04-30 23:21:54 +00001026 "%cB\r\n", efc->escape_char);
djm@openbsd.org97f4d302017-04-30 23:13:25 +00001027 buffer_append(berr, string, strlen(string));
1028 channel_request_start(c->self, "break", 0);
1029 packet_put_int(1000);
1030 packet_send();
Damien Miller54c45982003-05-15 10:20:13 +10001031 continue;
1032
Ben Lindstromf28f6342001-04-04 02:03:04 +00001033 case 'R':
djm@openbsd.org97f4d302017-04-30 23:13:25 +00001034 if (datafellows & SSH_BUG_NOREKEY)
1035 logit("Server does not "
1036 "support re-keying");
1037 else
1038 need_rekeying = 1;
Ben Lindstromf28f6342001-04-04 02:03:04 +00001039 continue;
1040
Darren Tucker50a48d02012-09-06 21:25:37 +10001041 case 'V':
1042 /* FALLTHROUGH */
1043 case 'v':
1044 if (c && c->ctl_chan != -1)
1045 goto noescape;
1046 if (!log_is_on_stderr()) {
1047 snprintf(string, sizeof string,
1048 "%c%c [Logging to syslog]\r\n",
djm@openbsd.org05164352017-04-30 23:21:54 +00001049 efc->escape_char, ch);
Darren Tucker50a48d02012-09-06 21:25:37 +10001050 buffer_append(berr, string,
1051 strlen(string));
1052 continue;
1053 }
1054 if (ch == 'V' && options.log_level >
1055 SYSLOG_LEVEL_QUIET)
1056 log_change_level(--options.log_level);
1057 if (ch == 'v' && options.log_level <
1058 SYSLOG_LEVEL_DEBUG3)
1059 log_change_level(++options.log_level);
1060 snprintf(string, sizeof string,
djm@openbsd.org05164352017-04-30 23:21:54 +00001061 "%c%c [LogLevel %s]\r\n",
1062 efc->escape_char, ch,
Darren Tucker50a48d02012-09-06 21:25:37 +10001063 log_level_name(options.log_level));
1064 buffer_append(berr, string, strlen(string));
1065 continue;
1066
Damien Millerad833b32000-08-23 10:46:23 +10001067 case '&':
Damien Millere1537f92010-01-26 13:26:22 +11001068 if (c && c->ctl_chan != -1)
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001069 goto noescape;
Damien Millerad833b32000-08-23 10:46:23 +10001070 /*
Darren Tucker4d5cd332008-06-13 04:51:14 +10001071 * Detach the program (continue to serve
1072 * connections, but put in background and no
1073 * more new connections).
Damien Millerad833b32000-08-23 10:46:23 +10001074 */
Damien Miller96507ef2001-11-12 10:52:25 +11001075 /* Restore tty modes. */
Damien Miller21771e22011-05-15 08:45:50 +10001076 leave_raw_mode(
1077 options.request_tty == REQUEST_TTY_FORCE);
Damien Miller96507ef2001-11-12 10:52:25 +11001078
1079 /* Stop listening for new connections. */
1080 channel_stop_listening();
1081
1082 snprintf(string, sizeof string,
djm@openbsd.org05164352017-04-30 23:21:54 +00001083 "%c& [backgrounded]\n", efc->escape_char);
Damien Miller96507ef2001-11-12 10:52:25 +11001084 buffer_append(berr, string, strlen(string));
1085
1086 /* Fork into background. */
1087 pid = fork();
1088 if (pid < 0) {
1089 error("fork: %.100s", strerror(errno));
1090 continue;
1091 }
1092 if (pid != 0) { /* This is the parent. */
1093 /* The parent just exits. */
1094 exit(0);
1095 }
1096 /* The child continues serving connections. */
djm@openbsd.org97f4d302017-04-30 23:13:25 +00001097 buffer_append(bin, "\004", 1);
1098 /* fake EOF on stdin */
1099 return -1;
Damien Millerad833b32000-08-23 10:46:23 +10001100 case '?':
djm@openbsd.org05164352017-04-30 23:21:54 +00001101 print_escape_help(berr, efc->escape_char,
Darren Tucker92a39cf2012-09-07 11:20:20 +10001102 (c && c->ctl_chan != -1),
1103 log_is_on_stderr());
Damien Millerad833b32000-08-23 10:46:23 +10001104 continue;
1105
1106 case '#':
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001107 snprintf(string, sizeof string, "%c#\r\n",
djm@openbsd.org05164352017-04-30 23:21:54 +00001108 efc->escape_char);
Damien Millerad833b32000-08-23 10:46:23 +10001109 buffer_append(berr, string, strlen(string));
1110 s = channel_open_message();
1111 buffer_append(berr, s, strlen(s));
Darren Tuckera627d422013-06-02 07:31:17 +10001112 free(s);
Damien Millerad833b32000-08-23 10:46:23 +10001113 continue;
1114
Ben Lindstrom5589f4b2002-03-22 03:24:32 +00001115 case 'C':
Damien Millere1537f92010-01-26 13:26:22 +11001116 if (c && c->ctl_chan != -1)
Damien Miller586b0052008-12-09 14:11:32 +11001117 goto noescape;
Ben Lindstrom681d9322002-03-22 03:53:00 +00001118 process_cmdline();
Ben Lindstrom5589f4b2002-03-22 03:24:32 +00001119 continue;
1120
Damien Millerad833b32000-08-23 10:46:23 +10001121 default:
djm@openbsd.org05164352017-04-30 23:21:54 +00001122 if (ch != efc->escape_char) {
1123 buffer_put_char(bin, efc->escape_char);
Damien Millerad833b32000-08-23 10:46:23 +10001124 bytes++;
1125 }
1126 /* Escaped characters fall through here */
1127 break;
1128 }
1129 } else {
1130 /*
Darren Tucker4d5cd332008-06-13 04:51:14 +10001131 * The previous character was not an escape char.
1132 * Check if this is an escape.
Damien Millerad833b32000-08-23 10:46:23 +10001133 */
djm@openbsd.org05164352017-04-30 23:21:54 +00001134 if (last_was_cr && ch == efc->escape_char) {
Darren Tucker4d5cd332008-06-13 04:51:14 +10001135 /*
1136 * It is. Set the flag and continue to
1137 * next character.
1138 */
djm@openbsd.org05164352017-04-30 23:21:54 +00001139 efc->escape_pending = 1;
Damien Millerad833b32000-08-23 10:46:23 +10001140 continue;
1141 }
1142 }
1143
1144 /*
1145 * Normal character. Record whether it was a newline,
1146 * and append it to the buffer.
1147 */
1148 last_was_cr = (ch == '\r' || ch == '\n');
1149 buffer_put_char(bin, ch);
1150 bytes++;
1151 }
1152 return bytes;
1153}
1154
Damien Miller5428f641999-11-25 11:54:57 +11001155/*
Damien Millerb38eff82000-04-01 11:09:21 +10001156 * Get packets from the connection input buffer, and process them as long as
1157 * there are packets available.
1158 *
1159 * Any unknown packets received during the actual
1160 * session cause the session to terminate. This is
1161 * intended to make debugging easier since no
1162 * confirmations are sent. Any compatible protocol
1163 * extensions must be negotiated during the
1164 * preparatory phase.
1165 */
1166
Ben Lindstrombba81212001-06-25 05:01:22 +00001167static void
Ben Lindstrom31ca54a2001-02-09 02:11:24 +00001168client_process_buffered_input_packets(void)
Damien Millerb38eff82000-04-01 11:09:21 +10001169{
markus@openbsd.org57d10cb2015-01-19 20:16:15 +00001170 dispatch_run(DISPATCH_NONBLOCK, &quit_pending, active_state);
Damien Millerb38eff82000-04-01 11:09:21 +10001171}
1172
Damien Millerad833b32000-08-23 10:46:23 +10001173/* scan buf[] for '~' before sending data to the peer */
1174
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001175/* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1176void *
1177client_new_escape_filter_ctx(int escape_char)
1178{
1179 struct escape_filter_ctx *ret;
1180
Damien Miller6c81fee2013-11-08 12:19:55 +11001181 ret = xcalloc(1, sizeof(*ret));
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001182 ret->escape_pending = 0;
1183 ret->escape_char = escape_char;
1184 return (void *)ret;
1185}
1186
Darren Tucker84c56f52008-06-13 04:55:46 +10001187/* Free the escape filter context on channel free */
1188void
1189client_filter_cleanup(int cid, void *ctx)
1190{
Darren Tuckera627d422013-06-02 07:31:17 +10001191 free(ctx);
Darren Tucker84c56f52008-06-13 04:55:46 +10001192}
1193
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001194int
1195client_simple_escape_filter(Channel *c, char *buf, int len)
Damien Millerad833b32000-08-23 10:46:23 +10001196{
Damien Miller5771ed72008-05-19 15:35:33 +10001197 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1198 return 0;
1199
Darren Tucker2fb66ca2008-06-13 04:49:33 +10001200 return process_escapes(c, &c->input, &c->output, &c->extended,
1201 buf, len);
Damien Millerad833b32000-08-23 10:46:23 +10001202}
1203
Ben Lindstrombba81212001-06-25 05:01:22 +00001204static void
Ben Lindstrom4c3f77d2001-04-05 23:37:36 +00001205client_channel_closed(int id, void *arg)
1206{
Damien Miller3ec27592001-10-12 11:35:04 +10001207 channel_cancel_cleanup(id);
Ben Lindstrom4c3f77d2001-04-05 23:37:36 +00001208 session_closed = 1;
Damien Miller21771e22011-05-15 08:45:50 +10001209 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Ben Lindstrom4c3f77d2001-04-05 23:37:36 +00001210}
1211
Damien Millerb38eff82000-04-01 11:09:21 +10001212/*
Damien Miller5428f641999-11-25 11:54:57 +11001213 * Implements the interactive session with the server. This is called after
1214 * the user has been authenticated, and a command has been started on the
Ben Lindstrom2b1f71b2001-06-05 20:32:21 +00001215 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1216 * used as an escape character for terminating or suspending the session.
Damien Miller5428f641999-11-25 11:54:57 +11001217 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001218
Damien Miller4af51302000-04-16 11:18:38 +10001219int
Damien Millerad833b32000-08-23 10:46:23 +10001220client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001221{
Damien Miller5e953212001-01-30 09:14:00 +11001222 fd_set *readset = NULL, *writeset = NULL;
Damien Miller95def091999-11-25 00:26:21 +11001223 double start_time, total_time;
djm@openbsd.org19bcf2e2016-02-08 10:57:07 +00001224 int r, max_fd = 0, max_fd2 = 0, len;
Damien Millerb61f3fc2008-07-11 17:36:48 +10001225 u_int64_t ibytes, obytes;
Darren Tuckerc7a6fc42004-08-13 21:18:00 +10001226 u_int nalloc = 0;
Damien Miller95def091999-11-25 00:26:21 +11001227 char buf[100];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001228
Damien Miller95def091999-11-25 00:26:21 +11001229 debug("Entering interactive session.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001230
semarie@openbsd.orgd7d2bc92015-12-26 07:46:03 +00001231 if (options.control_master &&
djm@openbsd.org368dd972016-07-23 02:54:08 +00001232 !option_clear_or_none(options.control_path)) {
semarie@openbsd.orgd7d2bc92015-12-26 07:46:03 +00001233 debug("pledge: id");
tb@openbsd.org372807c2016-07-11 21:38:13 +00001234 if (pledge("stdio rpath wpath cpath unix inet dns recvfd proc exec id tty",
semarie@openbsd.orgd7d2bc92015-12-26 07:46:03 +00001235 NULL) == -1)
1236 fatal("%s pledge(): %s", __func__, strerror(errno));
1237
1238 } else if (options.forward_x11 || options.permit_local_command) {
semarie@openbsd.orgb91926a2015-12-03 17:00:18 +00001239 debug("pledge: exec");
1240 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1241 NULL) == -1)
1242 fatal("%s pledge(): %s", __func__, strerror(errno));
1243
1244 } else if (options.update_hostkeys) {
1245 debug("pledge: filesystem full");
1246 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1247 NULL) == -1)
1248 fatal("%s pledge(): %s", __func__, strerror(errno));
1249
djm@openbsd.org368dd972016-07-23 02:54:08 +00001250 } else if (!option_clear_or_none(options.proxy_command) ||
1251 fork_after_authentication_flag) {
semarie@openbsd.orgb91926a2015-12-03 17:00:18 +00001252 debug("pledge: proc");
1253 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1254 fatal("%s pledge(): %s", __func__, strerror(errno));
1255
semarie@openbsd.orgb91926a2015-12-03 17:00:18 +00001256 } else {
1257 debug("pledge: network");
1258 if (pledge("stdio unix inet dns tty", NULL) == -1)
1259 fatal("%s pledge(): %s", __func__, strerror(errno));
1260 }
1261
Damien Miller95def091999-11-25 00:26:21 +11001262 start_time = get_current_time();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001263
Damien Miller95def091999-11-25 00:26:21 +11001264 /* Initialize variables. */
Damien Miller95def091999-11-25 00:26:21 +11001265 last_was_cr = 1;
1266 exit_status = -1;
Damien Miller95def091999-11-25 00:26:21 +11001267 connection_in = packet_get_connection_in();
1268 connection_out = packet_get_connection_out();
deraadt@openbsd.org9136ec12016-09-12 01:22:38 +00001269 max_fd = MAXIMUM(connection_in, connection_out);
Damien Miller5e953212001-01-30 09:14:00 +11001270
Damien Miller95def091999-11-25 00:26:21 +11001271 quit_pending = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001272
Damien Miller95def091999-11-25 00:26:21 +11001273 /* Initialize buffers. */
Damien Miller95def091999-11-25 00:26:21 +11001274 buffer_init(&stderr_buffer);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001275
Damien Millerb38eff82000-04-01 11:09:21 +10001276 client_init_dispatch();
1277
Ben Lindstromf49dbff2002-12-23 02:01:55 +00001278 /*
1279 * Set signal handlers, (e.g. to restore non-blocking mode)
1280 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1281 */
Darren Tucker07336da2004-11-05 20:02:16 +11001282 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1283 signal(SIGHUP, signal_handler);
Ben Lindstromf49dbff2002-12-23 02:01:55 +00001284 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1285 signal(SIGINT, signal_handler);
1286 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1287 signal(SIGQUIT, signal_handler);
1288 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1289 signal(SIGTERM, signal_handler);
Darren Tucker5d78de62004-11-05 20:35:44 +11001290 signal(SIGWINCH, window_change_handler);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001291
Damien Miller95def091999-11-25 00:26:21 +11001292 if (have_pty)
Damien Miller21771e22011-05-15 08:45:50 +10001293 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001294
djm@openbsd.org97f4d302017-04-30 23:13:25 +00001295 session_ident = ssh2_chan_id;
1296 if (session_ident != -1) {
1297 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1298 channel_register_filter(session_ident,
1299 client_simple_escape_filter, NULL,
1300 client_filter_cleanup,
1301 client_new_escape_filter_ctx(
1302 escape_char_arg));
Damien Miller6c3eec72011-05-05 14:16:22 +10001303 }
djm@openbsd.org97f4d302017-04-30 23:13:25 +00001304 channel_register_cleanup(session_ident,
1305 client_channel_closed, 0);
Ben Lindstrom5b828322001-02-09 01:34:36 +00001306 }
Damien Millerad833b32000-08-23 10:46:23 +10001307
Damien Miller95def091999-11-25 00:26:21 +11001308 /* Main loop of the client for the interactive session mode. */
1309 while (!quit_pending) {
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001310
Damien Miller5428f641999-11-25 11:54:57 +11001311 /* Process buffered packets sent by the server. */
Damien Miller95def091999-11-25 00:26:21 +11001312 client_process_buffered_input_packets();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001313
djm@openbsd.org97f4d302017-04-30 23:13:25 +00001314 if (session_closed && !channel_still_open())
Damien Miller1383bd82000-04-06 12:32:37 +10001315 break;
Ben Lindstrom4c3f77d2001-04-05 23:37:36 +00001316
djm@openbsd.org19bcf2e2016-02-08 10:57:07 +00001317 if (ssh_packet_is_rekeying(active_state)) {
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001318 debug("rekeying in progress");
djm@openbsd.org19bcf2e2016-02-08 10:57:07 +00001319 } else if (need_rekeying) {
1320 /* manual rekey request */
1321 debug("need rekeying");
1322 if ((r = kex_start_rekex(active_state)) != 0)
1323 fatal("%s: kex_start_rekex: %s", __func__,
1324 ssh_err(r));
1325 need_rekeying = 0;
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001326 } else {
1327 /*
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001328 * Make packets from buffered channel data, and
1329 * enqueue them for sending to the server.
1330 */
1331 if (packet_not_very_much_data_to_write())
1332 channel_output_poll();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001333
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001334 /*
1335 * Check if the window size has changed, and buffer a
1336 * message about it to the server if so.
1337 */
1338 client_check_window_change();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001339
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001340 if (quit_pending)
1341 break;
1342 }
Damien Miller5428f641999-11-25 11:54:57 +11001343 /*
1344 * Wait until we have something to do (something becomes
1345 * available on one of the descriptors).
1346 */
Ben Lindstrom16d29d52001-07-18 16:01:46 +00001347 max_fd2 = max_fd;
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001348 client_wait_until_can_do_something(&readset, &writeset,
djm@openbsd.org19bcf2e2016-02-08 10:57:07 +00001349 &max_fd2, &nalloc, ssh_packet_is_rekeying(active_state));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001350
Damien Miller95def091999-11-25 00:26:21 +11001351 if (quit_pending)
1352 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001353
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001354 /* Do channel operations unless rekeying in progress. */
djm@openbsd.org19bcf2e2016-02-08 10:57:07 +00001355 if (!ssh_packet_is_rekeying(active_state))
Ben Lindstrombe2cc432001-04-04 23:46:07 +00001356 channel_after_select(readset, writeset);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001357
Damien Miller1383bd82000-04-06 12:32:37 +10001358 /* Buffer input from the connection. */
Damien Miller5e953212001-01-30 09:14:00 +11001359 client_process_net_input(readset);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001360
Damien Miller1383bd82000-04-06 12:32:37 +10001361 if (quit_pending)
1362 break;
1363
Darren Tucker4d5cd332008-06-13 04:51:14 +10001364 /*
1365 * Send as much buffered packet data as possible to the
1366 * sender.
1367 */
Damien Miller5e953212001-01-30 09:14:00 +11001368 if (FD_ISSET(connection_out, writeset))
Damien Miller95def091999-11-25 00:26:21 +11001369 packet_write_poll();
Damien Millere11e1ea2010-08-03 16:04:46 +10001370
1371 /*
1372 * If we are a backgrounded control master, and the
1373 * timeout has expired without any active client
1374 * connections, then quit.
1375 */
1376 if (control_persist_exit_time > 0) {
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001377 if (monotime() >= control_persist_exit_time) {
Damien Millere11e1ea2010-08-03 16:04:46 +10001378 debug("ControlPersist timeout expired");
1379 break;
1380 }
1381 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001382 }
Darren Tuckera627d422013-06-02 07:31:17 +10001383 free(readset);
1384 free(writeset);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001385
Damien Miller95def091999-11-25 00:26:21 +11001386 /* Terminate the session. */
1387
1388 /* Stop watching for window change. */
Darren Tucker5d78de62004-11-05 20:35:44 +11001389 signal(SIGWINCH, SIG_DFL);
Damien Miller95def091999-11-25 00:26:21 +11001390
djm@openbsd.org97f4d302017-04-30 23:13:25 +00001391 packet_start(SSH2_MSG_DISCONNECT);
1392 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1393 packet_put_cstring("disconnected by user");
1394 packet_put_cstring(""); /* language tag */
1395 packet_send();
1396 packet_write_wait();
Darren Tucker12b4a652009-06-21 18:14:48 +10001397
Ben Lindstrom601e4362001-06-21 03:19:23 +00001398 channel_free_all();
Damien Miller95def091999-11-25 00:26:21 +11001399
Ben Lindstromec46e0b2001-06-09 01:27:31 +00001400 if (have_pty)
Damien Miller21771e22011-05-15 08:45:50 +10001401 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Ben Lindstromc93e84c2001-05-12 00:08:37 +00001402
1403 /* restore blocking io */
1404 if (!isatty(fileno(stdin)))
1405 unset_nonblock(fileno(stdin));
1406 if (!isatty(fileno(stdout)))
1407 unset_nonblock(fileno(stdout));
1408 if (!isatty(fileno(stderr)))
1409 unset_nonblock(fileno(stderr));
1410
Damien Millerd6965512003-12-17 16:31:53 +11001411 /*
1412 * If there was no shell or command requested, there will be no remote
1413 * exit status to be returned. In that case, clear error code if the
1414 * connection was deliberately terminated at this end.
1415 */
1416 if (no_shell_flag && received_signal == SIGTERM) {
1417 received_signal = 0;
1418 exit_status = 0;
1419 }
1420
Darren Tucker9a2c4cd2003-09-22 21:16:05 +10001421 if (received_signal)
Ben Lindstromf8f065b2001-12-06 17:52:16 +00001422 fatal("Killed by signal %d.", (int) received_signal);
Ben Lindstromec46e0b2001-06-09 01:27:31 +00001423
1424 /*
1425 * In interactive mode (with pseudo tty) display a message indicating
1426 * that the connection has been closed.
1427 */
1428 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
Darren Tucker4d5cd332008-06-13 04:51:14 +10001429 snprintf(buf, sizeof buf,
1430 "Connection to %.64s closed.\r\n", host);
Ben Lindstromec46e0b2001-06-09 01:27:31 +00001431 buffer_append(&stderr_buffer, buf, strlen(buf));
1432 }
1433
Damien Miller95def091999-11-25 00:26:21 +11001434 /* Output any buffered data for stderr. */
Damien Millercfd6e4f2011-01-16 23:18:33 +11001435 if (buffer_len(&stderr_buffer) > 0) {
Damien Miller4791f9d2011-01-16 23:16:53 +11001436 len = atomicio(vwrite, fileno(stderr),
1437 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
Damien Millercfd6e4f2011-01-16 23:18:33 +11001438 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
Damien Miller95def091999-11-25 00:26:21 +11001439 error("Write failed flushing stderr buffer.");
Damien Millercfd6e4f2011-01-16 23:18:33 +11001440 else
1441 buffer_consume(&stderr_buffer, len);
Damien Miller95def091999-11-25 00:26:21 +11001442 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001443
Damien Miller95def091999-11-25 00:26:21 +11001444 /* Clear and free any buffers. */
jsg@openbsd.org458abc22016-01-23 05:31:35 +00001445 explicit_bzero(buf, sizeof(buf));
Damien Miller95def091999-11-25 00:26:21 +11001446 buffer_free(&stderr_buffer);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001447
Damien Miller95def091999-11-25 00:26:21 +11001448 /* Report bytes transferred, and transfer rates. */
1449 total_time = get_current_time() - start_time;
markus@openbsd.org091c3022015-01-19 19:52:16 +00001450 packet_get_bytes(&ibytes, &obytes);
Damien Millerb61f3fc2008-07-11 17:36:48 +10001451 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
Damien Miller821de0a2011-01-11 17:20:29 +11001452 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
Damien Miller95def091999-11-25 00:26:21 +11001453 if (total_time > 0)
Damien Millerb61f3fc2008-07-11 17:36:48 +10001454 verbose("Bytes per second: sent %.1f, received %.1f",
1455 obytes / total_time, ibytes / total_time);
Damien Miller95def091999-11-25 00:26:21 +11001456 /* Return the exit status of the program. */
1457 debug("Exit status %d", exit_status);
1458 return exit_status;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001459}
Damien Millerb38eff82000-04-01 11:09:21 +10001460
1461/*********/
1462
Ben Lindstrombba81212001-06-25 05:01:22 +00001463static Channel *
markus@openbsd.org8d057842016-09-30 09:19:13 +00001464client_request_forwarded_tcpip(const char *request_type, int rchan,
1465 u_int rwindow, u_int rmaxpack)
Damien Miller0bc1bd82000-11-13 22:57:25 +11001466{
Ben Lindstroma962c2f2002-07-04 00:14:17 +00001467 Channel *c = NULL;
markus@openbsd.org8d057842016-09-30 09:19:13 +00001468 struct sshbuf *b = NULL;
Damien Miller0bc1bd82000-11-13 22:57:25 +11001469 char *listen_address, *originator_address;
Damien Miller3dc71ad2009-01-28 16:31:22 +11001470 u_short listen_port, originator_port;
markus@openbsd.org8d057842016-09-30 09:19:13 +00001471 int r;
Damien Miller0bc1bd82000-11-13 22:57:25 +11001472
1473 /* Get rest of the packet */
1474 listen_address = packet_get_string(NULL);
1475 listen_port = packet_get_int();
1476 originator_address = packet_get_string(NULL);
1477 originator_port = packet_get_int();
Damien Miller48b03fc2002-01-22 23:11:40 +11001478 packet_check_eom();
Damien Miller0bc1bd82000-11-13 22:57:25 +11001479
Damien Miller7acefbb2014-07-18 14:11:24 +10001480 debug("%s: listen %s port %d, originator %s port %d", __func__,
1481 listen_address, listen_port, originator_address, originator_port);
Damien Miller0bc1bd82000-11-13 22:57:25 +11001482
Damien Miller4b3ed642014-07-02 15:29:40 +10001483 c = channel_connect_by_listen_address(listen_address, listen_port,
Damien Millerbd740252008-05-19 15:37:09 +10001484 "forwarded-tcpip", originator_address);
1485
markus@openbsd.org8d057842016-09-30 09:19:13 +00001486 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1487 if ((b = sshbuf_new()) == NULL) {
1488 error("%s: alloc reply", __func__);
1489 goto out;
1490 }
1491 /* reconstruct and send to muxclient */
1492 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1493 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1494 (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1495 (r = sshbuf_put_u32(b, rchan)) != 0 ||
1496 (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1497 (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1498 (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1499 (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1500 (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1501 (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1502 (r = sshbuf_put_stringb(&c->output, b)) != 0) {
1503 error("%s: compose for muxclient %s", __func__,
1504 ssh_err(r));
1505 goto out;
1506 }
1507 }
1508
1509 out:
1510 sshbuf_free(b);
Darren Tuckera627d422013-06-02 07:31:17 +10001511 free(originator_address);
1512 free(listen_address);
Damien Miller0bc1bd82000-11-13 22:57:25 +11001513 return c;
1514}
1515
Ben Lindstroma962c2f2002-07-04 00:14:17 +00001516static Channel *
Damien Miller7acefbb2014-07-18 14:11:24 +10001517client_request_forwarded_streamlocal(const char *request_type, int rchan)
1518{
1519 Channel *c = NULL;
1520 char *listen_path;
1521
1522 /* Get the remote path. */
1523 listen_path = packet_get_string(NULL);
1524 /* XXX: Skip reserved field for now. */
1525 if (packet_get_string_ptr(NULL) == NULL)
1526 fatal("%s: packet_get_string_ptr failed", __func__);
1527 packet_check_eom();
1528
1529 debug("%s: %s", __func__, listen_path);
1530
1531 c = channel_connect_by_listen_path(listen_path,
1532 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1533 free(listen_path);
1534 return c;
1535}
1536
1537static Channel *
Damien Miller0bc1bd82000-11-13 22:57:25 +11001538client_request_x11(const char *request_type, int rchan)
1539{
1540 Channel *c = NULL;
1541 char *originator;
Damien Miller3dc71ad2009-01-28 16:31:22 +11001542 u_short originator_port;
Ben Lindstrom99c73b32001-05-05 04:09:47 +00001543 int sock;
Damien Miller0bc1bd82000-11-13 22:57:25 +11001544
1545 if (!options.forward_x11) {
1546 error("Warning: ssh server tried X11 forwarding.");
Darren Tucker4d5cd332008-06-13 04:51:14 +10001547 error("Warning: this is probably a break-in attempt by a "
1548 "malicious server.");
Damien Miller0bc1bd82000-11-13 22:57:25 +11001549 return NULL;
1550 }
djm@openbsd.org1bf477d2015-07-01 02:26:31 +00001551 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
Damien Miller1ab6a512010-06-26 10:02:24 +10001552 verbose("Rejected X11 connection after ForwardX11Timeout "
1553 "expired");
1554 return NULL;
1555 }
Damien Miller0bc1bd82000-11-13 22:57:25 +11001556 originator = packet_get_string(NULL);
1557 if (datafellows & SSH_BUG_X11FWD) {
1558 debug2("buggy server: x11 request w/o originator_port");
1559 originator_port = 0;
1560 } else {
1561 originator_port = packet_get_int();
1562 }
Damien Miller48b03fc2002-01-22 23:11:40 +11001563 packet_check_eom();
Damien Miller0bc1bd82000-11-13 22:57:25 +11001564 /* XXX check permission */
Damien Millerd83ff352001-01-30 09:19:34 +11001565 debug("client_request_x11: request from %s %d", originator,
1566 originator_port);
Darren Tuckera627d422013-06-02 07:31:17 +10001567 free(originator);
Ben Lindstrom99c73b32001-05-05 04:09:47 +00001568 sock = x11_connect_display();
1569 if (sock < 0)
1570 return NULL;
1571 c = channel_new("x11",
1572 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
Damien Millerb1ca8bb2003-05-14 13:45:42 +10001573 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
Ben Lindstrom944c4f02001-09-18 05:51:13 +00001574 c->force_drain = 1;
Damien Miller0bc1bd82000-11-13 22:57:25 +11001575 return c;
1576}
1577
Ben Lindstroma962c2f2002-07-04 00:14:17 +00001578static Channel *
Damien Miller0bc1bd82000-11-13 22:57:25 +11001579client_request_agent(const char *request_type, int rchan)
1580{
1581 Channel *c = NULL;
djm@openbsd.org141efe42015-01-14 20:05:27 +00001582 int r, sock;
Damien Miller0bc1bd82000-11-13 22:57:25 +11001583
1584 if (!options.forward_agent) {
1585 error("Warning: ssh server tried agent forwarding.");
Darren Tucker4d5cd332008-06-13 04:51:14 +10001586 error("Warning: this is probably a break-in attempt by a "
1587 "malicious server.");
Damien Miller0bc1bd82000-11-13 22:57:25 +11001588 return NULL;
1589 }
djm@openbsd.org141efe42015-01-14 20:05:27 +00001590 if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1591 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1592 debug("%s: ssh_get_authentication_socket: %s",
1593 __func__, ssh_err(r));
Ben Lindstrom99c73b32001-05-05 04:09:47 +00001594 return NULL;
djm@openbsd.org141efe42015-01-14 20:05:27 +00001595 }
Ben Lindstrom99c73b32001-05-05 04:09:47 +00001596 c = channel_new("authentication agent connection",
1597 SSH_CHANNEL_OPEN, sock, sock, -1,
Darren Tucker5baa1702007-12-29 09:37:10 +11001598 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
Damien Millerb1ca8bb2003-05-14 13:45:42 +10001599 "authentication agent connection", 1);
Ben Lindstrom944c4f02001-09-18 05:51:13 +00001600 c->force_drain = 1;
Damien Miller0bc1bd82000-11-13 22:57:25 +11001601 return c;
1602}
1603
Damien Millerb3ce9fe2007-08-08 14:32:41 +10001604int
1605client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1606{
1607 Channel *c;
1608 int fd;
1609
1610 if (tun_mode == SSH_TUNMODE_NO)
1611 return 0;
1612
Damien Millerb3ce9fe2007-08-08 14:32:41 +10001613 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1614
1615 /* Open local tunnel device */
1616 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1617 error("Tunnel device open failed.");
1618 return -1;
1619 }
1620
1621 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1622 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1623 c->datagram = 1;
1624
1625#if defined(SSH_TUN_FILTER)
1626 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1627 channel_register_filter(c->self, sys_tun_infilter,
Darren Tucker1cf65ae2008-06-13 05:09:18 +10001628 sys_tun_outfilter, NULL, NULL);
Damien Millerb3ce9fe2007-08-08 14:32:41 +10001629#endif
1630
1631 packet_start(SSH2_MSG_CHANNEL_OPEN);
1632 packet_put_cstring("tun@openssh.com");
1633 packet_put_int(c->self);
1634 packet_put_int(c->local_window_max);
1635 packet_put_int(c->local_maxpacket);
1636 packet_put_int(tun_mode);
1637 packet_put_int(remote_tun);
1638 packet_send();
1639
1640 return 0;
1641}
1642
Damien Millerbd483e72000-04-30 10:00:53 +10001643/* XXXX move to generic input handler */
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001644static int
Damien Miller630d6f42002-01-22 23:17:30 +11001645client_input_channel_open(int type, u_int32_t seq, void *ctxt)
Damien Millerbd483e72000-04-30 10:00:53 +10001646{
1647 Channel *c = NULL;
1648 char *ctype;
Damien Millerbd483e72000-04-30 10:00:53 +10001649 int rchan;
Ben Lindstrom4fed2be2002-06-25 23:17:36 +00001650 u_int rmaxpack, rwindow, len;
Damien Millerbd483e72000-04-30 10:00:53 +10001651
1652 ctype = packet_get_string(&len);
1653 rchan = packet_get_int();
1654 rwindow = packet_get_int();
1655 rmaxpack = packet_get_int();
1656
Damien Millere247cc42000-05-07 12:03:14 +10001657 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
Damien Millerbd483e72000-04-30 10:00:53 +10001658 ctype, rchan, rwindow, rmaxpack);
1659
Damien Miller0bc1bd82000-11-13 22:57:25 +11001660 if (strcmp(ctype, "forwarded-tcpip") == 0) {
markus@openbsd.org8d057842016-09-30 09:19:13 +00001661 c = client_request_forwarded_tcpip(ctype, rchan, rwindow,
1662 rmaxpack);
Damien Miller7acefbb2014-07-18 14:11:24 +10001663 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1664 c = client_request_forwarded_streamlocal(ctype, rchan);
Damien Miller0bc1bd82000-11-13 22:57:25 +11001665 } else if (strcmp(ctype, "x11") == 0) {
1666 c = client_request_x11(ctype, rchan);
1667 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1668 c = client_request_agent(ctype, rchan);
Damien Millerbd483e72000-04-30 10:00:53 +10001669 }
markus@openbsd.org8d057842016-09-30 09:19:13 +00001670 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1671 debug3("proxied to downstream: %s", ctype);
1672 } else if (c != NULL) {
Damien Millerbd483e72000-04-30 10:00:53 +10001673 debug("confirm %s", ctype);
1674 c->remote_id = rchan;
1675 c->remote_window = rwindow;
1676 c->remote_maxpacket = rmaxpack;
Ben Lindstroma69d89b2001-05-09 00:01:18 +00001677 if (c->type != SSH_CHANNEL_CONNECTING) {
1678 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1679 packet_put_int(c->remote_id);
1680 packet_put_int(c->self);
1681 packet_put_int(c->local_window);
1682 packet_put_int(c->local_maxpacket);
1683 packet_send();
1684 }
Damien Millerbd483e72000-04-30 10:00:53 +10001685 } else {
1686 debug("failure %s", ctype);
1687 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1688 packet_put_int(rchan);
1689 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
Ben Lindstromf3436742001-04-29 19:52:00 +00001690 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
Ben Lindstroma69d89b2001-05-09 00:01:18 +00001691 packet_put_cstring("open failed");
Ben Lindstromf3436742001-04-29 19:52:00 +00001692 packet_put_cstring("");
1693 }
Damien Millerbd483e72000-04-30 10:00:53 +10001694 packet_send();
1695 }
Darren Tuckera627d422013-06-02 07:31:17 +10001696 free(ctype);
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001697 return 0;
Damien Millerbd483e72000-04-30 10:00:53 +10001698}
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00001699
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001700static int
Damien Miller630d6f42002-01-22 23:17:30 +11001701client_input_channel_req(int type, u_int32_t seq, void *ctxt)
Ben Lindstrom5b828322001-02-09 01:34:36 +00001702{
1703 Channel *c = NULL;
Damien Miller0e220db2004-06-15 10:34:08 +10001704 int exitval, id, reply, success = 0;
Ben Lindstrom5b828322001-02-09 01:34:36 +00001705 char *rtype;
1706
1707 id = packet_get_int();
markus@openbsd.org8d057842016-09-30 09:19:13 +00001708 c = channel_lookup(id);
1709 if (channel_proxy_upstream(c, type, seq, ctxt))
1710 return 0;
Ben Lindstrom5b828322001-02-09 01:34:36 +00001711 rtype = packet_get_string(NULL);
1712 reply = packet_get_char();
1713
1714 debug("client_input_channel_req: channel %d rtype %s reply %d",
1715 id, rtype, reply);
1716
Damien Miller3bbd8782004-06-18 22:23:22 +10001717 if (id == -1) {
1718 error("client_input_channel_req: request for channel -1");
markus@openbsd.org8d057842016-09-30 09:19:13 +00001719 } else if (c == NULL) {
Darren Tucker4d5cd332008-06-13 04:51:14 +10001720 error("client_input_channel_req: channel %d: "
1721 "unknown channel", id);
Damien Millerbab9bd42008-05-19 16:06:47 +10001722 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1723 packet_check_eom();
1724 chan_rcvd_eow(c);
Ben Lindstrom5b828322001-02-09 01:34:36 +00001725 } else if (strcmp(rtype, "exit-status") == 0) {
Damien Miller0e220db2004-06-15 10:34:08 +10001726 exitval = packet_get_int();
Damien Millere1537f92010-01-26 13:26:22 +11001727 if (c->ctl_chan != -1) {
1728 mux_exit_message(c, exitval);
Damien Miller0e220db2004-06-15 10:34:08 +10001729 success = 1;
Darren Tucker29440822010-01-08 17:08:35 +11001730 } else if (id == session_ident) {
1731 /* Record exit value of local session */
1732 success = 1;
1733 exit_status = exitval;
1734 } else {
Damien Miller36f57eb2010-01-30 17:28:34 +11001735 /* Probably for a mux channel that has already closed */
1736 debug("%s: no sink for exit-status on channel %d",
1737 __func__, id);
Damien Miller0e220db2004-06-15 10:34:08 +10001738 }
Damien Miller48b03fc2002-01-22 23:11:40 +11001739 packet_check_eom();
Ben Lindstrom5b828322001-02-09 01:34:36 +00001740 }
Damien Millerc5893782014-05-15 13:48:49 +10001741 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
Ben Lindstrom5b828322001-02-09 01:34:36 +00001742 packet_start(success ?
1743 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
Damien Miller8533c782008-12-08 09:54:40 +11001744 packet_put_int(c->remote_id);
Ben Lindstrom5b828322001-02-09 01:34:36 +00001745 packet_send();
1746 }
Darren Tuckera627d422013-06-02 07:31:17 +10001747 free(rtype);
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00001748 return 0;
Ben Lindstrom5b828322001-02-09 01:34:36 +00001749}
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00001750
djm@openbsd.org523463a2015-02-16 22:13:32 +00001751struct hostkeys_update_ctx {
1752 /* The hostname and (optionally) IP address string for the server */
1753 char *host_str, *ip_str;
1754
1755 /*
1756 * Keys received from the server and a flag for each indicating
1757 * whether they already exist in known_hosts.
1758 * keys_seen is filled in by hostkeys_find() and later (for new
1759 * keys) by client_global_hostkeys_private_confirm().
1760 */
1761 struct sshkey **keys;
1762 int *keys_seen;
djm@openbsd.org05164352017-04-30 23:21:54 +00001763 size_t nkeys, nnew;
djm@openbsd.org523463a2015-02-16 22:13:32 +00001764
1765 /*
1766 * Keys that are in known_hosts, but were not present in the update
1767 * from the server (i.e. scheduled to be deleted).
1768 * Filled in by hostkeys_find().
1769 */
1770 struct sshkey **old_keys;
1771 size_t nold;
1772};
1773
1774static void
1775hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
1776{
1777 size_t i;
1778
1779 if (ctx == NULL)
1780 return;
1781 for (i = 0; i < ctx->nkeys; i++)
1782 sshkey_free(ctx->keys[i]);
1783 free(ctx->keys);
1784 free(ctx->keys_seen);
1785 for (i = 0; i < ctx->nold; i++)
1786 sshkey_free(ctx->old_keys[i]);
1787 free(ctx->old_keys);
1788 free(ctx->host_str);
1789 free(ctx->ip_str);
1790 free(ctx);
1791}
1792
1793static int
1794hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
1795{
1796 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1797 size_t i;
1798 struct sshkey **tmp;
1799
djm@openbsd.org873d3e72017-04-30 23:18:44 +00001800 if (l->status != HKF_STATUS_MATCHED || l->key == NULL)
djm@openbsd.org523463a2015-02-16 22:13:32 +00001801 return 0;
1802
1803 /* Mark off keys we've already seen for this host */
1804 for (i = 0; i < ctx->nkeys; i++) {
1805 if (sshkey_equal(l->key, ctx->keys[i])) {
1806 debug3("%s: found %s key at %s:%ld", __func__,
1807 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
1808 ctx->keys_seen[i] = 1;
1809 return 0;
1810 }
1811 }
1812 /* This line contained a key that not offered by the server */
1813 debug3("%s: deprecated %s key at %s:%ld", __func__,
1814 sshkey_ssh_name(l->key), l->path, l->linenum);
1815 if ((tmp = reallocarray(ctx->old_keys, ctx->nold + 1,
1816 sizeof(*ctx->old_keys))) == NULL)
1817 fatal("%s: reallocarray failed nold = %zu",
1818 __func__, ctx->nold);
1819 ctx->old_keys = tmp;
1820 ctx->old_keys[ctx->nold++] = l->key;
1821 l->key = NULL;
1822
1823 return 0;
1824}
1825
1826static void
1827update_known_hosts(struct hostkeys_update_ctx *ctx)
1828{
djm@openbsd.orgf2293a62015-02-23 16:33:25 +00001829 int r, was_raw = 0;
1830 int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
djm@openbsd.org523463a2015-02-16 22:13:32 +00001831 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
1832 char *fp, *response;
1833 size_t i;
1834
1835 for (i = 0; i < ctx->nkeys; i++) {
1836 if (ctx->keys_seen[i] != 2)
1837 continue;
1838 if ((fp = sshkey_fingerprint(ctx->keys[i],
1839 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1840 fatal("%s: sshkey_fingerprint failed", __func__);
1841 do_log2(loglevel, "Learned new hostkey: %s %s",
1842 sshkey_type(ctx->keys[i]), fp);
1843 free(fp);
1844 }
1845 for (i = 0; i < ctx->nold; i++) {
1846 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
1847 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1848 fatal("%s: sshkey_fingerprint failed", __func__);
1849 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
1850 sshkey_type(ctx->old_keys[i]), fp);
1851 free(fp);
1852 }
1853 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
djm@openbsd.orgf2293a62015-02-23 16:33:25 +00001854 if (get_saved_tio() != NULL) {
1855 leave_raw_mode(1);
1856 was_raw = 1;
1857 }
djm@openbsd.org523463a2015-02-16 22:13:32 +00001858 response = NULL;
1859 for (i = 0; !quit_pending && i < 3; i++) {
1860 free(response);
1861 response = read_passphrase("Accept updated hostkeys? "
1862 "(yes/no): ", RP_ECHO);
1863 if (strcasecmp(response, "yes") == 0)
1864 break;
1865 else if (quit_pending || response == NULL ||
1866 strcasecmp(response, "no") == 0) {
1867 options.update_hostkeys = 0;
1868 break;
1869 } else {
1870 do_log2(loglevel, "Please enter "
1871 "\"yes\" or \"no\"");
1872 }
1873 }
1874 if (quit_pending || i >= 3 || response == NULL)
1875 options.update_hostkeys = 0;
1876 free(response);
djm@openbsd.orgf2293a62015-02-23 16:33:25 +00001877 if (was_raw)
1878 enter_raw_mode(1);
djm@openbsd.org523463a2015-02-16 22:13:32 +00001879 }
1880
1881 /*
1882 * Now that all the keys are verified, we can go ahead and replace
1883 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
1884 * cancel the operation).
1885 */
1886 if (options.update_hostkeys != 0 &&
1887 (r = hostfile_replace_entries(options.user_hostfiles[0],
1888 ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
1889 options.hash_known_hosts, 0,
1890 options.fingerprint_hash)) != 0)
1891 error("%s: hostfile_replace_entries failed: %s",
1892 __func__, ssh_err(r));
1893}
1894
1895static void
1896client_global_hostkeys_private_confirm(int type, u_int32_t seq, void *_ctx)
1897{
1898 struct ssh *ssh = active_state; /* XXX */
1899 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1900 size_t i, ndone;
1901 struct sshbuf *signdata;
1902 int r;
1903 const u_char *sig;
1904 size_t siglen;
1905
1906 if (ctx->nnew == 0)
1907 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
1908 if (type != SSH2_MSG_REQUEST_SUCCESS) {
1909 error("Server failed to confirm ownership of "
1910 "private host keys");
1911 hostkeys_update_ctx_free(ctx);
1912 return;
1913 }
1914 if ((signdata = sshbuf_new()) == NULL)
1915 fatal("%s: sshbuf_new failed", __func__);
1916 /* Don't want to accidentally accept an unbound signature */
1917 if (ssh->kex->session_id_len == 0)
1918 fatal("%s: ssh->kex->session_id_len == 0", __func__);
1919 /*
1920 * Expect a signature for each of the ctx->nnew private keys we
1921 * haven't seen before. They will be in the same order as the
1922 * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
1923 */
1924 for (ndone = i = 0; i < ctx->nkeys; i++) {
1925 if (ctx->keys_seen[i])
1926 continue;
1927 /* Prepare data to be signed: session ID, unique string, key */
1928 sshbuf_reset(signdata);
djm@openbsd.org44732de2015-02-20 22:17:21 +00001929 if ( (r = sshbuf_put_cstring(signdata,
1930 "hostkeys-prove-00@openssh.com")) != 0 ||
1931 (r = sshbuf_put_string(signdata, ssh->kex->session_id,
djm@openbsd.org523463a2015-02-16 22:13:32 +00001932 ssh->kex->session_id_len)) != 0 ||
djm@openbsd.org523463a2015-02-16 22:13:32 +00001933 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
1934 fatal("%s: failed to prepare signature: %s",
1935 __func__, ssh_err(r));
1936 /* Extract and verify signature */
1937 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
1938 error("%s: couldn't parse message: %s",
1939 __func__, ssh_err(r));
1940 goto out;
1941 }
1942 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
1943 sshbuf_ptr(signdata), sshbuf_len(signdata), 0)) != 0) {
1944 error("%s: server gave bad signature for %s key %zu",
1945 __func__, sshkey_type(ctx->keys[i]), i);
1946 goto out;
1947 }
1948 /* Key is good. Mark it as 'seen' */
1949 ctx->keys_seen[i] = 2;
1950 ndone++;
1951 }
1952 if (ndone != ctx->nnew)
1953 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
1954 ndone, ctx->nnew); /* Shouldn't happen */
1955 ssh_packet_check_eom(ssh);
1956
1957 /* Make the edits to known_hosts */
1958 update_known_hosts(ctx);
1959 out:
1960 hostkeys_update_ctx_free(ctx);
1961}
1962
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00001963/*
djm@openbsd.org894221a2017-03-10 05:01:13 +00001964 * Returns non-zero if the key is accepted by HostkeyAlgorithms.
1965 * Made slightly less trivial by the multiple RSA signature algorithm names.
1966 */
1967static int
1968key_accepted_by_hostkeyalgs(const struct sshkey *key)
1969{
1970 const char *ktype = sshkey_ssh_name(key);
1971 const char *hostkeyalgs = options.hostkeyalgorithms != NULL ?
1972 options.hostkeyalgorithms : KEX_DEFAULT_PK_ALG;
1973
1974 if (key == NULL || key->type == KEY_UNSPEC)
1975 return 0;
1976 if (key->type == KEY_RSA &&
1977 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
1978 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
1979 return 1;
1980 return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
1981}
1982
1983/*
djm@openbsd.org44732de2015-02-20 22:17:21 +00001984 * Handle hostkeys-00@openssh.com global request to inform the client of all
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00001985 * the server's hostkeys. The keys are checked against the user's
1986 * HostkeyAlgorithms preference before they are accepted.
1987 */
1988static int
1989client_input_hostkeys(void)
1990{
djm@openbsd.org523463a2015-02-16 22:13:32 +00001991 struct ssh *ssh = active_state; /* XXX */
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00001992 const u_char *blob = NULL;
djm@openbsd.org523463a2015-02-16 22:13:32 +00001993 size_t i, len = 0;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00001994 struct sshbuf *buf = NULL;
djm@openbsd.org523463a2015-02-16 22:13:32 +00001995 struct sshkey *key = NULL, **tmp;
1996 int r;
1997 char *fp;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00001998 static int hostkeys_seen = 0; /* XXX use struct ssh */
djm@openbsd.org6c5c9492015-02-16 22:08:57 +00001999 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
djm@openbsd.orga63cfa22015-02-25 19:54:02 +00002000 struct hostkeys_update_ctx *ctx = NULL;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002001
2002 if (hostkeys_seen)
2003 fatal("%s: server already sent hostkeys", __func__);
djm@openbsd.org523463a2015-02-16 22:13:32 +00002004 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2005 options.batch_mode)
2006 return 1; /* won't ask in batchmode, so don't even try */
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002007 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2008 return 1;
djm@openbsd.orga63cfa22015-02-25 19:54:02 +00002009
2010 ctx = xcalloc(1, sizeof(*ctx));
djm@openbsd.org523463a2015-02-16 22:13:32 +00002011 while (ssh_packet_remaining(ssh) > 0) {
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002012 sshkey_free(key);
2013 key = NULL;
djm@openbsd.org523463a2015-02-16 22:13:32 +00002014 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2015 error("%s: couldn't parse message: %s",
2016 __func__, ssh_err(r));
2017 goto out;
2018 }
djm@openbsd.org44732de2015-02-20 22:17:21 +00002019 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2020 error("%s: parse key: %s", __func__, ssh_err(r));
2021 goto out;
2022 }
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002023 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2024 SSH_FP_DEFAULT);
2025 debug3("%s: received %s key %s", __func__,
2026 sshkey_type(key), fp);
2027 free(fp);
markus@openbsd.org3a1638d2015-07-10 06:21:53 +00002028
djm@openbsd.org894221a2017-03-10 05:01:13 +00002029 if (!key_accepted_by_hostkeyalgs(key)) {
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002030 debug3("%s: %s key not permitted by HostkeyAlgorithms",
2031 __func__, sshkey_ssh_name(key));
2032 continue;
2033 }
djm@openbsd.org523463a2015-02-16 22:13:32 +00002034 /* Skip certs */
2035 if (sshkey_is_cert(key)) {
2036 debug3("%s: %s key is a certificate; skipping",
2037 __func__, sshkey_ssh_name(key));
2038 continue;
2039 }
2040 /* Ensure keys are unique */
2041 for (i = 0; i < ctx->nkeys; i++) {
2042 if (sshkey_equal(key, ctx->keys[i])) {
2043 error("%s: received duplicated %s host key",
2044 __func__, sshkey_ssh_name(key));
2045 goto out;
2046 }
2047 }
2048 /* Key is good, record it */
2049 if ((tmp = reallocarray(ctx->keys, ctx->nkeys + 1,
2050 sizeof(*ctx->keys))) == NULL)
2051 fatal("%s: reallocarray failed nkeys = %zu",
2052 __func__, ctx->nkeys);
2053 ctx->keys = tmp;
2054 ctx->keys[ctx->nkeys++] = key;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002055 key = NULL;
2056 }
2057
djm@openbsd.org523463a2015-02-16 22:13:32 +00002058 if (ctx->nkeys == 0) {
djm@openbsd.org44732de2015-02-20 22:17:21 +00002059 debug("%s: server sent no hostkeys", __func__);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002060 goto out;
2061 }
djm@openbsd.org44732de2015-02-20 22:17:21 +00002062
djm@openbsd.org523463a2015-02-16 22:13:32 +00002063 if ((ctx->keys_seen = calloc(ctx->nkeys,
2064 sizeof(*ctx->keys_seen))) == NULL)
2065 fatal("%s: calloc failed", __func__);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002066
djm@openbsd.org6c5c9492015-02-16 22:08:57 +00002067 get_hostfile_hostname_ipaddr(host,
2068 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
djm@openbsd.org523463a2015-02-16 22:13:32 +00002069 options.port, &ctx->host_str,
2070 options.check_host_ip ? &ctx->ip_str : NULL);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002071
djm@openbsd.org523463a2015-02-16 22:13:32 +00002072 /* Find which keys we already know about. */
2073 if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2074 ctx, ctx->host_str, ctx->ip_str,
2075 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2076 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002077 goto out;
2078 }
2079
djm@openbsd.org523463a2015-02-16 22:13:32 +00002080 /* Figure out if we have any new keys to add */
2081 ctx->nnew = 0;
2082 for (i = 0; i < ctx->nkeys; i++) {
2083 if (!ctx->keys_seen[i])
2084 ctx->nnew++;
2085 }
2086
2087 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2088 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2089
2090 if (ctx->nnew == 0 && ctx->nold != 0) {
2091 /* We have some keys to remove. Just do it. */
2092 update_known_hosts(ctx);
2093 } else if (ctx->nnew != 0) {
2094 /*
2095 * We have received hitherto-unseen keys from the server.
2096 * Ask the server to confirm ownership of the private halves.
2097 */
2098 debug3("%s: asking server to prove ownership for %zu keys",
2099 __func__, ctx->nnew);
2100 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2101 (r = sshpkt_put_cstring(ssh,
djm@openbsd.org44732de2015-02-20 22:17:21 +00002102 "hostkeys-prove-00@openssh.com")) != 0 ||
djm@openbsd.org523463a2015-02-16 22:13:32 +00002103 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2104 fatal("%s: cannot prepare packet: %s",
2105 __func__, ssh_err(r));
2106 if ((buf = sshbuf_new()) == NULL)
2107 fatal("%s: sshbuf_new", __func__);
2108 for (i = 0; i < ctx->nkeys; i++) {
2109 if (ctx->keys_seen[i])
2110 continue;
2111 sshbuf_reset(buf);
2112 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2113 fatal("%s: sshkey_putb: %s",
2114 __func__, ssh_err(r));
2115 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2116 fatal("%s: sshpkt_put_string: %s",
2117 __func__, ssh_err(r));
2118 }
2119 if ((r = sshpkt_send(ssh)) != 0)
2120 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2121 client_register_global_confirm(
2122 client_global_hostkeys_private_confirm, ctx);
2123 ctx = NULL; /* will be freed in callback */
2124 }
2125
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002126 /* Success */
2127 out:
djm@openbsd.org523463a2015-02-16 22:13:32 +00002128 hostkeys_update_ctx_free(ctx);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002129 sshkey_free(key);
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002130 sshbuf_free(buf);
djm@openbsd.org523463a2015-02-16 22:13:32 +00002131 /*
2132 * NB. Return success for all cases. The server doesn't need to know
2133 * what the client does with its hosts file.
2134 */
2135 return 1;
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002136}
2137
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00002138static int
Damien Millerc3fa4072002-01-22 23:21:58 +11002139client_input_global_request(int type, u_int32_t seq, void *ctxt)
2140{
2141 char *rtype;
2142 int want_reply;
2143 int success = 0;
2144
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002145 rtype = packet_get_cstring(NULL);
Damien Millerc3fa4072002-01-22 23:21:58 +11002146 want_reply = packet_get_char();
Damien Miller509b0102003-12-17 16:33:10 +11002147 debug("client_input_global_request: rtype %s want_reply %d",
2148 rtype, want_reply);
djm@openbsd.org44732de2015-02-20 22:17:21 +00002149 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
djm@openbsd.org8d4f8722015-01-26 03:04:45 +00002150 success = client_input_hostkeys();
Damien Millerc3fa4072002-01-22 23:21:58 +11002151 if (want_reply) {
2152 packet_start(success ?
2153 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2154 packet_send();
2155 packet_write_wait();
2156 }
Darren Tuckera627d422013-06-02 07:31:17 +10002157 free(rtype);
markus@openbsd.org3fdc88a2015-01-19 20:07:45 +00002158 return 0;
Damien Millerc3fa4072002-01-22 23:21:58 +11002159}
Damien Millerbd483e72000-04-30 10:00:53 +10002160
Damien Miller0e220db2004-06-15 10:34:08 +10002161void
Darren Tuckerfc959702004-07-17 16:12:08 +10002162client_session2_setup(int id, int want_tty, int want_subsystem,
Damien Miller5771ed72008-05-19 15:35:33 +10002163 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
Damien Miller0e220db2004-06-15 10:34:08 +10002164{
2165 int len;
Darren Tucker5d78de62004-11-05 20:35:44 +11002166 Channel *c = NULL;
Damien Miller0e220db2004-06-15 10:34:08 +10002167
2168 debug2("%s: id %d", __func__, id);
2169
Darren Tucker5d78de62004-11-05 20:35:44 +11002170 if ((c = channel_lookup(id)) == NULL)
2171 fatal("client_session2_setup: channel %d: unknown channel", id);
2172
Damien Miller0dac6fb2010-11-20 15:19:38 +11002173 packet_set_interactive(want_tty,
2174 options.ip_qos_interactive, options.ip_qos_bulk);
2175
Damien Miller0e220db2004-06-15 10:34:08 +10002176 if (want_tty) {
2177 struct winsize ws;
Damien Miller0e220db2004-06-15 10:34:08 +10002178
2179 /* Store window size in the packet. */
2180 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2181 memset(&ws, 0, sizeof(ws));
2182
Damien Miller5771ed72008-05-19 15:35:33 +10002183 channel_request_start(id, "pty-req", 1);
Damien Miller555f3b82011-05-15 08:48:05 +10002184 client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
Damien Miller0e220db2004-06-15 10:34:08 +10002185 packet_put_cstring(term != NULL ? term : "");
Damien Miller71a73672006-03-26 14:04:36 +11002186 packet_put_int((u_int)ws.ws_col);
2187 packet_put_int((u_int)ws.ws_row);
2188 packet_put_int((u_int)ws.ws_xpixel);
2189 packet_put_int((u_int)ws.ws_ypixel);
Darren Tuckerdf189fb2008-06-08 12:55:32 +10002190 if (tiop == NULL)
2191 tiop = get_saved_tio();
2192 tty_make_modes(-1, tiop);
Damien Miller0e220db2004-06-15 10:34:08 +10002193 packet_send();
2194 /* XXX wait for reply */
Darren Tucker5d78de62004-11-05 20:35:44 +11002195 c->client_tty = 1;
Damien Miller0e220db2004-06-15 10:34:08 +10002196 }
2197
2198 /* Transfer any environment variables from client to server */
Damien Miller3756dce2004-06-18 01:17:29 +10002199 if (options.num_send_env != 0 && env != NULL) {
Damien Miller0e220db2004-06-15 10:34:08 +10002200 int i, j, matched;
Damien Miller0e220db2004-06-15 10:34:08 +10002201 char *name, *val;
2202
2203 debug("Sending environment.");
Damien Miller3756dce2004-06-18 01:17:29 +10002204 for (i = 0; env[i] != NULL; i++) {
Damien Miller0e220db2004-06-15 10:34:08 +10002205 /* Split */
Damien Miller3756dce2004-06-18 01:17:29 +10002206 name = xstrdup(env[i]);
Damien Miller0e220db2004-06-15 10:34:08 +10002207 if ((val = strchr(name, '=')) == NULL) {
Darren Tuckera627d422013-06-02 07:31:17 +10002208 free(name);
Damien Miller0e220db2004-06-15 10:34:08 +10002209 continue;
2210 }
2211 *val++ = '\0';
2212
2213 matched = 0;
2214 for (j = 0; j < options.num_send_env; j++) {
2215 if (match_pattern(name, options.send_env[j])) {
2216 matched = 1;
2217 break;
2218 }
2219 }
2220 if (!matched) {
2221 debug3("Ignored env %s", name);
Darren Tuckera627d422013-06-02 07:31:17 +10002222 free(name);
Damien Miller0e220db2004-06-15 10:34:08 +10002223 continue;
2224 }
2225
2226 debug("Sending env %s = %s", name, val);
2227 channel_request_start(id, "env", 0);
2228 packet_put_cstring(name);
2229 packet_put_cstring(val);
2230 packet_send();
Darren Tuckera627d422013-06-02 07:31:17 +10002231 free(name);
Damien Miller0e220db2004-06-15 10:34:08 +10002232 }
2233 }
2234
2235 len = buffer_len(cmd);
2236 if (len > 0) {
2237 if (len > 900)
2238 len = 900;
2239 if (want_subsystem) {
Damien Miller5771ed72008-05-19 15:35:33 +10002240 debug("Sending subsystem: %.*s",
2241 len, (u_char*)buffer_ptr(cmd));
2242 channel_request_start(id, "subsystem", 1);
Damien Miller555f3b82011-05-15 08:48:05 +10002243 client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
Damien Miller0e220db2004-06-15 10:34:08 +10002244 } else {
Damien Miller5771ed72008-05-19 15:35:33 +10002245 debug("Sending command: %.*s",
2246 len, (u_char*)buffer_ptr(cmd));
2247 channel_request_start(id, "exec", 1);
Damien Miller555f3b82011-05-15 08:48:05 +10002248 client_expect_confirm(id, "exec", CONFIRM_CLOSE);
Damien Miller0e220db2004-06-15 10:34:08 +10002249 }
2250 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2251 packet_send();
2252 } else {
Damien Miller5771ed72008-05-19 15:35:33 +10002253 channel_request_start(id, "shell", 1);
Damien Miller555f3b82011-05-15 08:48:05 +10002254 client_expect_confirm(id, "shell", CONFIRM_CLOSE);
Damien Miller0e220db2004-06-15 10:34:08 +10002255 packet_send();
2256 }
2257}
2258
Ben Lindstrombba81212001-06-25 05:01:22 +00002259static void
djm@openbsd.org97f4d302017-04-30 23:13:25 +00002260client_init_dispatch(void)
Damien Miller1383bd82000-04-06 12:32:37 +10002261{
Ben Lindstrom8ac91062001-04-04 17:57:54 +00002262 dispatch_init(&dispatch_protocol_error);
Damien Miller2797f7f2002-04-23 21:09:44 +10002263
Damien Miller1383bd82000-04-06 12:32:37 +10002264 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2265 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2266 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2267 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
Damien Millerbd483e72000-04-30 10:00:53 +10002268 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
Damien Miller1383bd82000-04-06 12:32:37 +10002269 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2270 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
Ben Lindstrom5b828322001-02-09 01:34:36 +00002271 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
Damien Miller1383bd82000-04-06 12:32:37 +10002272 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
Damien Millerb84886b2008-05-19 15:05:07 +10002273 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2274 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
Damien Millerc3fa4072002-01-22 23:21:58 +11002275 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
Ben Lindstrom8ac91062001-04-04 17:57:54 +00002276
2277 /* rekeying */
2278 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
Damien Miller2797f7f2002-04-23 21:09:44 +10002279
2280 /* global request reply messages */
2281 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2282 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
Damien Miller1383bd82000-04-06 12:32:37 +10002283}
Darren Tucker4d5cd332008-06-13 04:51:14 +10002284
Damien Miller6c3eec72011-05-05 14:16:22 +10002285void
2286client_stop_mux(void)
2287{
2288 if (options.control_path != NULL && muxserver_sock != -1)
2289 unlink(options.control_path);
2290 /*
Darren Tucker48bf4b02012-09-07 16:38:53 +10002291 * If we are in persist mode, or don't have a shell, signal that we
2292 * should close when all active channels are closed.
Damien Miller6c3eec72011-05-05 14:16:22 +10002293 */
Darren Tucker48bf4b02012-09-07 16:38:53 +10002294 if (options.control_persist || no_shell_flag) {
Damien Miller6c3eec72011-05-05 14:16:22 +10002295 session_closed = 1;
Damien Miller4ac99c32011-06-20 14:43:31 +10002296 setproctitle("[stopped mux]");
2297 }
Damien Miller6c3eec72011-05-05 14:16:22 +10002298}
2299
Darren Tucker9a2c4cd2003-09-22 21:16:05 +10002300/* client specific fatal cleanup */
2301void
Darren Tucker3e33cec2003-10-02 16:12:36 +10002302cleanup_exit(int i)
Darren Tucker9a2c4cd2003-09-22 21:16:05 +10002303{
Damien Miller21771e22011-05-15 08:45:50 +10002304 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
Darren Tucker9a2c4cd2003-09-22 21:16:05 +10002305 leave_non_blocking();
Damien Millerb1cbfa22008-05-19 16:00:08 +10002306 if (options.control_path != NULL && muxserver_sock != -1)
Damien Miller0e220db2004-06-15 10:34:08 +10002307 unlink(options.control_path);
Damien Millera41ccca2010-10-07 22:07:32 +11002308 ssh_kill_proxy_command();
Darren Tucker3e33cec2003-10-02 16:12:36 +10002309 _exit(i);
Darren Tucker9a2c4cd2003-09-22 21:16:05 +10002310}