GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.bin/ssh/ssh/../ssh.c Lines: 0 1020 0.0 %
Date: 2017-11-13 Branches: 0 617 0.0 %

Line Branch Exec Source
1
/* $OpenBSD: ssh.c,v 1.469 2017/11/01 00:04:15 djm Exp $ */
2
/*
3
 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4
 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5
 *                    All rights reserved
6
 * Ssh client program.  This program can be used to log into a remote machine.
7
 * The software supports strong authentication, encryption, and forwarding
8
 * of X11, TCP/IP, and authentication connections.
9
 *
10
 * As far as I am concerned, the code I have written for this software
11
 * can be used freely for any purpose.  Any derived versions of this
12
 * software must be clearly marked as such, and if the derived work is
13
 * incompatible with the protocol description in the RFC file, it must be
14
 * called by a name other than "ssh" or "Secure Shell".
15
 *
16
 * Copyright (c) 1999 Niels Provos.  All rights reserved.
17
 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
18
 *
19
 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20
 * in Canada (German citizen).
21
 *
22
 * Redistribution and use in source and binary forms, with or without
23
 * modification, are permitted provided that the following conditions
24
 * are met:
25
 * 1. Redistributions of source code must retain the above copyright
26
 *    notice, this list of conditions and the following disclaimer.
27
 * 2. Redistributions in binary form must reproduce the above copyright
28
 *    notice, this list of conditions and the following disclaimer in the
29
 *    documentation and/or other materials provided with the distribution.
30
 *
31
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41
 */
42
43
#include <sys/types.h>
44
#include <sys/ioctl.h>
45
#include <sys/queue.h>
46
#include <sys/resource.h>
47
#include <sys/socket.h>
48
#include <sys/stat.h>
49
#include <sys/time.h>
50
#include <sys/wait.h>
51
52
#include <ctype.h>
53
#include <errno.h>
54
#include <fcntl.h>
55
#include <netdb.h>
56
#include <paths.h>
57
#include <pwd.h>
58
#include <signal.h>
59
#include <stddef.h>
60
#include <stdio.h>
61
#include <stdlib.h>
62
#include <string.h>
63
#include <unistd.h>
64
#include <limits.h>
65
#include <locale.h>
66
67
#ifdef WITH_OPENSSL
68
#include <openssl/evp.h>
69
#include <openssl/err.h>
70
#endif
71
72
#include "xmalloc.h"
73
#include "ssh.h"
74
#include "ssh2.h"
75
#include "canohost.h"
76
#include "compat.h"
77
#include "cipher.h"
78
#include "digest.h"
79
#include "packet.h"
80
#include "buffer.h"
81
#include "channels.h"
82
#include "key.h"
83
#include "authfd.h"
84
#include "authfile.h"
85
#include "pathnames.h"
86
#include "dispatch.h"
87
#include "clientloop.h"
88
#include "log.h"
89
#include "misc.h"
90
#include "readconf.h"
91
#include "sshconnect.h"
92
#include "kex.h"
93
#include "mac.h"
94
#include "sshpty.h"
95
#include "match.h"
96
#include "msg.h"
97
#include "uidswap.h"
98
#include "version.h"
99
#include "ssherr.h"
100
#include "myproposal.h"
101
102
#ifdef ENABLE_PKCS11
103
#include "ssh-pkcs11.h"
104
#endif
105
106
extern char *__progname;
107
108
/* Flag indicating whether debug mode is on.  May be set on the command line. */
109
int debug_flag = 0;
110
111
/* Flag indicating whether a tty should be requested */
112
int tty_flag = 0;
113
114
/* don't exec a shell */
115
int no_shell_flag = 0;
116
117
/*
118
 * Flag indicating that nothing should be read from stdin.  This can be set
119
 * on the command line.
120
 */
121
int stdin_null_flag = 0;
122
123
/*
124
 * Flag indicating that the current process should be backgrounded and
125
 * a new slave launched in the foreground for ControlPersist.
126
 */
127
int need_controlpersist_detach = 0;
128
129
/* Copies of flags for ControlPersist foreground slave */
130
int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
131
132
/*
133
 * Flag indicating that ssh should fork after authentication.  This is useful
134
 * so that the passphrase can be entered manually, and then ssh goes to the
135
 * background.
136
 */
137
int fork_after_authentication_flag = 0;
138
139
/*
140
 * General data structure for command line options and options configurable
141
 * in configuration files.  See readconf.h.
142
 */
143
Options options;
144
145
/* optional user configfile */
146
char *config = NULL;
147
148
/*
149
 * Name of the host we are connecting to.  This is the name given on the
150
 * command line, or the HostName specified for the user-supplied name in a
151
 * configuration file.
152
 */
153
char *host;
154
155
/* Various strings used to to percent_expand() arguments */
156
static char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
157
static char uidstr[32], *host_arg, *conn_hash_hex;
158
159
/* socket address the host resolves to */
160
struct sockaddr_storage hostaddr;
161
162
/* Private host keys. */
163
Sensitive sensitive_data;
164
165
/* Original real UID. */
166
uid_t original_real_uid;
167
uid_t original_effective_uid;
168
169
/* command to be executed */
170
Buffer command;
171
172
/* Should we execute a command or invoke a subsystem? */
173
int subsystem_flag = 0;
174
175
/* # of replies received for global requests */
176
static int remote_forward_confirms_received = 0;
177
178
/* mux.c */
179
extern int muxserver_sock;
180
extern u_int muxclient_command;
181
182
/* Prints a help message to the user.  This function never returns. */
183
184
static void
185
usage(void)
186
{
187
	fprintf(stderr,
188
"usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
189
"           [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
190
"           [-F configfile] [-I pkcs11] [-i identity_file]\n"
191
"           [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]\n"
192
"           [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]\n"
193
"           [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]\n"
194
"           destination [command]\n"
195
	);
196
	exit(255);
197
}
198
199
static int ssh_session2(struct ssh *, struct passwd *);
200
static void load_public_identity_files(struct passwd *);
201
static void main_sigchld_handler(int);
202
203
/* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
204
static void
205
tilde_expand_paths(char **paths, u_int num_paths)
206
{
207
	u_int i;
208
	char *cp;
209
210
	for (i = 0; i < num_paths; i++) {
211
		cp = tilde_expand_filename(paths[i], original_real_uid);
212
		free(paths[i]);
213
		paths[i] = cp;
214
	}
215
}
216
217
/*
218
 * Attempt to resolve a host name / port to a set of addresses and
219
 * optionally return any CNAMEs encountered along the way.
220
 * Returns NULL on failure.
221
 * NB. this function must operate with a options having undefined members.
222
 */
223
static struct addrinfo *
224
resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
225
{
226
	char strport[NI_MAXSERV];
227
	struct addrinfo hints, *res;
228
	int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
229
230
	if (port <= 0)
231
		port = default_ssh_port();
232
233
	snprintf(strport, sizeof strport, "%d", port);
234
	memset(&hints, 0, sizeof(hints));
235
	hints.ai_family = options.address_family == -1 ?
236
	    AF_UNSPEC : options.address_family;
237
	hints.ai_socktype = SOCK_STREAM;
238
	if (cname != NULL)
239
		hints.ai_flags = AI_CANONNAME;
240
	if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
241
		if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
242
			loglevel = SYSLOG_LEVEL_ERROR;
243
		do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
244
		    __progname, name, ssh_gai_strerror(gaierr));
245
		return NULL;
246
	}
247
	if (cname != NULL && res->ai_canonname != NULL) {
248
		if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
249
			error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
250
			    __func__, name,  res->ai_canonname, (u_long)clen);
251
			if (clen > 0)
252
				*cname = '\0';
253
		}
254
	}
255
	return res;
256
}
257
258
/*
259
 * Attempt to resolve a numeric host address / port to a single address.
260
 * Returns a canonical address string.
261
 * Returns NULL on failure.
262
 * NB. this function must operate with a options having undefined members.
263
 */
264
static struct addrinfo *
265
resolve_addr(const char *name, int port, char *caddr, size_t clen)
266
{
267
	char addr[NI_MAXHOST], strport[NI_MAXSERV];
268
	struct addrinfo hints, *res;
269
	int gaierr;
270
271
	if (port <= 0)
272
		port = default_ssh_port();
273
	snprintf(strport, sizeof strport, "%u", port);
274
	memset(&hints, 0, sizeof(hints));
275
	hints.ai_family = options.address_family == -1 ?
276
	    AF_UNSPEC : options.address_family;
277
	hints.ai_socktype = SOCK_STREAM;
278
	hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
279
	if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
280
		debug2("%s: could not resolve name %.100s as address: %s",
281
		    __func__, name, ssh_gai_strerror(gaierr));
282
		return NULL;
283
	}
284
	if (res == NULL) {
285
		debug("%s: getaddrinfo %.100s returned no addresses",
286
		 __func__, name);
287
		return NULL;
288
	}
289
	if (res->ai_next != NULL) {
290
		debug("%s: getaddrinfo %.100s returned multiple addresses",
291
		    __func__, name);
292
		goto fail;
293
	}
294
	if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
295
	    addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
296
		debug("%s: Could not format address for name %.100s: %s",
297
		    __func__, name, ssh_gai_strerror(gaierr));
298
		goto fail;
299
	}
300
	if (strlcpy(caddr, addr, clen) >= clen) {
301
		error("%s: host \"%s\" addr \"%s\" too long (max %lu)",
302
		    __func__, name,  addr, (u_long)clen);
303
		if (clen > 0)
304
			*caddr = '\0';
305
 fail:
306
		freeaddrinfo(res);
307
		return NULL;
308
	}
309
	return res;
310
}
311
312
/*
313
 * Check whether the cname is a permitted replacement for the hostname
314
 * and perform the replacement if it is.
315
 * NB. this function must operate with a options having undefined members.
316
 */
317
static int
318
check_follow_cname(int direct, char **namep, const char *cname)
319
{
320
	int i;
321
	struct allowed_cname *rule;
322
323
	if (*cname == '\0' || options.num_permitted_cnames == 0 ||
324
	    strcmp(*namep, cname) == 0)
325
		return 0;
326
	if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
327
		return 0;
328
	/*
329
	 * Don't attempt to canonicalize names that will be interpreted by
330
	 * a proxy or jump host unless the user specifically requests so.
331
	 */
332
	if (!direct &&
333
	    options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
334
		return 0;
335
	debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
336
	for (i = 0; i < options.num_permitted_cnames; i++) {
337
		rule = options.permitted_cnames + i;
338
		if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
339
		    match_pattern_list(cname, rule->target_list, 1) != 1)
340
			continue;
341
		verbose("Canonicalized DNS aliased hostname "
342
		    "\"%s\" => \"%s\"", *namep, cname);
343
		free(*namep);
344
		*namep = xstrdup(cname);
345
		return 1;
346
	}
347
	return 0;
348
}
349
350
/*
351
 * Attempt to resolve the supplied hostname after applying the user's
352
 * canonicalization rules. Returns the address list for the host or NULL
353
 * if no name was found after canonicalization.
354
 * NB. this function must operate with a options having undefined members.
355
 */
356
static struct addrinfo *
357
resolve_canonicalize(char **hostp, int port)
358
{
359
	int i, direct, ndots;
360
	char *cp, *fullhost, newname[NI_MAXHOST];
361
	struct addrinfo *addrs;
362
363
	if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
364
		return NULL;
365
366
	/*
367
	 * Don't attempt to canonicalize names that will be interpreted by
368
	 * a proxy unless the user specifically requests so.
369
	 */
370
	direct = option_clear_or_none(options.proxy_command) &&
371
	    options.jump_host == NULL;
372
	if (!direct &&
373
	    options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
374
		return NULL;
375
376
	/* Try numeric hostnames first */
377
	if ((addrs = resolve_addr(*hostp, port,
378
	    newname, sizeof(newname))) != NULL) {
379
		debug2("%s: hostname %.100s is address", __func__, *hostp);
380
		if (strcasecmp(*hostp, newname) != 0) {
381
			debug2("%s: canonicalised address \"%s\" => \"%s\"",
382
			    __func__, *hostp, newname);
383
			free(*hostp);
384
			*hostp = xstrdup(newname);
385
		}
386
		return addrs;
387
	}
388
389
	/* If domain name is anchored, then resolve it now */
390
	if ((*hostp)[strlen(*hostp) - 1] == '.') {
391
		debug3("%s: name is fully qualified", __func__);
392
		fullhost = xstrdup(*hostp);
393
		if ((addrs = resolve_host(fullhost, port, 0,
394
		    newname, sizeof(newname))) != NULL)
395
			goto found;
396
		free(fullhost);
397
		goto notfound;
398
	}
399
400
	/* Don't apply canonicalization to sufficiently-qualified hostnames */
401
	ndots = 0;
402
	for (cp = *hostp; *cp != '\0'; cp++) {
403
		if (*cp == '.')
404
			ndots++;
405
	}
406
	if (ndots > options.canonicalize_max_dots) {
407
		debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
408
		    __func__, *hostp, options.canonicalize_max_dots);
409
		return NULL;
410
	}
411
	/* Attempt each supplied suffix */
412
	for (i = 0; i < options.num_canonical_domains; i++) {
413
		*newname = '\0';
414
		xasprintf(&fullhost, "%s.%s.", *hostp,
415
		    options.canonical_domains[i]);
416
		debug3("%s: attempting \"%s\" => \"%s\"", __func__,
417
		    *hostp, fullhost);
418
		if ((addrs = resolve_host(fullhost, port, 0,
419
		    newname, sizeof(newname))) == NULL) {
420
			free(fullhost);
421
			continue;
422
		}
423
 found:
424
		/* Remove trailing '.' */
425
		fullhost[strlen(fullhost) - 1] = '\0';
426
		/* Follow CNAME if requested */
427
		if (!check_follow_cname(direct, &fullhost, newname)) {
428
			debug("Canonicalized hostname \"%s\" => \"%s\"",
429
			    *hostp, fullhost);
430
		}
431
		free(*hostp);
432
		*hostp = fullhost;
433
		return addrs;
434
	}
435
 notfound:
436
	if (!options.canonicalize_fallback_local)
437
		fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
438
	debug2("%s: host %s not found in any suffix", __func__, *hostp);
439
	return NULL;
440
}
441
442
/*
443
 * Read per-user configuration file.  Ignore the system wide config
444
 * file if the user specifies a config file on the command line.
445
 */
446
static void
447
process_config_files(const char *host_name, struct passwd *pw, int post_canon)
448
{
449
	char buf[PATH_MAX];
450
	int r;
451
452
	if (config != NULL) {
453
		if (strcasecmp(config, "none") != 0 &&
454
		    !read_config_file(config, pw, host, host_name, &options,
455
		    SSHCONF_USERCONF | (post_canon ? SSHCONF_POSTCANON : 0)))
456
			fatal("Can't open user config file %.100s: "
457
			    "%.100s", config, strerror(errno));
458
	} else {
459
		r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
460
		    _PATH_SSH_USER_CONFFILE);
461
		if (r > 0 && (size_t)r < sizeof(buf))
462
			(void)read_config_file(buf, pw, host, host_name,
463
			    &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
464
			    (post_canon ? SSHCONF_POSTCANON : 0));
465
466
		/* Read systemwide configuration file after user config. */
467
		(void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
468
		    host, host_name, &options,
469
		    post_canon ? SSHCONF_POSTCANON : 0);
470
	}
471
}
472
473
/* Rewrite the port number in an addrinfo list of addresses */
474
static void
475
set_addrinfo_port(struct addrinfo *addrs, int port)
476
{
477
	struct addrinfo *addr;
478
479
	for (addr = addrs; addr != NULL; addr = addr->ai_next) {
480
		switch (addr->ai_family) {
481
		case AF_INET:
482
			((struct sockaddr_in *)addr->ai_addr)->
483
			    sin_port = htons(port);
484
			break;
485
		case AF_INET6:
486
			((struct sockaddr_in6 *)addr->ai_addr)->
487
			    sin6_port = htons(port);
488
			break;
489
		}
490
	}
491
}
492
493
/*
494
 * Main program for the ssh client.
495
 */
496
int
497
main(int ac, char **av)
498
{
499
	struct ssh *ssh = NULL;
500
	int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
501
	int config_test = 0, opt_terminated = 0;
502
	char *p, *cp, *line, *argv0, buf[PATH_MAX], *logfile;
503
	char cname[NI_MAXHOST];
504
	struct stat st;
505
	struct passwd *pw;
506
	extern int optind, optreset;
507
	extern char *optarg;
508
	struct Forward fwd;
509
	struct addrinfo *addrs = NULL;
510
	struct ssh_digest_ctx *md;
511
	u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
512
513
	ssh_malloc_init();	/* must be called before any mallocs */
514
	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
515
	sanitise_stdfd();
516
517
	/*
518
	 * Discard other fds that are hanging around. These can cause problem
519
	 * with backgrounded ssh processes started by ControlPersist.
520
	 */
521
	closefrom(STDERR_FILENO + 1);
522
523
	/*
524
	 * Save the original real uid.  It will be needed later (uid-swapping
525
	 * may clobber the real uid).
526
	 */
527
	original_real_uid = getuid();
528
	original_effective_uid = geteuid();
529
530
	/*
531
	 * Use uid-swapping to give up root privileges for the duration of
532
	 * option processing.  We will re-instantiate the rights when we are
533
	 * ready to create the privileged port, and will permanently drop
534
	 * them when the port has been created (actually, when the connection
535
	 * has been made, as we may need to create the port several times).
536
	 */
537
	PRIV_END;
538
539
	/* If we are installed setuid root be careful to not drop core. */
540
	if (original_real_uid != original_effective_uid) {
541
		struct rlimit rlim;
542
		rlim.rlim_cur = rlim.rlim_max = 0;
543
		if (setrlimit(RLIMIT_CORE, &rlim) < 0)
544
			fatal("setrlimit failed: %.100s", strerror(errno));
545
	}
546
	/* Get user data. */
547
	pw = getpwuid(original_real_uid);
548
	if (!pw) {
549
		logit("No user exists for uid %lu", (u_long)original_real_uid);
550
		exit(255);
551
	}
552
	/* Take a copy of the returned structure. */
553
	pw = pwcopy(pw);
554
555
	/*
556
	 * Set our umask to something reasonable, as some files are created
557
	 * with the default umask.  This will make them world-readable but
558
	 * writable only by the owner, which is ok for all files for which we
559
	 * don't set the modes explicitly.
560
	 */
561
	umask(022);
562
563
	setlocale(LC_CTYPE, "");
564
565
	/*
566
	 * Initialize option structure to indicate that no values have been
567
	 * set.
568
	 */
569
	initialize_options(&options);
570
571
	/*
572
	 * Prepare main ssh transport/connection structures
573
	 */
574
	if ((ssh = ssh_alloc_session_state()) == NULL)
575
		fatal("Couldn't allocate session state");
576
	channel_init_channels(ssh);
577
	active_state = ssh; /* XXX legacy API compat */
578
579
	/* Parse command-line arguments. */
580
	host = NULL;
581
	use_syslog = 0;
582
	logfile = NULL;
583
	argv0 = av[0];
584
585
 again:
586
	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
587
	    "ACD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
588
		switch (opt) {
589
		case '1':
590
			fatal("SSH protocol v.1 is no longer supported");
591
			break;
592
		case '2':
593
			/* Ignored */
594
			break;
595
		case '4':
596
			options.address_family = AF_INET;
597
			break;
598
		case '6':
599
			options.address_family = AF_INET6;
600
			break;
601
		case 'n':
602
			stdin_null_flag = 1;
603
			break;
604
		case 'f':
605
			fork_after_authentication_flag = 1;
606
			stdin_null_flag = 1;
607
			break;
608
		case 'x':
609
			options.forward_x11 = 0;
610
			break;
611
		case 'X':
612
			options.forward_x11 = 1;
613
			break;
614
		case 'y':
615
			use_syslog = 1;
616
			break;
617
		case 'E':
618
			logfile = optarg;
619
			break;
620
		case 'G':
621
			config_test = 1;
622
			break;
623
		case 'Y':
624
			options.forward_x11 = 1;
625
			options.forward_x11_trusted = 1;
626
			break;
627
		case 'g':
628
			options.fwd_opts.gateway_ports = 1;
629
			break;
630
		case 'O':
631
			if (options.stdio_forward_host != NULL)
632
				fatal("Cannot specify multiplexing "
633
				    "command with -W");
634
			else if (muxclient_command != 0)
635
				fatal("Multiplexing command already specified");
636
			if (strcmp(optarg, "check") == 0)
637
				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
638
			else if (strcmp(optarg, "forward") == 0)
639
				muxclient_command = SSHMUX_COMMAND_FORWARD;
640
			else if (strcmp(optarg, "exit") == 0)
641
				muxclient_command = SSHMUX_COMMAND_TERMINATE;
642
			else if (strcmp(optarg, "stop") == 0)
643
				muxclient_command = SSHMUX_COMMAND_STOP;
644
			else if (strcmp(optarg, "cancel") == 0)
645
				muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
646
			else if (strcmp(optarg, "proxy") == 0)
647
				muxclient_command = SSHMUX_COMMAND_PROXY;
648
			else
649
				fatal("Invalid multiplex command.");
650
			break;
651
		case 'P':	/* deprecated */
652
			options.use_privileged_port = 0;
653
			break;
654
		case 'Q':
655
			cp = NULL;
656
			if (strcmp(optarg, "cipher") == 0)
657
				cp = cipher_alg_list('\n', 0);
658
			else if (strcmp(optarg, "cipher-auth") == 0)
659
				cp = cipher_alg_list('\n', 1);
660
			else if (strcmp(optarg, "mac") == 0)
661
				cp = mac_alg_list('\n');
662
			else if (strcmp(optarg, "kex") == 0)
663
				cp = kex_alg_list('\n');
664
			else if (strcmp(optarg, "key") == 0)
665
				cp = sshkey_alg_list(0, 0, 0, '\n');
666
			else if (strcmp(optarg, "key-cert") == 0)
667
				cp = sshkey_alg_list(1, 0, 0, '\n');
668
			else if (strcmp(optarg, "key-plain") == 0)
669
				cp = sshkey_alg_list(0, 1, 0, '\n');
670
			else if (strcmp(optarg, "protocol-version") == 0) {
671
				cp = xstrdup("2");
672
			}
673
			if (cp == NULL)
674
				fatal("Unsupported query \"%s\"", optarg);
675
			printf("%s\n", cp);
676
			free(cp);
677
			exit(0);
678
			break;
679
		case 'a':
680
			options.forward_agent = 0;
681
			break;
682
		case 'A':
683
			options.forward_agent = 1;
684
			break;
685
		case 'k':
686
			options.gss_deleg_creds = 0;
687
			break;
688
		case 'K':
689
			options.gss_authentication = 1;
690
			options.gss_deleg_creds = 1;
691
			break;
692
		case 'i':
693
			p = tilde_expand_filename(optarg, original_real_uid);
694
			if (stat(p, &st) < 0)
695
				fprintf(stderr, "Warning: Identity file %s "
696
				    "not accessible: %s.\n", p,
697
				    strerror(errno));
698
			else
699
				add_identity_file(&options, NULL, p, 1);
700
			free(p);
701
			break;
702
		case 'I':
703
#ifdef ENABLE_PKCS11
704
			free(options.pkcs11_provider);
705
			options.pkcs11_provider = xstrdup(optarg);
706
#else
707
			fprintf(stderr, "no support for PKCS#11.\n");
708
#endif
709
			break;
710
		case 'J':
711
			if (options.jump_host != NULL)
712
				fatal("Only a single -J option permitted");
713
			if (options.proxy_command != NULL)
714
				fatal("Cannot specify -J with ProxyCommand");
715
			if (parse_jump(optarg, &options, 1) == -1)
716
				fatal("Invalid -J argument");
717
			options.proxy_command = xstrdup("none");
718
			break;
719
		case 't':
720
			if (options.request_tty == REQUEST_TTY_YES)
721
				options.request_tty = REQUEST_TTY_FORCE;
722
			else
723
				options.request_tty = REQUEST_TTY_YES;
724
			break;
725
		case 'v':
726
			if (debug_flag == 0) {
727
				debug_flag = 1;
728
				options.log_level = SYSLOG_LEVEL_DEBUG1;
729
			} else {
730
				if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
731
					debug_flag++;
732
					options.log_level++;
733
				}
734
			}
735
			break;
736
		case 'V':
737
			fprintf(stderr, "%s, %s\n",
738
			    SSH_VERSION,
739
#ifdef WITH_OPENSSL
740
			    SSLeay_version(SSLEAY_VERSION)
741
#else
742
			    "without OpenSSL"
743
#endif
744
			);
745
			if (opt == 'V')
746
				exit(0);
747
			break;
748
		case 'w':
749
			if (options.tun_open == -1)
750
				options.tun_open = SSH_TUNMODE_DEFAULT;
751
			options.tun_local = a2tun(optarg, &options.tun_remote);
752
			if (options.tun_local == SSH_TUNID_ERR) {
753
				fprintf(stderr,
754
				    "Bad tun device '%s'\n", optarg);
755
				exit(255);
756
			}
757
			break;
758
		case 'W':
759
			if (options.stdio_forward_host != NULL)
760
				fatal("stdio forward already specified");
761
			if (muxclient_command != 0)
762
				fatal("Cannot specify stdio forward with -O");
763
			if (parse_forward(&fwd, optarg, 1, 0)) {
764
				options.stdio_forward_host = fwd.listen_host;
765
				options.stdio_forward_port = fwd.listen_port;
766
				free(fwd.connect_host);
767
			} else {
768
				fprintf(stderr,
769
				    "Bad stdio forwarding specification '%s'\n",
770
				    optarg);
771
				exit(255);
772
			}
773
			options.request_tty = REQUEST_TTY_NO;
774
			no_shell_flag = 1;
775
			break;
776
		case 'q':
777
			options.log_level = SYSLOG_LEVEL_QUIET;
778
			break;
779
		case 'e':
780
			if (optarg[0] == '^' && optarg[2] == 0 &&
781
			    (u_char) optarg[1] >= 64 &&
782
			    (u_char) optarg[1] < 128)
783
				options.escape_char = (u_char) optarg[1] & 31;
784
			else if (strlen(optarg) == 1)
785
				options.escape_char = (u_char) optarg[0];
786
			else if (strcmp(optarg, "none") == 0)
787
				options.escape_char = SSH_ESCAPECHAR_NONE;
788
			else {
789
				fprintf(stderr, "Bad escape character '%s'.\n",
790
				    optarg);
791
				exit(255);
792
			}
793
			break;
794
		case 'c':
795
			if (!ciphers_valid(*optarg == '+' ?
796
			    optarg + 1 : optarg)) {
797
				fprintf(stderr, "Unknown cipher type '%s'\n",
798
				    optarg);
799
				exit(255);
800
			}
801
			free(options.ciphers);
802
			options.ciphers = xstrdup(optarg);
803
			break;
804
		case 'm':
805
			if (mac_valid(optarg)) {
806
				free(options.macs);
807
				options.macs = xstrdup(optarg);
808
			} else {
809
				fprintf(stderr, "Unknown mac type '%s'\n",
810
				    optarg);
811
				exit(255);
812
			}
813
			break;
814
		case 'M':
815
			if (options.control_master == SSHCTL_MASTER_YES)
816
				options.control_master = SSHCTL_MASTER_ASK;
817
			else
818
				options.control_master = SSHCTL_MASTER_YES;
819
			break;
820
		case 'p':
821
			if (options.port == -1) {
822
				options.port = a2port(optarg);
823
				if (options.port <= 0) {
824
					fprintf(stderr, "Bad port '%s'\n",
825
					    optarg);
826
					exit(255);
827
				}
828
			}
829
			break;
830
		case 'l':
831
			if (options.user == NULL)
832
				options.user = optarg;
833
			break;
834
835
		case 'L':
836
			if (parse_forward(&fwd, optarg, 0, 0))
837
				add_local_forward(&options, &fwd);
838
			else {
839
				fprintf(stderr,
840
				    "Bad local forwarding specification '%s'\n",
841
				    optarg);
842
				exit(255);
843
			}
844
			break;
845
846
		case 'R':
847
			if (parse_forward(&fwd, optarg, 0, 1) ||
848
			    parse_forward(&fwd, optarg, 1, 1)) {
849
				add_remote_forward(&options, &fwd);
850
			} else {
851
				fprintf(stderr,
852
				    "Bad remote forwarding specification "
853
				    "'%s'\n", optarg);
854
				exit(255);
855
			}
856
			break;
857
858
		case 'D':
859
			if (parse_forward(&fwd, optarg, 1, 0)) {
860
				add_local_forward(&options, &fwd);
861
			} else {
862
				fprintf(stderr,
863
				    "Bad dynamic forwarding specification "
864
				    "'%s'\n", optarg);
865
				exit(255);
866
			}
867
			break;
868
869
		case 'C':
870
			options.compression = 1;
871
			break;
872
		case 'N':
873
			no_shell_flag = 1;
874
			options.request_tty = REQUEST_TTY_NO;
875
			break;
876
		case 'T':
877
			options.request_tty = REQUEST_TTY_NO;
878
			break;
879
		case 'o':
880
			line = xstrdup(optarg);
881
			if (process_config_line(&options, pw,
882
			    host ? host : "", host ? host : "", line,
883
			    "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
884
				exit(255);
885
			free(line);
886
			break;
887
		case 's':
888
			subsystem_flag = 1;
889
			break;
890
		case 'S':
891
			free(options.control_path);
892
			options.control_path = xstrdup(optarg);
893
			break;
894
		case 'b':
895
			options.bind_address = optarg;
896
			break;
897
		case 'F':
898
			config = optarg;
899
			break;
900
		default:
901
			usage();
902
		}
903
	}
904
905
	if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
906
		opt_terminated = 1;
907
908
	ac -= optind;
909
	av += optind;
910
911
	if (ac > 0 && !host) {
912
		int tport;
913
		char *tuser;
914
		switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
915
		case -1:
916
			usage();
917
			break;
918
		case 0:
919
			if (options.user == NULL) {
920
				options.user = tuser;
921
				tuser = NULL;
922
			}
923
			free(tuser);
924
			if (options.port == -1 && tport != -1)
925
				options.port = tport;
926
			break;
927
		default:
928
			p = xstrdup(*av);
929
			cp = strrchr(p, '@');
930
			if (cp != NULL) {
931
				if (cp == p)
932
					usage();
933
				if (options.user == NULL) {
934
					options.user = p;
935
					p = NULL;
936
				}
937
				*cp++ = '\0';
938
				host = xstrdup(cp);
939
				free(p);
940
			} else
941
				host = p;
942
			break;
943
		}
944
		if (ac > 1 && !opt_terminated) {
945
			optind = optreset = 1;
946
			goto again;
947
		}
948
		ac--, av++;
949
	}
950
951
	/* Check that we got a host name. */
952
	if (!host)
953
		usage();
954
955
	host_arg = xstrdup(host);
956
957
#ifdef WITH_OPENSSL
958
	OpenSSL_add_all_algorithms();
959
	ERR_load_crypto_strings();
960
#endif
961
962
	/* Initialize the command to execute on remote host. */
963
	buffer_init(&command);
964
965
	/*
966
	 * Save the command to execute on the remote host in a buffer. There
967
	 * is no limit on the length of the command, except by the maximum
968
	 * packet size.  Also sets the tty flag if there is no command.
969
	 */
970
	if (!ac) {
971
		/* No command specified - execute shell on a tty. */
972
		if (subsystem_flag) {
973
			fprintf(stderr,
974
			    "You must specify a subsystem to invoke.\n");
975
			usage();
976
		}
977
	} else {
978
		/* A command has been specified.  Store it into the buffer. */
979
		for (i = 0; i < ac; i++) {
980
			if (i)
981
				buffer_append(&command, " ", 1);
982
			buffer_append(&command, av[i], strlen(av[i]));
983
		}
984
	}
985
986
	/*
987
	 * Initialize "log" output.  Since we are the client all output
988
	 * goes to stderr unless otherwise specified by -y or -E.
989
	 */
990
	if (use_syslog && logfile != NULL)
991
		fatal("Can't specify both -y and -E");
992
	if (logfile != NULL)
993
		log_redirect_stderr_to(logfile);
994
	log_init(argv0,
995
	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
996
	    SYSLOG_LEVEL_INFO : options.log_level,
997
	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
998
	    SYSLOG_FACILITY_USER : options.log_facility,
999
	    !use_syslog);
1000
1001
	if (debug_flag)
1002
		logit("%s, %s", SSH_VERSION,
1003
#ifdef WITH_OPENSSL
1004
		    SSLeay_version(SSLEAY_VERSION)
1005
#else
1006
		    "without OpenSSL"
1007
#endif
1008
		);
1009
1010
	/* Parse the configuration files */
1011
	process_config_files(host_arg, pw, 0);
1012
1013
	/* Hostname canonicalisation needs a few options filled. */
1014
	fill_default_options_for_canonicalization(&options);
1015
1016
	/* If the user has replaced the hostname then take it into use now */
1017
	if (options.hostname != NULL) {
1018
		/* NB. Please keep in sync with readconf.c:match_cfg_line() */
1019
		cp = percent_expand(options.hostname,
1020
		    "h", host, (char *)NULL);
1021
		free(host);
1022
		host = cp;
1023
		free(options.hostname);
1024
		options.hostname = xstrdup(host);
1025
	}
1026
1027
	/* If canonicalization requested then try to apply it */
1028
	lowercase(host);
1029
	if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
1030
		addrs = resolve_canonicalize(&host, options.port);
1031
1032
	/*
1033
	 * If CanonicalizePermittedCNAMEs have been specified but
1034
	 * other canonicalization did not happen (by not being requested
1035
	 * or by failing with fallback) then the hostname may still be changed
1036
	 * as a result of CNAME following.
1037
	 *
1038
	 * Try to resolve the bare hostname name using the system resolver's
1039
	 * usual search rules and then apply the CNAME follow rules.
1040
	 *
1041
	 * Skip the lookup if a ProxyCommand is being used unless the user
1042
	 * has specifically requested canonicalisation for this case via
1043
	 * CanonicalizeHostname=always
1044
	 */
1045
	direct = option_clear_or_none(options.proxy_command) &&
1046
	    options.jump_host == NULL;
1047
	if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
1048
	    options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1049
		if ((addrs = resolve_host(host, options.port,
1050
		    option_clear_or_none(options.proxy_command),
1051
		    cname, sizeof(cname))) == NULL) {
1052
			/* Don't fatal proxied host names not in the DNS */
1053
			if (option_clear_or_none(options.proxy_command))
1054
				cleanup_exit(255); /* logged in resolve_host */
1055
		} else
1056
			check_follow_cname(direct, &host, cname);
1057
	}
1058
1059
	/*
1060
	 * If canonicalisation is enabled then re-parse the configuration
1061
	 * files as new stanzas may match.
1062
	 */
1063
	if (options.canonicalize_hostname != 0) {
1064
		debug("Re-reading configuration after hostname "
1065
		    "canonicalisation");
1066
		free(options.hostname);
1067
		options.hostname = xstrdup(host);
1068
		process_config_files(host_arg, pw, 1);
1069
		/*
1070
		 * Address resolution happens early with canonicalisation
1071
		 * enabled and the port number may have changed since, so
1072
		 * reset it in address list
1073
		 */
1074
		if (addrs != NULL && options.port > 0)
1075
			set_addrinfo_port(addrs, options.port);
1076
	}
1077
1078
	/* Fill configuration defaults. */
1079
	fill_default_options(&options);
1080
1081
	/*
1082
	 * If ProxyJump option specified, then construct a ProxyCommand now.
1083
	 */
1084
	if (options.jump_host != NULL) {
1085
		char port_s[8];
1086
1087
		/* Consistency check */
1088
		if (options.proxy_command != NULL)
1089
			fatal("inconsistent options: ProxyCommand+ProxyJump");
1090
		/* Never use FD passing for ProxyJump */
1091
		options.proxy_use_fdpass = 0;
1092
		snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1093
		xasprintf(&options.proxy_command,
1094
		    "ssh%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1095
		    /* Optional "-l user" argument if jump_user set */
1096
		    options.jump_user == NULL ? "" : " -l ",
1097
		    options.jump_user == NULL ? "" : options.jump_user,
1098
		    /* Optional "-p port" argument if jump_port set */
1099
		    options.jump_port <= 0 ? "" : " -p ",
1100
		    options.jump_port <= 0 ? "" : port_s,
1101
		    /* Optional additional jump hosts ",..." */
1102
		    options.jump_extra == NULL ? "" : " -J ",
1103
		    options.jump_extra == NULL ? "" : options.jump_extra,
1104
		    /* Optional "-F" argumment if -F specified */
1105
		    config == NULL ? "" : " -F ",
1106
		    config == NULL ? "" : config,
1107
		    /* Optional "-v" arguments if -v set */
1108
		    debug_flag ? " -" : "",
1109
		    debug_flag, "vvv",
1110
		    /* Mandatory hostname */
1111
		    options.jump_host);
1112
		debug("Setting implicit ProxyCommand from ProxyJump: %s",
1113
		    options.proxy_command);
1114
	}
1115
1116
	if (options.port == 0)
1117
		options.port = default_ssh_port();
1118
	channel_set_af(ssh, options.address_family);
1119
1120
	/* Tidy and check options */
1121
	if (options.host_key_alias != NULL)
1122
		lowercase(options.host_key_alias);
1123
	if (options.proxy_command != NULL &&
1124
	    strcmp(options.proxy_command, "-") == 0 &&
1125
	    options.proxy_use_fdpass)
1126
		fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1127
	if (options.control_persist &&
1128
	    options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1129
		debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
1130
		    "disabling");
1131
		options.update_hostkeys = 0;
1132
	}
1133
	if (options.connection_attempts <= 0)
1134
		fatal("Invalid number of ConnectionAttempts");
1135
1136
	if (original_effective_uid != 0)
1137
		options.use_privileged_port = 0;
1138
1139
	if (buffer_len(&command) != 0 && options.remote_command != NULL)
1140
		fatal("Cannot execute command-line and remote command.");
1141
1142
	/* Cannot fork to background if no command. */
1143
	if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
1144
	    options.remote_command == NULL && !no_shell_flag)
1145
		fatal("Cannot fork into background without a command "
1146
		    "to execute.");
1147
1148
	/* reinit */
1149
	log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1150
1151
	if (options.request_tty == REQUEST_TTY_YES ||
1152
	    options.request_tty == REQUEST_TTY_FORCE)
1153
		tty_flag = 1;
1154
1155
	/* Allocate a tty by default if no command specified. */
1156
	if (buffer_len(&command) == 0 && options.remote_command == NULL)
1157
		tty_flag = options.request_tty != REQUEST_TTY_NO;
1158
1159
	/* Force no tty */
1160
	if (options.request_tty == REQUEST_TTY_NO ||
1161
	    (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY))
1162
		tty_flag = 0;
1163
	/* Do not allocate a tty if stdin is not a tty. */
1164
	if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1165
	    options.request_tty != REQUEST_TTY_FORCE) {
1166
		if (tty_flag)
1167
			logit("Pseudo-terminal will not be allocated because "
1168
			    "stdin is not a terminal.");
1169
		tty_flag = 0;
1170
	}
1171
1172
	if (options.user == NULL)
1173
		options.user = xstrdup(pw->pw_name);
1174
1175
	/* Set up strings used to percent_expand() arguments */
1176
	if (gethostname(thishost, sizeof(thishost)) == -1)
1177
		fatal("gethostname: %s", strerror(errno));
1178
	strlcpy(shorthost, thishost, sizeof(shorthost));
1179
	shorthost[strcspn(thishost, ".")] = '\0';
1180
	snprintf(portstr, sizeof(portstr), "%d", options.port);
1181
	snprintf(uidstr, sizeof(uidstr), "%d", pw->pw_uid);
1182
1183
	if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
1184
	    ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
1185
	    ssh_digest_update(md, host, strlen(host)) < 0 ||
1186
	    ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
1187
	    ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
1188
	    ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
1189
		fatal("%s: mux digest failed", __func__);
1190
	ssh_digest_free(md);
1191
	conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
1192
1193
	/*
1194
	 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1195
	 * after port-forwarding is set up, so it may pick up any local
1196
	 * tunnel interface name allocated.
1197
	 */
1198
	if (options.remote_command != NULL) {
1199
		debug3("expanding RemoteCommand: %s", options.remote_command);
1200
		cp = options.remote_command;
1201
		options.remote_command = percent_expand(cp,
1202
		    "C", conn_hash_hex,
1203
		    "L", shorthost,
1204
		    "d", pw->pw_dir,
1205
		    "h", host,
1206
		    "l", thishost,
1207
		    "n", host_arg,
1208
		    "p", portstr,
1209
		    "r", options.user,
1210
		    "u", pw->pw_name,
1211
		    (char *)NULL);
1212
		debug3("expanded RemoteCommand: %s", options.remote_command);
1213
		free(cp);
1214
		buffer_append(&command, options.remote_command,
1215
		    strlen(options.remote_command));
1216
	}
1217
1218
	if (options.control_path != NULL) {
1219
		cp = tilde_expand_filename(options.control_path,
1220
		    original_real_uid);
1221
		free(options.control_path);
1222
		options.control_path = percent_expand(cp,
1223
		    "C", conn_hash_hex,
1224
		    "L", shorthost,
1225
		    "h", host,
1226
		    "l", thishost,
1227
		    "n", host_arg,
1228
		    "p", portstr,
1229
		    "r", options.user,
1230
		    "u", pw->pw_name,
1231
		    "i", uidstr,
1232
		    (char *)NULL);
1233
		free(cp);
1234
	}
1235
	free(conn_hash_hex);
1236
1237
	if (config_test) {
1238
		dump_client_config(&options, host);
1239
		exit(0);
1240
	}
1241
1242
	if (muxclient_command != 0 && options.control_path == NULL)
1243
		fatal("No ControlPath specified for \"-O\" command");
1244
	if (options.control_path != NULL) {
1245
		int sock;
1246
		if ((sock = muxclient(options.control_path)) >= 0) {
1247
			ssh_packet_set_connection(ssh, sock, sock);
1248
			packet_set_mux();
1249
			goto skip_connect;
1250
		}
1251
	}
1252
1253
	/*
1254
	 * If hostname canonicalisation was not enabled, then we may not
1255
	 * have yet resolved the hostname. Do so now.
1256
	 */
1257
	if (addrs == NULL && options.proxy_command == NULL) {
1258
		debug2("resolving \"%s\" port %d", host, options.port);
1259
		if ((addrs = resolve_host(host, options.port, 1,
1260
		    cname, sizeof(cname))) == NULL)
1261
			cleanup_exit(255); /* resolve_host logs the error */
1262
	}
1263
1264
	timeout_ms = options.connection_timeout * 1000;
1265
1266
	/* Open a connection to the remote host. */
1267
	if (ssh_connect(ssh, host, addrs, &hostaddr, options.port,
1268
	    options.address_family, options.connection_attempts,
1269
	    &timeout_ms, options.tcp_keep_alive,
1270
	    options.use_privileged_port) != 0)
1271
		exit(255);
1272
1273
	if (addrs != NULL)
1274
		freeaddrinfo(addrs);
1275
1276
	packet_set_timeout(options.server_alive_interval,
1277
	    options.server_alive_count_max);
1278
1279
	ssh = active_state; /* XXX */
1280
1281
	if (timeout_ms > 0)
1282
		debug3("timeout: %d ms remain after connect", timeout_ms);
1283
1284
	/*
1285
	 * If we successfully made the connection, load the host private key
1286
	 * in case we will need it later for combined rsa-rhosts
1287
	 * authentication. This must be done before releasing extra
1288
	 * privileges, because the file is only readable by root.
1289
	 * If we cannot access the private keys, load the public keys
1290
	 * instead and try to execute the ssh-keysign helper instead.
1291
	 */
1292
	sensitive_data.nkeys = 0;
1293
	sensitive_data.keys = NULL;
1294
	sensitive_data.external_keysign = 0;
1295
	if (options.hostbased_authentication) {
1296
		sensitive_data.nkeys = 9;
1297
		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1298
		    sizeof(struct sshkey));	/* XXX */
1299
1300
		PRIV_START;
1301
		sensitive_data.keys[1] = key_load_private_cert(KEY_ECDSA,
1302
		    _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1303
		sensitive_data.keys[2] = key_load_private_cert(KEY_ED25519,
1304
		    _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1305
		sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1306
		    _PATH_HOST_RSA_KEY_FILE, "", NULL);
1307
		sensitive_data.keys[4] = key_load_private_cert(KEY_DSA,
1308
		    _PATH_HOST_DSA_KEY_FILE, "", NULL);
1309
		sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
1310
		    _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1311
		sensitive_data.keys[6] = key_load_private_type(KEY_ED25519,
1312
		    _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1313
		sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1314
		    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1315
		sensitive_data.keys[8] = key_load_private_type(KEY_DSA,
1316
		    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1317
		PRIV_END;
1318
1319
		if (options.hostbased_authentication == 1 &&
1320
		    sensitive_data.keys[0] == NULL &&
1321
		    sensitive_data.keys[5] == NULL &&
1322
		    sensitive_data.keys[6] == NULL &&
1323
		    sensitive_data.keys[7] == NULL &&
1324
		    sensitive_data.keys[8] == NULL) {
1325
			sensitive_data.keys[1] = key_load_cert(
1326
			    _PATH_HOST_ECDSA_KEY_FILE);
1327
			sensitive_data.keys[2] = key_load_cert(
1328
			    _PATH_HOST_ED25519_KEY_FILE);
1329
			sensitive_data.keys[3] = key_load_cert(
1330
			    _PATH_HOST_RSA_KEY_FILE);
1331
			sensitive_data.keys[4] = key_load_cert(
1332
			    _PATH_HOST_DSA_KEY_FILE);
1333
			sensitive_data.keys[5] = key_load_public(
1334
			    _PATH_HOST_ECDSA_KEY_FILE, NULL);
1335
			sensitive_data.keys[6] = key_load_public(
1336
			    _PATH_HOST_ED25519_KEY_FILE, NULL);
1337
			sensitive_data.keys[7] = key_load_public(
1338
			    _PATH_HOST_RSA_KEY_FILE, NULL);
1339
			sensitive_data.keys[8] = key_load_public(
1340
			    _PATH_HOST_DSA_KEY_FILE, NULL);
1341
			sensitive_data.external_keysign = 1;
1342
		}
1343
	}
1344
	/*
1345
	 * Get rid of any extra privileges that we may have.  We will no
1346
	 * longer need them.  Also, extra privileges could make it very hard
1347
	 * to read identity files and other non-world-readable files from the
1348
	 * user's home directory if it happens to be on a NFS volume where
1349
	 * root is mapped to nobody.
1350
	 */
1351
	if (original_effective_uid == 0) {
1352
		PRIV_START;
1353
		permanently_set_uid(pw);
1354
	}
1355
1356
	/*
1357
	 * Now that we are back to our own permissions, create ~/.ssh
1358
	 * directory if it doesn't already exist.
1359
	 */
1360
	if (config == NULL) {
1361
		r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1362
		    strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1363
		if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
1364
			if (mkdir(buf, 0700) < 0)
1365
				error("Could not create directory '%.200s'.",
1366
				    buf);
1367
	}
1368
1369
	/* load options.identity_files */
1370
	load_public_identity_files(pw);
1371
1372
	/* optionally set the SSH_AUTHSOCKET_ENV_NAME varibale */
1373
	if (options.identity_agent &&
1374
	    strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1375
		if (strcmp(options.identity_agent, "none") == 0) {
1376
			unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1377
		} else {
1378
			p = tilde_expand_filename(options.identity_agent,
1379
			    original_real_uid);
1380
			cp = percent_expand(p, "d", pw->pw_dir,
1381
			    "u", pw->pw_name, "l", thishost, "h", host,
1382
			    "r", options.user, (char *)NULL);
1383
			setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1384
			free(cp);
1385
			free(p);
1386
		}
1387
	}
1388
1389
	/* Expand ~ in known host file names. */
1390
	tilde_expand_paths(options.system_hostfiles,
1391
	    options.num_system_hostfiles);
1392
	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1393
1394
	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1395
	signal(SIGCHLD, main_sigchld_handler);
1396
1397
	/* Log into the remote system.  Never returns if the login fails. */
1398
	ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1399
	    options.port, pw, timeout_ms);
1400
1401
	if (packet_connection_is_on_socket()) {
1402
		verbose("Authenticated to %s ([%s]:%d).", host,
1403
		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1404
	} else {
1405
		verbose("Authenticated to %s (via proxy).", host);
1406
	}
1407
1408
	/* We no longer need the private host keys.  Clear them now. */
1409
	if (sensitive_data.nkeys != 0) {
1410
		for (i = 0; i < sensitive_data.nkeys; i++) {
1411
			if (sensitive_data.keys[i] != NULL) {
1412
				/* Destroys contents safely */
1413
				debug3("clear hostkey %d", i);
1414
				key_free(sensitive_data.keys[i]);
1415
				sensitive_data.keys[i] = NULL;
1416
			}
1417
		}
1418
		free(sensitive_data.keys);
1419
	}
1420
	for (i = 0; i < options.num_identity_files; i++) {
1421
		free(options.identity_files[i]);
1422
		options.identity_files[i] = NULL;
1423
		if (options.identity_keys[i]) {
1424
			key_free(options.identity_keys[i]);
1425
			options.identity_keys[i] = NULL;
1426
		}
1427
	}
1428
	for (i = 0; i < options.num_certificate_files; i++) {
1429
		free(options.certificate_files[i]);
1430
		options.certificate_files[i] = NULL;
1431
	}
1432
1433
 skip_connect:
1434
	exit_status = ssh_session2(ssh, pw);
1435
	packet_close();
1436
1437
	if (options.control_path != NULL && muxserver_sock != -1)
1438
		unlink(options.control_path);
1439
1440
	/* Kill ProxyCommand if it is running. */
1441
	ssh_kill_proxy_command();
1442
1443
	return exit_status;
1444
}
1445
1446
static void
1447
control_persist_detach(void)
1448
{
1449
	pid_t pid;
1450
	int devnull, keep_stderr;
1451
1452
	debug("%s: backgrounding master process", __func__);
1453
1454
 	/*
1455
 	 * master (current process) into the background, and make the
1456
 	 * foreground process a client of the backgrounded master.
1457
 	 */
1458
	switch ((pid = fork())) {
1459
	case -1:
1460
		fatal("%s: fork: %s", __func__, strerror(errno));
1461
	case 0:
1462
		/* Child: master process continues mainloop */
1463
 		break;
1464
 	default:
1465
		/* Parent: set up mux slave to connect to backgrounded master */
1466
		debug2("%s: background process is %ld", __func__, (long)pid);
1467
		stdin_null_flag = ostdin_null_flag;
1468
		options.request_tty = orequest_tty;
1469
		tty_flag = otty_flag;
1470
 		close(muxserver_sock);
1471
 		muxserver_sock = -1;
1472
		options.control_master = SSHCTL_MASTER_NO;
1473
 		muxclient(options.control_path);
1474
		/* muxclient() doesn't return on success. */
1475
 		fatal("Failed to connect to new control master");
1476
 	}
1477
	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1478
		error("%s: open(\"/dev/null\"): %s", __func__,
1479
		    strerror(errno));
1480
	} else {
1481
		keep_stderr = log_is_on_stderr() && debug_flag;
1482
		if (dup2(devnull, STDIN_FILENO) == -1 ||
1483
		    dup2(devnull, STDOUT_FILENO) == -1 ||
1484
		    (!keep_stderr && dup2(devnull, STDERR_FILENO) == -1))
1485
			error("%s: dup2: %s", __func__, strerror(errno));
1486
		if (devnull > STDERR_FILENO)
1487
			close(devnull);
1488
	}
1489
	daemon(1, 1);
1490
	setproctitle("%s [mux]", options.control_path);
1491
}
1492
1493
/* Do fork() after authentication. Used by "ssh -f" */
1494
static void
1495
fork_postauth(void)
1496
{
1497
	if (need_controlpersist_detach)
1498
		control_persist_detach();
1499
	debug("forking to background");
1500
	fork_after_authentication_flag = 0;
1501
	if (daemon(1, 1) < 0)
1502
		fatal("daemon() failed: %.200s", strerror(errno));
1503
}
1504
1505
/* Callback for remote forward global requests */
1506
static void
1507
ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1508
{
1509
	struct Forward *rfwd = (struct Forward *)ctxt;
1510
1511
	/* XXX verbose() on failure? */
1512
	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1513
	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1514
	    rfwd->listen_path ? rfwd->listen_path :
1515
	    rfwd->listen_host ? rfwd->listen_host : "",
1516
	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1517
	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1518
	    rfwd->connect_host, rfwd->connect_port);
1519
	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1520
		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1521
			rfwd->allocated_port = packet_get_int();
1522
			logit("Allocated port %u for remote forward to %s:%d",
1523
			    rfwd->allocated_port,
1524
			    rfwd->connect_host, rfwd->connect_port);
1525
			channel_update_permitted_opens(ssh,
1526
			    rfwd->handle, rfwd->allocated_port);
1527
		} else {
1528
			channel_update_permitted_opens(ssh, rfwd->handle, -1);
1529
		}
1530
	}
1531
1532
	if (type == SSH2_MSG_REQUEST_FAILURE) {
1533
		if (options.exit_on_forward_failure) {
1534
			if (rfwd->listen_path != NULL)
1535
				fatal("Error: remote port forwarding failed "
1536
				    "for listen path %s", rfwd->listen_path);
1537
			else
1538
				fatal("Error: remote port forwarding failed "
1539
				    "for listen port %d", rfwd->listen_port);
1540
		} else {
1541
			if (rfwd->listen_path != NULL)
1542
				logit("Warning: remote port forwarding failed "
1543
				    "for listen path %s", rfwd->listen_path);
1544
			else
1545
				logit("Warning: remote port forwarding failed "
1546
				    "for listen port %d", rfwd->listen_port);
1547
		}
1548
	}
1549
	if (++remote_forward_confirms_received == options.num_remote_forwards) {
1550
		debug("All remote forwarding requests processed");
1551
		if (fork_after_authentication_flag)
1552
			fork_postauth();
1553
	}
1554
}
1555
1556
static void
1557
client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1558
{
1559
	debug("stdio forwarding: done");
1560
	cleanup_exit(0);
1561
}
1562
1563
static void
1564
ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1565
{
1566
	if (!success)
1567
		fatal("stdio forwarding failed");
1568
}
1569
1570
static void
1571
ssh_init_stdio_forwarding(struct ssh *ssh)
1572
{
1573
	Channel *c;
1574
	int in, out;
1575
1576
	if (options.stdio_forward_host == NULL)
1577
		return;
1578
1579
	debug3("%s: %s:%d", __func__, options.stdio_forward_host,
1580
	    options.stdio_forward_port);
1581
1582
	if ((in = dup(STDIN_FILENO)) < 0 ||
1583
	    (out = dup(STDOUT_FILENO)) < 0)
1584
		fatal("channel_connect_stdio_fwd: dup() in/out failed");
1585
	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1586
	    options.stdio_forward_port, in, out)) == NULL)
1587
		fatal("%s: channel_connect_stdio_fwd failed", __func__);
1588
	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1589
	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1590
}
1591
1592
static void
1593
ssh_init_forwarding(struct ssh *ssh, char **ifname)
1594
{
1595
	int success = 0;
1596
	int i;
1597
1598
	/* Initiate local TCP/IP port forwardings. */
1599
	for (i = 0; i < options.num_local_forwards; i++) {
1600
		debug("Local connections to %.200s:%d forwarded to remote "
1601
		    "address %.200s:%d",
1602
		    (options.local_forwards[i].listen_path != NULL) ?
1603
		    options.local_forwards[i].listen_path :
1604
		    (options.local_forwards[i].listen_host == NULL) ?
1605
		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1606
		    options.local_forwards[i].listen_host,
1607
		    options.local_forwards[i].listen_port,
1608
		    (options.local_forwards[i].connect_path != NULL) ?
1609
		    options.local_forwards[i].connect_path :
1610
		    options.local_forwards[i].connect_host,
1611
		    options.local_forwards[i].connect_port);
1612
		success += channel_setup_local_fwd_listener(ssh,
1613
		    &options.local_forwards[i], &options.fwd_opts);
1614
	}
1615
	if (i > 0 && success != i && options.exit_on_forward_failure)
1616
		fatal("Could not request local forwarding.");
1617
	if (i > 0 && success == 0)
1618
		error("Could not request local forwarding.");
1619
1620
	/* Initiate remote TCP/IP port forwardings. */
1621
	for (i = 0; i < options.num_remote_forwards; i++) {
1622
		debug("Remote connections from %.200s:%d forwarded to "
1623
		    "local address %.200s:%d",
1624
		    (options.remote_forwards[i].listen_path != NULL) ?
1625
		    options.remote_forwards[i].listen_path :
1626
		    (options.remote_forwards[i].listen_host == NULL) ?
1627
		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1628
		    options.remote_forwards[i].listen_port,
1629
		    (options.remote_forwards[i].connect_path != NULL) ?
1630
		    options.remote_forwards[i].connect_path :
1631
		    options.remote_forwards[i].connect_host,
1632
		    options.remote_forwards[i].connect_port);
1633
		options.remote_forwards[i].handle =
1634
		    channel_request_remote_forwarding(ssh,
1635
		    &options.remote_forwards[i]);
1636
		if (options.remote_forwards[i].handle < 0) {
1637
			if (options.exit_on_forward_failure)
1638
				fatal("Could not request remote forwarding.");
1639
			else
1640
				logit("Warning: Could not request remote "
1641
				    "forwarding.");
1642
		} else {
1643
			client_register_global_confirm(
1644
			    ssh_confirm_remote_forward,
1645
			    &options.remote_forwards[i]);
1646
		}
1647
	}
1648
1649
	/* Initiate tunnel forwarding. */
1650
	if (options.tun_open != SSH_TUNMODE_NO) {
1651
		if ((*ifname = client_request_tun_fwd(ssh,
1652
		    options.tun_open, options.tun_local,
1653
		    options.tun_remote)) == NULL) {
1654
			if (options.exit_on_forward_failure)
1655
				fatal("Could not request tunnel forwarding.");
1656
			else
1657
				error("Could not request tunnel forwarding.");
1658
		}
1659
	}
1660
}
1661
1662
static void
1663
check_agent_present(void)
1664
{
1665
	int r;
1666
1667
	if (options.forward_agent) {
1668
		/* Clear agent forwarding if we don't have an agent. */
1669
		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1670
			options.forward_agent = 0;
1671
			if (r != SSH_ERR_AGENT_NOT_PRESENT)
1672
				debug("ssh_get_authentication_socket: %s",
1673
				    ssh_err(r));
1674
		}
1675
	}
1676
}
1677
1678
static void
1679
ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
1680
{
1681
	extern char **environ;
1682
	const char *display;
1683
	int interactive = tty_flag;
1684
	char *proto = NULL, *data = NULL;
1685
1686
	if (!success)
1687
		return; /* No need for error message, channels code sens one */
1688
1689
	display = getenv("DISPLAY");
1690
	if (display == NULL && options.forward_x11)
1691
		debug("X11 forwarding requested but DISPLAY not set");
1692
	if (options.forward_x11 && client_x11_get_proto(ssh, display,
1693
	    options.xauth_location, options.forward_x11_trusted,
1694
	    options.forward_x11_timeout, &proto, &data) == 0) {
1695
		/* Request forwarding with authentication spoofing. */
1696
		debug("Requesting X11 forwarding with authentication "
1697
		    "spoofing.");
1698
		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
1699
		    data, 1);
1700
		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
1701
		/* XXX exit_on_forward_failure */
1702
		interactive = 1;
1703
	}
1704
1705
	check_agent_present();
1706
	if (options.forward_agent) {
1707
		debug("Requesting authentication agent forwarding.");
1708
		channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1709
		packet_send();
1710
	}
1711
1712
	/* Tell the packet module whether this is an interactive session. */
1713
	packet_set_interactive(interactive,
1714
	    options.ip_qos_interactive, options.ip_qos_bulk);
1715
1716
	client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
1717
	    NULL, fileno(stdin), &command, environ);
1718
}
1719
1720
/* open new channel for a session */
1721
static int
1722
ssh_session2_open(struct ssh *ssh)
1723
{
1724
	Channel *c;
1725
	int window, packetmax, in, out, err;
1726
1727
	if (stdin_null_flag) {
1728
		in = open(_PATH_DEVNULL, O_RDONLY);
1729
	} else {
1730
		in = dup(STDIN_FILENO);
1731
	}
1732
	out = dup(STDOUT_FILENO);
1733
	err = dup(STDERR_FILENO);
1734
1735
	if (in < 0 || out < 0 || err < 0)
1736
		fatal("dup() in/out/err failed");
1737
1738
	/* enable nonblocking unless tty */
1739
	if (!isatty(in))
1740
		set_nonblock(in);
1741
	if (!isatty(out))
1742
		set_nonblock(out);
1743
	if (!isatty(err))
1744
		set_nonblock(err);
1745
1746
	window = CHAN_SES_WINDOW_DEFAULT;
1747
	packetmax = CHAN_SES_PACKET_DEFAULT;
1748
	if (tty_flag) {
1749
		window >>= 1;
1750
		packetmax >>= 1;
1751
	}
1752
	c = channel_new(ssh,
1753
	    "session", SSH_CHANNEL_OPENING, in, out, err,
1754
	    window, packetmax, CHAN_EXTENDED_WRITE,
1755
	    "client-session", /*nonblock*/0);
1756
1757
	debug3("%s: channel_new: %d", __func__, c->self);
1758
1759
	channel_send_open(ssh, c->self);
1760
	if (!no_shell_flag)
1761
		channel_register_open_confirm(ssh, c->self,
1762
		    ssh_session2_setup, NULL);
1763
1764
	return c->self;
1765
}
1766
1767
static int
1768
ssh_session2(struct ssh *ssh, struct passwd *pw)
1769
{
1770
	int devnull, id = -1;
1771
	char *cp, *tun_fwd_ifname = NULL;
1772
1773
	/* XXX should be pre-session */
1774
	if (!options.control_persist)
1775
		ssh_init_stdio_forwarding(ssh);
1776
1777
	ssh_init_forwarding(ssh, &tun_fwd_ifname);
1778
1779
	if (options.local_command != NULL) {
1780
		debug3("expanding LocalCommand: %s", options.local_command);
1781
		cp = options.local_command;
1782
		options.local_command = percent_expand(cp,
1783
		    "C", conn_hash_hex,
1784
		    "L", shorthost,
1785
		    "d", pw->pw_dir,
1786
		    "h", host,
1787
		    "l", thishost,
1788
		    "n", host_arg,
1789
		    "p", portstr,
1790
		    "r", options.user,
1791
		    "u", pw->pw_name,
1792
		    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
1793
		    (char *)NULL);
1794
		debug3("expanded LocalCommand: %s", options.local_command);
1795
		free(cp);
1796
	}
1797
1798
	/* Start listening for multiplex clients */
1799
	if (!packet_get_mux())
1800
		muxserver_listen(ssh);
1801
1802
 	/*
1803
	 * If we are in control persist mode and have a working mux listen
1804
	 * socket, then prepare to background ourselves and have a foreground
1805
	 * client attach as a control slave.
1806
	 * NB. we must save copies of the flags that we override for
1807
	 * the backgrounding, since we defer attachment of the slave until
1808
	 * after the connection is fully established (in particular,
1809
	 * async rfwd replies have been received for ExitOnForwardFailure).
1810
	 */
1811
 	if (options.control_persist && muxserver_sock != -1) {
1812
		ostdin_null_flag = stdin_null_flag;
1813
		ono_shell_flag = no_shell_flag;
1814
		orequest_tty = options.request_tty;
1815
		otty_flag = tty_flag;
1816
 		stdin_null_flag = 1;
1817
 		no_shell_flag = 1;
1818
 		tty_flag = 0;
1819
		if (!fork_after_authentication_flag)
1820
			need_controlpersist_detach = 1;
1821
		fork_after_authentication_flag = 1;
1822
 	}
1823
	/*
1824
	 * ControlPersist mux listen socket setup failed, attempt the
1825
	 * stdio forward setup that we skipped earlier.
1826
	 */
1827
	if (options.control_persist && muxserver_sock == -1)
1828
		ssh_init_stdio_forwarding(ssh);
1829
1830
	if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1831
		id = ssh_session2_open(ssh);
1832
	else {
1833
		packet_set_interactive(
1834
		    options.control_master == SSHCTL_MASTER_NO,
1835
		    options.ip_qos_interactive, options.ip_qos_bulk);
1836
	}
1837
1838
	/* If we don't expect to open a new session, then disallow it */
1839
	if (options.control_master == SSHCTL_MASTER_NO &&
1840
	    (datafellows & SSH_NEW_OPENSSH)) {
1841
		debug("Requesting no-more-sessions@openssh.com");
1842
		packet_start(SSH2_MSG_GLOBAL_REQUEST);
1843
		packet_put_cstring("no-more-sessions@openssh.com");
1844
		packet_put_char(0);
1845
		packet_send();
1846
	}
1847
1848
	/* Execute a local command */
1849
	if (options.local_command != NULL &&
1850
	    options.permit_local_command)
1851
		ssh_local_cmd(options.local_command);
1852
1853
	/*
1854
	 * stdout is now owned by the session channel; clobber it here
1855
	 * so future channel closes are propagated to the local fd.
1856
	 * NB. this can only happen after LocalCommand has completed,
1857
	 * as it may want to write to stdout.
1858
	 */
1859
	if (!need_controlpersist_detach) {
1860
		if ((devnull = open(_PATH_DEVNULL, O_WRONLY)) == -1)
1861
			error("%s: open %s: %s", __func__,
1862
			    _PATH_DEVNULL, strerror(errno));
1863
		if (dup2(devnull, STDOUT_FILENO) < 0)
1864
			fatal("%s: dup2() stdout failed", __func__);
1865
		if (devnull > STDERR_FILENO)
1866
			close(devnull);
1867
	}
1868
1869
	/*
1870
	 * If requested and we are not interested in replies to remote
1871
	 * forwarding requests, then let ssh continue in the background.
1872
	 */
1873
	if (fork_after_authentication_flag) {
1874
		if (options.exit_on_forward_failure &&
1875
		    options.num_remote_forwards > 0) {
1876
			debug("deferring postauth fork until remote forward "
1877
			    "confirmation received");
1878
		} else
1879
			fork_postauth();
1880
	}
1881
1882
	return client_loop(ssh, tty_flag, tty_flag ?
1883
	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
1884
}
1885
1886
/* Loads all IdentityFile and CertificateFile keys */
1887
static void
1888
load_public_identity_files(struct passwd *pw)
1889
{
1890
	char *filename, *cp;
1891
	struct sshkey *public;
1892
	int i;
1893
	u_int n_ids, n_certs;
1894
	char *identity_files[SSH_MAX_IDENTITY_FILES];
1895
	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
1896
	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
1897
	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
1898
#ifdef ENABLE_PKCS11
1899
	struct sshkey **keys;
1900
	int nkeys;
1901
#endif /* PKCS11 */
1902
1903
	n_ids = n_certs = 0;
1904
	memset(identity_files, 0, sizeof(identity_files));
1905
	memset(identity_keys, 0, sizeof(identity_keys));
1906
	memset(certificate_files, 0, sizeof(certificate_files));
1907
	memset(certificates, 0, sizeof(certificates));
1908
1909
#ifdef ENABLE_PKCS11
1910
	if (options.pkcs11_provider != NULL &&
1911
	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1912
	    (pkcs11_init(!options.batch_mode) == 0) &&
1913
	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1914
	    &keys)) > 0) {
1915
		for (i = 0; i < nkeys; i++) {
1916
			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1917
				key_free(keys[i]);
1918
				continue;
1919
			}
1920
			identity_keys[n_ids] = keys[i];
1921
			identity_files[n_ids] =
1922
			    xstrdup(options.pkcs11_provider); /* XXX */
1923
			n_ids++;
1924
		}
1925
		free(keys);
1926
	}
1927
#endif /* ENABLE_PKCS11 */
1928
	if ((pw = getpwuid(original_real_uid)) == NULL)
1929
		fatal("load_public_identity_files: getpwuid failed");
1930
	for (i = 0; i < options.num_identity_files; i++) {
1931
		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
1932
		    strcasecmp(options.identity_files[i], "none") == 0) {
1933
			free(options.identity_files[i]);
1934
			options.identity_files[i] = NULL;
1935
			continue;
1936
		}
1937
		cp = tilde_expand_filename(options.identity_files[i],
1938
		    original_real_uid);
1939
		filename = percent_expand(cp, "d", pw->pw_dir,
1940
		    "u", pw->pw_name, "l", thishost, "h", host,
1941
		    "r", options.user, (char *)NULL);
1942
		free(cp);
1943
		public = key_load_public(filename, NULL);
1944
		debug("identity file %s type %d", filename,
1945
		    public ? public->type : -1);
1946
		free(options.identity_files[i]);
1947
		identity_files[n_ids] = filename;
1948
		identity_keys[n_ids] = public;
1949
1950
		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1951
			continue;
1952
1953
		/*
1954
		 * If no certificates have been explicitly listed then try
1955
		 * to add the default certificate variant too.
1956
		 */
1957
		if (options.num_certificate_files != 0)
1958
			continue;
1959
		xasprintf(&cp, "%s-cert", filename);
1960
		public = key_load_public(cp, NULL);
1961
		debug("identity file %s type %d", cp,
1962
		    public ? public->type : -1);
1963
		if (public == NULL) {
1964
			free(cp);
1965
			continue;
1966
		}
1967
		if (!key_is_cert(public)) {
1968
			debug("%s: key %s type %s is not a certificate",
1969
			    __func__, cp, key_type(public));
1970
			key_free(public);
1971
			free(cp);
1972
			continue;
1973
		}
1974
		/* NB. leave filename pointing to private key */
1975
		identity_files[n_ids] = xstrdup(filename);
1976
		identity_keys[n_ids] = public;
1977
		n_ids++;
1978
	}
1979
1980
	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
1981
		fatal("%s: too many certificates", __func__);
1982
	for (i = 0; i < options.num_certificate_files; i++) {
1983
		cp = tilde_expand_filename(options.certificate_files[i],
1984
		    original_real_uid);
1985
		filename = percent_expand(cp, "d", pw->pw_dir,
1986
		    "u", pw->pw_name, "l", thishost, "h", host,
1987
		    "r", options.user, (char *)NULL);
1988
		free(cp);
1989
1990
		public = key_load_public(filename, NULL);
1991
		debug("certificate file %s type %d", filename,
1992
		    public ? public->type : -1);
1993
		free(options.certificate_files[i]);
1994
		options.certificate_files[i] = NULL;
1995
		if (public == NULL) {
1996
			free(filename);
1997
			continue;
1998
		}
1999
		if (!key_is_cert(public)) {
2000
			debug("%s: key %s type %s is not a certificate",
2001
			    __func__, filename, key_type(public));
2002
			key_free(public);
2003
			free(filename);
2004
			continue;
2005
		}
2006
		certificate_files[n_certs] = filename;
2007
		certificates[n_certs] = public;
2008
		++n_certs;
2009
	}
2010
2011
	options.num_identity_files = n_ids;
2012
	memcpy(options.identity_files, identity_files, sizeof(identity_files));
2013
	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2014
2015
	options.num_certificate_files = n_certs;
2016
	memcpy(options.certificate_files,
2017
	    certificate_files, sizeof(certificate_files));
2018
	memcpy(options.certificates, certificates, sizeof(certificates));
2019
}
2020
2021
static void
2022
main_sigchld_handler(int sig)
2023
{
2024
	int save_errno = errno;
2025
	pid_t pid;
2026
	int status;
2027
2028
	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2029
	    (pid < 0 && errno == EINTR))
2030
		;
2031
2032
	signal(sig, main_sigchld_handler);
2033
	errno = save_errno;
2034
}