GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.bin/ssh/ssh/../ssh.c Lines: 313 1010 31.0 %
Date: 2017-11-07 Branches: 129 598 21.6 %

Line Branch Exec Source
1
/* $OpenBSD: ssh.c,v 1.464 2017/09/21 19:16:53 markus 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
/* socket address the host resolves to */
156
struct sockaddr_storage hostaddr;
157
158
/* Private host keys. */
159
Sensitive sensitive_data;
160
161
/* Original real UID. */
162
uid_t original_real_uid;
163
uid_t original_effective_uid;
164
165
/* command to be executed */
166
Buffer command;
167
168
/* Should we execute a command or invoke a subsystem? */
169
int subsystem_flag = 0;
170
171
/* # of replies received for global requests */
172
static int remote_forward_confirms_received = 0;
173
174
/* mux.c */
175
extern int muxserver_sock;
176
extern u_int muxclient_command;
177
178
/* Prints a help message to the user.  This function never returns. */
179
180
static void
181
usage(void)
182
{
183
	fprintf(stderr,
184
"usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
185
"           [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
186
"           [-F configfile] [-I pkcs11] [-i identity_file]\n"
187
"           [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]\n"
188
"           [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]\n"
189
"           [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]\n"
190
"           [user@]hostname [command]\n"
191
	);
192
	exit(255);
193
}
194
195
static int ssh_session2(struct ssh *);
196
static void load_public_identity_files(void);
197
static void main_sigchld_handler(int);
198
199
/* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
200
static void
201
tilde_expand_paths(char **paths, u_int num_paths)
202
{
203
	u_int i;
204
	char *cp;
205
206
14
	for (i = 0; i < num_paths; i++) {
207
4
		cp = tilde_expand_filename(paths[i], original_real_uid);
208
4
		free(paths[i]);
209
4
		paths[i] = cp;
210
	}
211
2
}
212
213
/*
214
 * Attempt to resolve a host name / port to a set of addresses and
215
 * optionally return any CNAMEs encountered along the way.
216
 * Returns NULL on failure.
217
 * NB. this function must operate with a options having undefined members.
218
 */
219
static struct addrinfo *
220
resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
221
{
222
2
	char strport[NI_MAXSERV];
223
1
	struct addrinfo hints, *res;
224
	int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
225
226
1
	if (port <= 0)
227
		port = default_ssh_port();
228
229
1
	snprintf(strport, sizeof strport, "%d", port);
230
1
	memset(&hints, 0, sizeof(hints));
231
1
	hints.ai_family = options.address_family == -1 ?
232
	    AF_UNSPEC : options.address_family;
233
1
	hints.ai_socktype = SOCK_STREAM;
234
1
	if (cname != NULL)
235
1
		hints.ai_flags = AI_CANONNAME;
236
1
	if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
237
		if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
238
			loglevel = SYSLOG_LEVEL_ERROR;
239
		do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
240
		    __progname, name, ssh_gai_strerror(gaierr));
241
		return NULL;
242
	}
243

2
	if (cname != NULL && res->ai_canonname != NULL) {
244
		if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
245
			error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
246
			    __func__, name,  res->ai_canonname, (u_long)clen);
247
			if (clen > 0)
248
				*cname = '\0';
249
		}
250
	}
251
1
	return res;
252
1
}
253
254
/*
255
 * Attempt to resolve a numeric host address / port to a single address.
256
 * Returns a canonical address string.
257
 * Returns NULL on failure.
258
 * NB. this function must operate with a options having undefined members.
259
 */
260
static struct addrinfo *
261
resolve_addr(const char *name, int port, char *caddr, size_t clen)
262
{
263
	char addr[NI_MAXHOST], strport[NI_MAXSERV];
264
	struct addrinfo hints, *res;
265
	int gaierr;
266
267
	if (port <= 0)
268
		port = default_ssh_port();
269
	snprintf(strport, sizeof strport, "%u", port);
270
	memset(&hints, 0, sizeof(hints));
271
	hints.ai_family = options.address_family == -1 ?
272
	    AF_UNSPEC : options.address_family;
273
	hints.ai_socktype = SOCK_STREAM;
274
	hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
275
	if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
276
		debug2("%s: could not resolve name %.100s as address: %s",
277
		    __func__, name, ssh_gai_strerror(gaierr));
278
		return NULL;
279
	}
280
	if (res == NULL) {
281
		debug("%s: getaddrinfo %.100s returned no addresses",
282
		 __func__, name);
283
		return NULL;
284
	}
285
	if (res->ai_next != NULL) {
286
		debug("%s: getaddrinfo %.100s returned multiple addresses",
287
		    __func__, name);
288
		goto fail;
289
	}
290
	if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
291
	    addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
292
		debug("%s: Could not format address for name %.100s: %s",
293
		    __func__, name, ssh_gai_strerror(gaierr));
294
		goto fail;
295
	}
296
	if (strlcpy(caddr, addr, clen) >= clen) {
297
		error("%s: host \"%s\" addr \"%s\" too long (max %lu)",
298
		    __func__, name,  addr, (u_long)clen);
299
		if (clen > 0)
300
			*caddr = '\0';
301
 fail:
302
		freeaddrinfo(res);
303
		return NULL;
304
	}
305
	return res;
306
}
307
308
/*
309
 * Check whether the cname is a permitted replacement for the hostname
310
 * and perform the replacement if it is.
311
 * NB. this function must operate with a options having undefined members.
312
 */
313
static int
314
check_follow_cname(int direct, char **namep, const char *cname)
315
{
316
	int i;
317
	struct allowed_cname *rule;
318
319
	if (*cname == '\0' || options.num_permitted_cnames == 0 ||
320
	    strcmp(*namep, cname) == 0)
321
		return 0;
322
	if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
323
		return 0;
324
	/*
325
	 * Don't attempt to canonicalize names that will be interpreted by
326
	 * a proxy or jump host unless the user specifically requests so.
327
	 */
328
	if (!direct &&
329
	    options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
330
		return 0;
331
	debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
332
	for (i = 0; i < options.num_permitted_cnames; i++) {
333
		rule = options.permitted_cnames + i;
334
		if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
335
		    match_pattern_list(cname, rule->target_list, 1) != 1)
336
			continue;
337
		verbose("Canonicalized DNS aliased hostname "
338
		    "\"%s\" => \"%s\"", *namep, cname);
339
		free(*namep);
340
		*namep = xstrdup(cname);
341
		return 1;
342
	}
343
	return 0;
344
}
345
346
/*
347
 * Attempt to resolve the supplied hostname after applying the user's
348
 * canonicalization rules. Returns the address list for the host or NULL
349
 * if no name was found after canonicalization.
350
 * NB. this function must operate with a options having undefined members.
351
 */
352
static struct addrinfo *
353
resolve_canonicalize(char **hostp, int port)
354
{
355
	int i, direct, ndots;
356
	char *cp, *fullhost, newname[NI_MAXHOST];
357
	struct addrinfo *addrs;
358
359
	if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
360
		return NULL;
361
362
	/*
363
	 * Don't attempt to canonicalize names that will be interpreted by
364
	 * a proxy unless the user specifically requests so.
365
	 */
366
	direct = option_clear_or_none(options.proxy_command) &&
367
	    options.jump_host == NULL;
368
	if (!direct &&
369
	    options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
370
		return NULL;
371
372
	/* Try numeric hostnames first */
373
	if ((addrs = resolve_addr(*hostp, port,
374
	    newname, sizeof(newname))) != NULL) {
375
		debug2("%s: hostname %.100s is address", __func__, *hostp);
376
		if (strcasecmp(*hostp, newname) != 0) {
377
			debug2("%s: canonicalised address \"%s\" => \"%s\"",
378
			    __func__, *hostp, newname);
379
			free(*hostp);
380
			*hostp = xstrdup(newname);
381
		}
382
		return addrs;
383
	}
384
385
	/* If domain name is anchored, then resolve it now */
386
	if ((*hostp)[strlen(*hostp) - 1] == '.') {
387
		debug3("%s: name is fully qualified", __func__);
388
		fullhost = xstrdup(*hostp);
389
		if ((addrs = resolve_host(fullhost, port, 0,
390
		    newname, sizeof(newname))) != NULL)
391
			goto found;
392
		free(fullhost);
393
		goto notfound;
394
	}
395
396
	/* Don't apply canonicalization to sufficiently-qualified hostnames */
397
	ndots = 0;
398
	for (cp = *hostp; *cp != '\0'; cp++) {
399
		if (*cp == '.')
400
			ndots++;
401
	}
402
	if (ndots > options.canonicalize_max_dots) {
403
		debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
404
		    __func__, *hostp, options.canonicalize_max_dots);
405
		return NULL;
406
	}
407
	/* Attempt each supplied suffix */
408
	for (i = 0; i < options.num_canonical_domains; i++) {
409
		*newname = '\0';
410
		xasprintf(&fullhost, "%s.%s.", *hostp,
411
		    options.canonical_domains[i]);
412
		debug3("%s: attempting \"%s\" => \"%s\"", __func__,
413
		    *hostp, fullhost);
414
		if ((addrs = resolve_host(fullhost, port, 0,
415
		    newname, sizeof(newname))) == NULL) {
416
			free(fullhost);
417
			continue;
418
		}
419
 found:
420
		/* Remove trailing '.' */
421
		fullhost[strlen(fullhost) - 1] = '\0';
422
		/* Follow CNAME if requested */
423
		if (!check_follow_cname(direct, &fullhost, newname)) {
424
			debug("Canonicalized hostname \"%s\" => \"%s\"",
425
			    *hostp, fullhost);
426
		}
427
		free(*hostp);
428
		*hostp = fullhost;
429
		return addrs;
430
	}
431
 notfound:
432
	if (!options.canonicalize_fallback_local)
433
		fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
434
	debug2("%s: host %s not found in any suffix", __func__, *hostp);
435
	return NULL;
436
}
437
438
/*
439
 * Read per-user configuration file.  Ignore the system wide config
440
 * file if the user specifies a config file on the command line.
441
 */
442
static void
443
process_config_files(const char *host_arg, struct passwd *pw, int post_canon)
444
{
445
2
	char buf[PATH_MAX];
446
	int r;
447
448
1
	if (config != NULL) {
449
		if (strcasecmp(config, "none") != 0 &&
450
		    !read_config_file(config, pw, host, host_arg, &options,
451
		    SSHCONF_USERCONF | (post_canon ? SSHCONF_POSTCANON : 0)))
452
			fatal("Can't open user config file %.100s: "
453
			    "%.100s", config, strerror(errno));
454
	} else {
455
1
		r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
456
		    _PATH_SSH_USER_CONFFILE);
457

2
		if (r > 0 && (size_t)r < sizeof(buf))
458
2
			(void)read_config_file(buf, pw, host, host_arg,
459
1
			    &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
460
1
			    (post_canon ? SSHCONF_POSTCANON : 0));
461
462
		/* Read systemwide configuration file after user config. */
463
1
		(void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
464
1
		    host, host_arg, &options,
465
1
		    post_canon ? SSHCONF_POSTCANON : 0);
466
	}
467
1
}
468
469
/* Rewrite the port number in an addrinfo list of addresses */
470
static void
471
set_addrinfo_port(struct addrinfo *addrs, int port)
472
{
473
	struct addrinfo *addr;
474
475
	for (addr = addrs; addr != NULL; addr = addr->ai_next) {
476
		switch (addr->ai_family) {
477
		case AF_INET:
478
			((struct sockaddr_in *)addr->ai_addr)->
479
			    sin_port = htons(port);
480
			break;
481
		case AF_INET6:
482
			((struct sockaddr_in6 *)addr->ai_addr)->
483
			    sin6_port = htons(port);
484
			break;
485
		}
486
	}
487
}
488
489
/*
490
 * Main program for the ssh client.
491
 */
492
int
493
main(int ac, char **av)
494
{
495
	struct ssh *ssh = NULL;
496
2
	int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
497
	int config_test = 0, opt_terminated = 0;
498
1
	char *p, *cp, *line, *argv0, buf[PATH_MAX], *host_arg, *logfile;
499
1
	char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
500
1
	char cname[NI_MAXHOST], uidstr[32], *conn_hash_hex;
501
1
	struct stat st;
502
	struct passwd *pw;
503
	extern int optind, optreset;
504
	extern char *optarg;
505
1
	struct Forward fwd;
506
	struct addrinfo *addrs = NULL;
507
	struct ssh_digest_ctx *md;
508
1
	u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
509
510
1
	ssh_malloc_init();	/* must be called before any mallocs */
511
	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
512
1
	sanitise_stdfd();
513
514
	/*
515
	 * Discard other fds that are hanging around. These can cause problem
516
	 * with backgrounded ssh processes started by ControlPersist.
517
	 */
518
1
	closefrom(STDERR_FILENO + 1);
519
520
	/*
521
	 * Save the original real uid.  It will be needed later (uid-swapping
522
	 * may clobber the real uid).
523
	 */
524
1
	original_real_uid = getuid();
525
1
	original_effective_uid = geteuid();
526
527
	/*
528
	 * Use uid-swapping to give up root privileges for the duration of
529
	 * option processing.  We will re-instantiate the rights when we are
530
	 * ready to create the privileged port, and will permanently drop
531
	 * them when the port has been created (actually, when the connection
532
	 * has been made, as we may need to create the port several times).
533
	 */
534
2
	PRIV_END;
535
536
	/* If we are installed setuid root be careful to not drop core. */
537
1
	if (original_real_uid != original_effective_uid) {
538
		struct rlimit rlim;
539
		rlim.rlim_cur = rlim.rlim_max = 0;
540
		if (setrlimit(RLIMIT_CORE, &rlim) < 0)
541
			fatal("setrlimit failed: %.100s", strerror(errno));
542
	}
543
	/* Get user data. */
544
1
	pw = getpwuid(original_real_uid);
545
1
	if (!pw) {
546
		logit("No user exists for uid %lu", (u_long)original_real_uid);
547
		exit(255);
548
	}
549
	/* Take a copy of the returned structure. */
550
1
	pw = pwcopy(pw);
551
552
	/*
553
	 * Set our umask to something reasonable, as some files are created
554
	 * with the default umask.  This will make them world-readable but
555
	 * writable only by the owner, which is ok for all files for which we
556
	 * don't set the modes explicitly.
557
	 */
558
1
	umask(022);
559
560
1
	setlocale(LC_CTYPE, "");
561
562
	/*
563
	 * Initialize option structure to indicate that no values have been
564
	 * set.
565
	 */
566
1
	initialize_options(&options);
567
568
	/*
569
	 * Prepare main ssh transport/connection structures
570
	 */
571
1
	if ((ssh = ssh_alloc_session_state()) == NULL)
572
		fatal("Couldn't allocate session state");
573
1
	channel_init_channels(ssh);
574
1
	active_state = ssh; /* XXX legacy API compat */
575
576
	/* Parse command-line arguments. */
577
1
	host = NULL;
578
	use_syslog = 0;
579
	logfile = NULL;
580
1
	argv0 = av[0];
581
582
 again:
583
13
	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
584
6
	    "ACD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
585











10
		switch (opt) {
586
		case '1':
587
			fatal("SSH protocol v.1 is no longer supported");
588
			break;
589
		case '2':
590
			/* Ignored */
591
			break;
592
		case '4':
593
			options.address_family = AF_INET;
594
			break;
595
		case '6':
596
			options.address_family = AF_INET6;
597
			break;
598
		case 'n':
599
			stdin_null_flag = 1;
600
			break;
601
		case 'f':
602
			fork_after_authentication_flag = 1;
603
			stdin_null_flag = 1;
604
			break;
605
		case 'x':
606
1
			options.forward_x11 = 0;
607
1
			break;
608
		case 'X':
609
			options.forward_x11 = 1;
610
			break;
611
		case 'y':
612
			use_syslog = 1;
613
			break;
614
		case 'E':
615
			logfile = optarg;
616
			break;
617
		case 'G':
618
			config_test = 1;
619
			break;
620
		case 'Y':
621
			options.forward_x11 = 1;
622
			options.forward_x11_trusted = 1;
623
			break;
624
		case 'g':
625
			options.fwd_opts.gateway_ports = 1;
626
			break;
627
		case 'O':
628
			if (options.stdio_forward_host != NULL)
629
				fatal("Cannot specify multiplexing "
630
				    "command with -W");
631
			else if (muxclient_command != 0)
632
				fatal("Multiplexing command already specified");
633
			if (strcmp(optarg, "check") == 0)
634
				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
635
			else if (strcmp(optarg, "forward") == 0)
636
				muxclient_command = SSHMUX_COMMAND_FORWARD;
637
			else if (strcmp(optarg, "exit") == 0)
638
				muxclient_command = SSHMUX_COMMAND_TERMINATE;
639
			else if (strcmp(optarg, "stop") == 0)
640
				muxclient_command = SSHMUX_COMMAND_STOP;
641
			else if (strcmp(optarg, "cancel") == 0)
642
				muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
643
			else if (strcmp(optarg, "proxy") == 0)
644
				muxclient_command = SSHMUX_COMMAND_PROXY;
645
			else
646
				fatal("Invalid multiplex command.");
647
			break;
648
		case 'P':	/* deprecated */
649
			options.use_privileged_port = 0;
650
			break;
651
		case 'Q':
652
			cp = NULL;
653
			if (strcmp(optarg, "cipher") == 0)
654
				cp = cipher_alg_list('\n', 0);
655
			else if (strcmp(optarg, "cipher-auth") == 0)
656
				cp = cipher_alg_list('\n', 1);
657
			else if (strcmp(optarg, "mac") == 0)
658
				cp = mac_alg_list('\n');
659
			else if (strcmp(optarg, "kex") == 0)
660
				cp = kex_alg_list('\n');
661
			else if (strcmp(optarg, "key") == 0)
662
				cp = sshkey_alg_list(0, 0, 0, '\n');
663
			else if (strcmp(optarg, "key-cert") == 0)
664
				cp = sshkey_alg_list(1, 0, 0, '\n');
665
			else if (strcmp(optarg, "key-plain") == 0)
666
				cp = sshkey_alg_list(0, 1, 0, '\n');
667
			else if (strcmp(optarg, "protocol-version") == 0) {
668
				cp = xstrdup("2");
669
			}
670
			if (cp == NULL)
671
				fatal("Unsupported query \"%s\"", optarg);
672
			printf("%s\n", cp);
673
			free(cp);
674
			exit(0);
675
			break;
676
		case 'a':
677
			options.forward_agent = 0;
678
			break;
679
		case 'A':
680
			options.forward_agent = 1;
681
			break;
682
		case 'k':
683
			options.gss_deleg_creds = 0;
684
			break;
685
		case 'K':
686
			options.gss_authentication = 1;
687
			options.gss_deleg_creds = 1;
688
			break;
689
		case 'i':
690
			p = tilde_expand_filename(optarg, original_real_uid);
691
			if (stat(p, &st) < 0)
692
				fprintf(stderr, "Warning: Identity file %s "
693
				    "not accessible: %s.\n", p,
694
				    strerror(errno));
695
			else
696
				add_identity_file(&options, NULL, p, 1);
697
			free(p);
698
			break;
699
		case 'I':
700
#ifdef ENABLE_PKCS11
701
			free(options.pkcs11_provider);
702
			options.pkcs11_provider = xstrdup(optarg);
703
#else
704
			fprintf(stderr, "no support for PKCS#11.\n");
705
#endif
706
			break;
707
		case 'J':
708
			if (options.jump_host != NULL)
709
				fatal("Only a single -J option permitted");
710
			if (options.proxy_command != NULL)
711
				fatal("Cannot specify -J with ProxyCommand");
712
			if (parse_jump(optarg, &options, 1) == -1)
713
				fatal("Invalid -J argument");
714
			options.proxy_command = xstrdup("none");
715
			break;
716
		case 't':
717
			if (options.request_tty == REQUEST_TTY_YES)
718
				options.request_tty = REQUEST_TTY_FORCE;
719
			else
720
				options.request_tty = REQUEST_TTY_YES;
721
			break;
722
		case 'v':
723
			if (debug_flag == 0) {
724
				debug_flag = 1;
725
				options.log_level = SYSLOG_LEVEL_DEBUG1;
726
			} else {
727
				if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
728
					debug_flag++;
729
					options.log_level++;
730
				}
731
			}
732
			break;
733
		case 'V':
734
			fprintf(stderr, "%s, %s\n",
735
			    SSH_VERSION,
736
#ifdef WITH_OPENSSL
737
			    SSLeay_version(SSLEAY_VERSION)
738
#else
739
			    "without OpenSSL"
740
#endif
741
			);
742
			if (opt == 'V')
743
				exit(0);
744
			break;
745
		case 'w':
746
			if (options.tun_open == -1)
747
				options.tun_open = SSH_TUNMODE_DEFAULT;
748
			options.tun_local = a2tun(optarg, &options.tun_remote);
749
			if (options.tun_local == SSH_TUNID_ERR) {
750
				fprintf(stderr,
751
				    "Bad tun device '%s'\n", optarg);
752
				exit(255);
753
			}
754
			break;
755
		case 'W':
756
			if (options.stdio_forward_host != NULL)
757
				fatal("stdio forward already specified");
758
			if (muxclient_command != 0)
759
				fatal("Cannot specify stdio forward with -O");
760
			if (parse_forward(&fwd, optarg, 1, 0)) {
761
				options.stdio_forward_host = fwd.listen_host;
762
				options.stdio_forward_port = fwd.listen_port;
763
				free(fwd.connect_host);
764
			} else {
765
				fprintf(stderr,
766
				    "Bad stdio forwarding specification '%s'\n",
767
				    optarg);
768
				exit(255);
769
			}
770
			options.request_tty = REQUEST_TTY_NO;
771
			no_shell_flag = 1;
772
			break;
773
		case 'q':
774
			options.log_level = SYSLOG_LEVEL_QUIET;
775
			break;
776
		case 'e':
777
			if (optarg[0] == '^' && optarg[2] == 0 &&
778
			    (u_char) optarg[1] >= 64 &&
779
			    (u_char) optarg[1] < 128)
780
				options.escape_char = (u_char) optarg[1] & 31;
781
			else if (strlen(optarg) == 1)
782
				options.escape_char = (u_char) optarg[0];
783
			else if (strcmp(optarg, "none") == 0)
784
				options.escape_char = SSH_ESCAPECHAR_NONE;
785
			else {
786
				fprintf(stderr, "Bad escape character '%s'.\n",
787
				    optarg);
788
				exit(255);
789
			}
790
			break;
791
		case 'c':
792
			if (!ciphers_valid(*optarg == '+' ?
793
			    optarg + 1 : optarg)) {
794
				fprintf(stderr, "Unknown cipher type '%s'\n",
795
				    optarg);
796
				exit(255);
797
			}
798
			free(options.ciphers);
799
			options.ciphers = xstrdup(optarg);
800
			break;
801
		case 'm':
802
			if (mac_valid(optarg)) {
803
				free(options.macs);
804
				options.macs = xstrdup(optarg);
805
			} else {
806
				fprintf(stderr, "Unknown mac type '%s'\n",
807
				    optarg);
808
				exit(255);
809
			}
810
			break;
811
		case 'M':
812
			if (options.control_master == SSHCTL_MASTER_YES)
813
				options.control_master = SSHCTL_MASTER_ASK;
814
			else
815
				options.control_master = SSHCTL_MASTER_YES;
816
			break;
817
		case 'p':
818
			options.port = a2port(optarg);
819
			if (options.port <= 0) {
820
				fprintf(stderr, "Bad port '%s'\n", optarg);
821
				exit(255);
822
			}
823
			break;
824
		case 'l':
825
1
			options.user = optarg;
826
1
			break;
827
828
		case 'L':
829
			if (parse_forward(&fwd, optarg, 0, 0))
830
				add_local_forward(&options, &fwd);
831
			else {
832
				fprintf(stderr,
833
				    "Bad local forwarding specification '%s'\n",
834
				    optarg);
835
				exit(255);
836
			}
837
			break;
838
839
		case 'R':
840
			if (parse_forward(&fwd, optarg, 0, 1) ||
841
			    parse_forward(&fwd, optarg, 1, 1)) {
842
				add_remote_forward(&options, &fwd);
843
			} else {
844
				fprintf(stderr,
845
				    "Bad remote forwarding specification "
846
				    "'%s'\n", optarg);
847
				exit(255);
848
			}
849
			break;
850
851
		case 'D':
852
			if (parse_forward(&fwd, optarg, 1, 0)) {
853
				add_local_forward(&options, &fwd);
854
			} else {
855
				fprintf(stderr,
856
				    "Bad dynamic forwarding specification "
857
				    "'%s'\n", optarg);
858
				exit(255);
859
			}
860
			break;
861
862
		case 'C':
863
			options.compression = 1;
864
			break;
865
		case 'N':
866
			no_shell_flag = 1;
867
			options.request_tty = REQUEST_TTY_NO;
868
			break;
869
		case 'T':
870
			options.request_tty = REQUEST_TTY_NO;
871
			break;
872
		case 'o':
873
3
			line = xstrdup(optarg);
874
6
			if (process_config_line(&options, pw,
875
3
			    host ? host : "", host ? host : "", line,
876
3
			    "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
877
				exit(255);
878
3
			free(line);
879
3
			break;
880
		case 's':
881
			subsystem_flag = 1;
882
			break;
883
		case 'S':
884
			free(options.control_path);
885
			options.control_path = xstrdup(optarg);
886
			break;
887
		case 'b':
888
			options.bind_address = optarg;
889
			break;
890
		case 'F':
891
			config = optarg;
892
			break;
893
		default:
894
			usage();
895
		}
896
	}
897
898

2
	if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
899
1
		opt_terminated = 1;
900
901
1
	ac -= optind;
902
1
	av += optind;
903
904
1
	if (ac > 0 && !host) {
905
2
		if (strrchr(*av, '@')) {
906
1
			p = xstrdup(*av);
907
			cp = strrchr(p, '@');
908
			if (cp == NULL || cp == p)
909
				usage();
910
			options.user = p;
911
			*cp = '\0';
912
			host = xstrdup(++cp);
913
		} else
914
			host = xstrdup(*av);
915
1
		if (ac > 1 && !opt_terminated) {
916
			optind = optreset = 1;
917
			goto again;
918
		}
919
1
		ac--, av++;
920
1
	}
921
922
	/* Check that we got a host name. */
923
1
	if (!host)
924
		usage();
925
926
1
	host_arg = xstrdup(host);
927
928
#ifdef WITH_OPENSSL
929
1
	OpenSSL_add_all_algorithms();
930
1
	ERR_load_crypto_strings();
931
#endif
932
933
	/* Initialize the command to execute on remote host. */
934
1
	buffer_init(&command);
935
936
	/*
937
	 * Save the command to execute on the remote host in a buffer. There
938
	 * is no limit on the length of the command, except by the maximum
939
	 * packet size.  Also sets the tty flag if there is no command.
940
	 */
941
1
	if (!ac) {
942
		/* No command specified - execute shell on a tty. */
943
		if (subsystem_flag) {
944
			fprintf(stderr,
945
			    "You must specify a subsystem to invoke.\n");
946
			usage();
947
		}
948
	} else {
949
		/* A command has been specified.  Store it into the buffer. */
950
4
		for (i = 0; i < ac; i++) {
951
1
			if (i)
952
				buffer_append(&command, " ", 1);
953
1
			buffer_append(&command, av[i], strlen(av[i]));
954
		}
955
	}
956
957
	/*
958
	 * Initialize "log" output.  Since we are the client all output
959
	 * goes to stderr unless otherwise specified by -y or -E.
960
	 */
961
1
	if (use_syslog && logfile != NULL)
962
		fatal("Can't specify both -y and -E");
963
1
	if (logfile != NULL)
964
		log_redirect_stderr_to(logfile);
965
1
	log_init(argv0,
966
1
	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
967
	    SYSLOG_LEVEL_INFO : options.log_level,
968
1
	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
969
	    SYSLOG_FACILITY_USER : options.log_facility,
970
1
	    !use_syslog);
971
972
1
	if (debug_flag)
973
		logit("%s, %s", SSH_VERSION,
974
#ifdef WITH_OPENSSL
975
		    SSLeay_version(SSLEAY_VERSION)
976
#else
977
		    "without OpenSSL"
978
#endif
979
		);
980
981
	/* Parse the configuration files */
982
1
	process_config_files(host_arg, pw, 0);
983
984
	/* Hostname canonicalisation needs a few options filled. */
985
1
	fill_default_options_for_canonicalization(&options);
986
987
	/* If the user has replaced the hostname then take it into use now */
988
1
	if (options.hostname != NULL) {
989
		/* NB. Please keep in sync with readconf.c:match_cfg_line() */
990
		cp = percent_expand(options.hostname,
991
		    "h", host, (char *)NULL);
992
		free(host);
993
		host = cp;
994
		free(options.hostname);
995
		options.hostname = xstrdup(host);
996
	}
997
998
	/* If canonicalization requested then try to apply it */
999
1
	lowercase(host);
1000
1
	if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
1001
		addrs = resolve_canonicalize(&host, options.port);
1002
1003
	/*
1004
	 * If CanonicalizePermittedCNAMEs have been specified but
1005
	 * other canonicalization did not happen (by not being requested
1006
	 * or by failing with fallback) then the hostname may still be changed
1007
	 * as a result of CNAME following.
1008
	 *
1009
	 * Try to resolve the bare hostname name using the system resolver's
1010
	 * usual search rules and then apply the CNAME follow rules.
1011
	 *
1012
	 * Skip the lookup if a ProxyCommand is being used unless the user
1013
	 * has specifically requested canonicalisation for this case via
1014
	 * CanonicalizeHostname=always
1015
	 */
1016
2
	direct = option_clear_or_none(options.proxy_command) &&
1017
1
	    options.jump_host == NULL;
1018

1
	if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
1019
	    options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1020
		if ((addrs = resolve_host(host, options.port,
1021
		    option_clear_or_none(options.proxy_command),
1022
		    cname, sizeof(cname))) == NULL) {
1023
			/* Don't fatal proxied host names not in the DNS */
1024
			if (option_clear_or_none(options.proxy_command))
1025
				cleanup_exit(255); /* logged in resolve_host */
1026
		} else
1027
			check_follow_cname(direct, &host, cname);
1028
	}
1029
1030
	/*
1031
	 * If canonicalisation is enabled then re-parse the configuration
1032
	 * files as new stanzas may match.
1033
	 */
1034
1
	if (options.canonicalize_hostname != 0) {
1035
		debug("Re-reading configuration after hostname "
1036
		    "canonicalisation");
1037
		free(options.hostname);
1038
		options.hostname = xstrdup(host);
1039
		process_config_files(host_arg, pw, 1);
1040
		/*
1041
		 * Address resolution happens early with canonicalisation
1042
		 * enabled and the port number may have changed since, so
1043
		 * reset it in address list
1044
		 */
1045
		if (addrs != NULL && options.port > 0)
1046
			set_addrinfo_port(addrs, options.port);
1047
	}
1048
1049
	/* Fill configuration defaults. */
1050
1
	fill_default_options(&options);
1051
1052
	/*
1053
	 * If ProxyJump option specified, then construct a ProxyCommand now.
1054
	 */
1055
1
	if (options.jump_host != NULL) {
1056
		char port_s[8];
1057
1058
		/* Consistency check */
1059
		if (options.proxy_command != NULL)
1060
			fatal("inconsistent options: ProxyCommand+ProxyJump");
1061
		/* Never use FD passing for ProxyJump */
1062
		options.proxy_use_fdpass = 0;
1063
		snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1064
		xasprintf(&options.proxy_command,
1065
		    "ssh%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1066
		    /* Optional "-l user" argument if jump_user set */
1067
		    options.jump_user == NULL ? "" : " -l ",
1068
		    options.jump_user == NULL ? "" : options.jump_user,
1069
		    /* Optional "-p port" argument if jump_port set */
1070
		    options.jump_port <= 0 ? "" : " -p ",
1071
		    options.jump_port <= 0 ? "" : port_s,
1072
		    /* Optional additional jump hosts ",..." */
1073
		    options.jump_extra == NULL ? "" : " -J ",
1074
		    options.jump_extra == NULL ? "" : options.jump_extra,
1075
		    /* Optional "-F" argumment if -F specified */
1076
		    config == NULL ? "" : " -F ",
1077
		    config == NULL ? "" : config,
1078
		    /* Optional "-v" arguments if -v set */
1079
		    debug_flag ? " -" : "",
1080
		    debug_flag, "vvv",
1081
		    /* Mandatory hostname */
1082
		    options.jump_host);
1083
		debug("Setting implicit ProxyCommand from ProxyJump: %s",
1084
		    options.proxy_command);
1085
	}
1086
1087
1
	if (options.port == 0)
1088
1
		options.port = default_ssh_port();
1089
1
	channel_set_af(ssh, options.address_family);
1090
1091
	/* Tidy and check options */
1092
1
	if (options.host_key_alias != NULL)
1093
		lowercase(options.host_key_alias);
1094
1
	if (options.proxy_command != NULL &&
1095
	    strcmp(options.proxy_command, "-") == 0 &&
1096
	    options.proxy_use_fdpass)
1097
		fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1098
2
	if (options.control_persist &&
1099
1
	    options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1100
		debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
1101
		    "disabling");
1102
		options.update_hostkeys = 0;
1103
	}
1104
1
	if (options.connection_attempts <= 0)
1105
		fatal("Invalid number of ConnectionAttempts");
1106
1107
1
	if (original_effective_uid != 0)
1108
		options.use_privileged_port = 0;
1109
1110
1
	if (buffer_len(&command) != 0 && options.remote_command != NULL)
1111
		fatal("Cannot execute command-line and remote command.");
1112
1113
	/* Cannot fork to background if no command. */
1114

1
	if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
1115
	    options.remote_command == NULL && !no_shell_flag)
1116
		fatal("Cannot fork into background without a command "
1117
		    "to execute.");
1118
1119
	/* reinit */
1120
1
	log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1121
1122
2
	if (options.request_tty == REQUEST_TTY_YES ||
1123
1
	    options.request_tty == REQUEST_TTY_FORCE)
1124
		tty_flag = 1;
1125
1126
	/* Allocate a tty by default if no command specified. */
1127
1
	if (buffer_len(&command) == 0 && options.remote_command == NULL)
1128
		tty_flag = options.request_tty != REQUEST_TTY_NO;
1129
1130
	/* Force no tty */
1131
1
	if (options.request_tty == REQUEST_TTY_NO ||
1132
1
	    (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY))
1133
		tty_flag = 0;
1134
	/* Do not allocate a tty if stdin is not a tty. */
1135

4
	if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1136
1
	    options.request_tty != REQUEST_TTY_FORCE) {
1137
1
		if (tty_flag)
1138
			logit("Pseudo-terminal will not be allocated because "
1139
			    "stdin is not a terminal.");
1140
1
		tty_flag = 0;
1141
1
	}
1142
1143
1
	if (options.user == NULL)
1144
		options.user = xstrdup(pw->pw_name);
1145
1146
1
	if (gethostname(thishost, sizeof(thishost)) == -1)
1147
		fatal("gethostname: %s", strerror(errno));
1148
1
	strlcpy(shorthost, thishost, sizeof(shorthost));
1149
1
	shorthost[strcspn(thishost, ".")] = '\0';
1150
1
	snprintf(portstr, sizeof(portstr), "%d", options.port);
1151
1
	snprintf(uidstr, sizeof(uidstr), "%d", pw->pw_uid);
1152
1153

2
	if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
1154
1
	    ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
1155
1
	    ssh_digest_update(md, host, strlen(host)) < 0 ||
1156
1
	    ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
1157
1
	    ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
1158
1
	    ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
1159
		fatal("%s: mux digest failed", __func__);
1160
1
	ssh_digest_free(md);
1161
1
	conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
1162
1163
1
	if (options.local_command != NULL) {
1164
		debug3("expanding LocalCommand: %s", options.local_command);
1165
		cp = options.local_command;
1166
		options.local_command = percent_expand(cp,
1167
		    "C", conn_hash_hex,
1168
		    "L", shorthost,
1169
		    "d", pw->pw_dir,
1170
		    "h", host,
1171
		    "l", thishost,
1172
		    "n", host_arg,
1173
		    "p", portstr,
1174
		    "r", options.user,
1175
		    "u", pw->pw_name,
1176
		    (char *)NULL);
1177
		debug3("expanded LocalCommand: %s", options.local_command);
1178
		free(cp);
1179
	}
1180
1181
1
	if (options.remote_command != NULL) {
1182
		debug3("expanding RemoteCommand: %s", options.remote_command);
1183
		cp = options.remote_command;
1184
		options.remote_command = percent_expand(cp,
1185
		    "C", conn_hash_hex,
1186
		    "L", shorthost,
1187
		    "d", pw->pw_dir,
1188
		    "h", host,
1189
		    "l", thishost,
1190
		    "n", host_arg,
1191
		    "p", portstr,
1192
		    "r", options.user,
1193
		    "u", pw->pw_name,
1194
		    (char *)NULL);
1195
		debug3("expanded RemoteCommand: %s", options.remote_command);
1196
		free(cp);
1197
		buffer_append(&command, options.remote_command,
1198
		    strlen(options.remote_command));
1199
1200
	}
1201
1202
1
	if (options.control_path != NULL) {
1203
		cp = tilde_expand_filename(options.control_path,
1204
		    original_real_uid);
1205
		free(options.control_path);
1206
		options.control_path = percent_expand(cp,
1207
		    "C", conn_hash_hex,
1208
		    "L", shorthost,
1209
		    "h", host,
1210
		    "l", thishost,
1211
		    "n", host_arg,
1212
		    "p", portstr,
1213
		    "r", options.user,
1214
		    "u", pw->pw_name,
1215
		    "i", uidstr,
1216
		    (char *)NULL);
1217
		free(cp);
1218
	}
1219
1
	free(conn_hash_hex);
1220
1221
1
	if (config_test) {
1222
		dump_client_config(&options, host);
1223
		exit(0);
1224
	}
1225
1226
1
	if (muxclient_command != 0 && options.control_path == NULL)
1227
		fatal("No ControlPath specified for \"-O\" command");
1228
1
	if (options.control_path != NULL) {
1229
		int sock;
1230
		if ((sock = muxclient(options.control_path)) >= 0) {
1231
			ssh_packet_set_connection(ssh, sock, sock);
1232
			packet_set_mux();
1233
			goto skip_connect;
1234
		}
1235
	}
1236
1237
	/*
1238
	 * If hostname canonicalisation was not enabled, then we may not
1239
	 * have yet resolved the hostname. Do so now.
1240
	 */
1241
1
	if (addrs == NULL && options.proxy_command == NULL) {
1242
1
		debug2("resolving \"%s\" port %d", host, options.port);
1243
3
		if ((addrs = resolve_host(host, options.port, 1,
1244
2
		    cname, sizeof(cname))) == NULL)
1245
			cleanup_exit(255); /* resolve_host logs the error */
1246
	}
1247
1248
1
	timeout_ms = options.connection_timeout * 1000;
1249
1250
	/* Open a connection to the remote host. */
1251
3
	if (ssh_connect(ssh, host, addrs, &hostaddr, options.port,
1252
1
	    options.address_family, options.connection_attempts,
1253
1
	    &timeout_ms, options.tcp_keep_alive,
1254
2
	    options.use_privileged_port) != 0)
1255
		exit(255);
1256
1257
1
	if (addrs != NULL)
1258
1
		freeaddrinfo(addrs);
1259
1260
1
	packet_set_timeout(options.server_alive_interval,
1261
	    options.server_alive_count_max);
1262
1263
1
	ssh = active_state; /* XXX */
1264
1265
1
	if (timeout_ms > 0)
1266
		debug3("timeout: %d ms remain after connect", timeout_ms);
1267
1268
	/*
1269
	 * If we successfully made the connection, load the host private key
1270
	 * in case we will need it later for combined rsa-rhosts
1271
	 * authentication. This must be done before releasing extra
1272
	 * privileges, because the file is only readable by root.
1273
	 * If we cannot access the private keys, load the public keys
1274
	 * instead and try to execute the ssh-keysign helper instead.
1275
	 */
1276
1
	sensitive_data.nkeys = 0;
1277
1
	sensitive_data.keys = NULL;
1278
1
	sensitive_data.external_keysign = 0;
1279
1
	if (options.hostbased_authentication) {
1280
		sensitive_data.nkeys = 9;
1281
		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1282
		    sizeof(struct sshkey));	/* XXX */
1283
1284
		PRIV_START;
1285
		sensitive_data.keys[1] = key_load_private_cert(KEY_ECDSA,
1286
		    _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1287
		sensitive_data.keys[2] = key_load_private_cert(KEY_ED25519,
1288
		    _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1289
		sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1290
		    _PATH_HOST_RSA_KEY_FILE, "", NULL);
1291
		sensitive_data.keys[4] = key_load_private_cert(KEY_DSA,
1292
		    _PATH_HOST_DSA_KEY_FILE, "", NULL);
1293
		sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
1294
		    _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1295
		sensitive_data.keys[6] = key_load_private_type(KEY_ED25519,
1296
		    _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1297
		sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1298
		    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1299
		sensitive_data.keys[8] = key_load_private_type(KEY_DSA,
1300
		    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1301
		PRIV_END;
1302
1303
		if (options.hostbased_authentication == 1 &&
1304
		    sensitive_data.keys[0] == NULL &&
1305
		    sensitive_data.keys[5] == NULL &&
1306
		    sensitive_data.keys[6] == NULL &&
1307
		    sensitive_data.keys[7] == NULL &&
1308
		    sensitive_data.keys[8] == NULL) {
1309
			sensitive_data.keys[1] = key_load_cert(
1310
			    _PATH_HOST_ECDSA_KEY_FILE);
1311
			sensitive_data.keys[2] = key_load_cert(
1312
			    _PATH_HOST_ED25519_KEY_FILE);
1313
			sensitive_data.keys[3] = key_load_cert(
1314
			    _PATH_HOST_RSA_KEY_FILE);
1315
			sensitive_data.keys[4] = key_load_cert(
1316
			    _PATH_HOST_DSA_KEY_FILE);
1317
			sensitive_data.keys[5] = key_load_public(
1318
			    _PATH_HOST_ECDSA_KEY_FILE, NULL);
1319
			sensitive_data.keys[6] = key_load_public(
1320
			    _PATH_HOST_ED25519_KEY_FILE, NULL);
1321
			sensitive_data.keys[7] = key_load_public(
1322
			    _PATH_HOST_RSA_KEY_FILE, NULL);
1323
			sensitive_data.keys[8] = key_load_public(
1324
			    _PATH_HOST_DSA_KEY_FILE, NULL);
1325
			sensitive_data.external_keysign = 1;
1326
		}
1327
	}
1328
	/*
1329
	 * Get rid of any extra privileges that we may have.  We will no
1330
	 * longer need them.  Also, extra privileges could make it very hard
1331
	 * to read identity files and other non-world-readable files from the
1332
	 * user's home directory if it happens to be on a NFS volume where
1333
	 * root is mapped to nobody.
1334
	 */
1335
1
	if (original_effective_uid == 0) {
1336
2
		PRIV_START;
1337
1
		permanently_set_uid(pw);
1338
1
	}
1339
1340
	/*
1341
	 * Now that we are back to our own permissions, create ~/.ssh
1342
	 * directory if it doesn't already exist.
1343
	 */
1344
1
	if (config == NULL) {
1345
2
		r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1346
1
		    strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1347

3
		if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
1348
			if (mkdir(buf, 0700) < 0)
1349
				error("Could not create directory '%.200s'.",
1350
				    buf);
1351
	}
1352
1353
	/* load options.identity_files */
1354
1
	load_public_identity_files();
1355
1356
	/* optionally set the SSH_AUTHSOCKET_ENV_NAME varibale */
1357

1
	if (options.identity_agent &&
1358
	    strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1359
		if (strcmp(options.identity_agent, "none") == 0) {
1360
			unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1361
		} else {
1362
			p = tilde_expand_filename(options.identity_agent,
1363
			    original_real_uid);
1364
			cp = percent_expand(p, "d", pw->pw_dir,
1365
			    "u", pw->pw_name, "l", thishost, "h", host,
1366
			    "r", options.user, (char *)NULL);
1367
			setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1368
			free(cp);
1369
			free(p);
1370
		}
1371
	}
1372
1373
	/* Expand ~ in known host file names. */
1374
1
	tilde_expand_paths(options.system_hostfiles,
1375
1
	    options.num_system_hostfiles);
1376
1
	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1377
1378
1
	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1379
1
	signal(SIGCHLD, main_sigchld_handler);
1380
1381
	/* Log into the remote system.  Never returns if the login fails. */
1382
2
	ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1383
1
	    options.port, pw, timeout_ms);
1384
1385
1
	if (packet_connection_is_on_socket()) {
1386
1
		verbose("Authenticated to %s ([%s]:%d).", host,
1387
1
		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1388
1
	} else {
1389
		verbose("Authenticated to %s (via proxy).", host);
1390
	}
1391
1392
	/* We no longer need the private host keys.  Clear them now. */
1393
1
	if (sensitive_data.nkeys != 0) {
1394
		for (i = 0; i < sensitive_data.nkeys; i++) {
1395
			if (sensitive_data.keys[i] != NULL) {
1396
				/* Destroys contents safely */
1397
				debug3("clear hostkey %d", i);
1398
				key_free(sensitive_data.keys[i]);
1399
				sensitive_data.keys[i] = NULL;
1400
			}
1401
		}
1402
		free(sensitive_data.keys);
1403
	}
1404
10
	for (i = 0; i < options.num_identity_files; i++) {
1405
4
		free(options.identity_files[i]);
1406
4
		options.identity_files[i] = NULL;
1407
4
		if (options.identity_keys[i]) {
1408
			key_free(options.identity_keys[i]);
1409
			options.identity_keys[i] = NULL;
1410
		}
1411
	}
1412
2
	for (i = 0; i < options.num_certificate_files; i++) {
1413
		free(options.certificate_files[i]);
1414
		options.certificate_files[i] = NULL;
1415
	}
1416
1417
 skip_connect:
1418
1
	exit_status = ssh_session2(ssh);
1419
1
	packet_close();
1420
1421
1
	if (options.control_path != NULL && muxserver_sock != -1)
1422
		unlink(options.control_path);
1423
1424
	/* Kill ProxyCommand if it is running. */
1425
1
	ssh_kill_proxy_command();
1426
1427
1
	return exit_status;
1428
1
}
1429
1430
static void
1431
control_persist_detach(void)
1432
{
1433
	pid_t pid;
1434
	int devnull, keep_stderr;
1435
1436
	debug("%s: backgrounding master process", __func__);
1437
1438
 	/*
1439
 	 * master (current process) into the background, and make the
1440
 	 * foreground process a client of the backgrounded master.
1441
 	 */
1442
	switch ((pid = fork())) {
1443
	case -1:
1444
		fatal("%s: fork: %s", __func__, strerror(errno));
1445
	case 0:
1446
		/* Child: master process continues mainloop */
1447
 		break;
1448
 	default:
1449
		/* Parent: set up mux slave to connect to backgrounded master */
1450
		debug2("%s: background process is %ld", __func__, (long)pid);
1451
		stdin_null_flag = ostdin_null_flag;
1452
		options.request_tty = orequest_tty;
1453
		tty_flag = otty_flag;
1454
 		close(muxserver_sock);
1455
 		muxserver_sock = -1;
1456
		options.control_master = SSHCTL_MASTER_NO;
1457
 		muxclient(options.control_path);
1458
		/* muxclient() doesn't return on success. */
1459
 		fatal("Failed to connect to new control master");
1460
 	}
1461
	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1462
		error("%s: open(\"/dev/null\"): %s", __func__,
1463
		    strerror(errno));
1464
	} else {
1465
		keep_stderr = log_is_on_stderr() && debug_flag;
1466
		if (dup2(devnull, STDIN_FILENO) == -1 ||
1467
		    dup2(devnull, STDOUT_FILENO) == -1 ||
1468
		    (!keep_stderr && dup2(devnull, STDERR_FILENO) == -1))
1469
			error("%s: dup2: %s", __func__, strerror(errno));
1470
		if (devnull > STDERR_FILENO)
1471
			close(devnull);
1472
	}
1473
	daemon(1, 1);
1474
	setproctitle("%s [mux]", options.control_path);
1475
}
1476
1477
/* Do fork() after authentication. Used by "ssh -f" */
1478
static void
1479
fork_postauth(void)
1480
{
1481
	if (need_controlpersist_detach)
1482
		control_persist_detach();
1483
	debug("forking to background");
1484
	fork_after_authentication_flag = 0;
1485
	if (daemon(1, 1) < 0)
1486
		fatal("daemon() failed: %.200s", strerror(errno));
1487
}
1488
1489
/* Callback for remote forward global requests */
1490
static void
1491
ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1492
{
1493
	struct Forward *rfwd = (struct Forward *)ctxt;
1494
1495
	/* XXX verbose() on failure? */
1496
	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1497
	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1498
	    rfwd->listen_path ? rfwd->listen_path :
1499
	    rfwd->listen_host ? rfwd->listen_host : "",
1500
	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1501
	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1502
	    rfwd->connect_host, rfwd->connect_port);
1503
	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1504
		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1505
			rfwd->allocated_port = packet_get_int();
1506
			logit("Allocated port %u for remote forward to %s:%d",
1507
			    rfwd->allocated_port,
1508
			    rfwd->connect_host, rfwd->connect_port);
1509
			channel_update_permitted_opens(ssh,
1510
			    rfwd->handle, rfwd->allocated_port);
1511
		} else {
1512
			channel_update_permitted_opens(ssh, rfwd->handle, -1);
1513
		}
1514
	}
1515
1516
	if (type == SSH2_MSG_REQUEST_FAILURE) {
1517
		if (options.exit_on_forward_failure) {
1518
			if (rfwd->listen_path != NULL)
1519
				fatal("Error: remote port forwarding failed "
1520
				    "for listen path %s", rfwd->listen_path);
1521
			else
1522
				fatal("Error: remote port forwarding failed "
1523
				    "for listen port %d", rfwd->listen_port);
1524
		} else {
1525
			if (rfwd->listen_path != NULL)
1526
				logit("Warning: remote port forwarding failed "
1527
				    "for listen path %s", rfwd->listen_path);
1528
			else
1529
				logit("Warning: remote port forwarding failed "
1530
				    "for listen port %d", rfwd->listen_port);
1531
		}
1532
	}
1533
	if (++remote_forward_confirms_received == options.num_remote_forwards) {
1534
		debug("All remote forwarding requests processed");
1535
		if (fork_after_authentication_flag)
1536
			fork_postauth();
1537
	}
1538
}
1539
1540
static void
1541
client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1542
{
1543
	debug("stdio forwarding: done");
1544
	cleanup_exit(0);
1545
}
1546
1547
static void
1548
ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1549
{
1550
	if (!success)
1551
		fatal("stdio forwarding failed");
1552
}
1553
1554
static void
1555
ssh_init_stdio_forwarding(struct ssh *ssh)
1556
{
1557
	Channel *c;
1558
	int in, out;
1559
1560
2
	if (options.stdio_forward_host == NULL)
1561
1
		return;
1562
1563
	debug3("%s: %s:%d", __func__, options.stdio_forward_host,
1564
	    options.stdio_forward_port);
1565
1566
	if ((in = dup(STDIN_FILENO)) < 0 ||
1567
	    (out = dup(STDOUT_FILENO)) < 0)
1568
		fatal("channel_connect_stdio_fwd: dup() in/out failed");
1569
	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1570
	    options.stdio_forward_port, in, out)) == NULL)
1571
		fatal("%s: channel_connect_stdio_fwd failed", __func__);
1572
	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1573
	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1574
1
}
1575
1576
static void
1577
ssh_init_forwarding(struct ssh *ssh)
1578
{
1579
	int success = 0;
1580
	int i;
1581
1582
	/* Initiate local TCP/IP port forwardings. */
1583
3
	for (i = 0; i < options.num_local_forwards; i++) {
1584
		debug("Local connections to %.200s:%d forwarded to remote "
1585
		    "address %.200s:%d",
1586
		    (options.local_forwards[i].listen_path != NULL) ?
1587
		    options.local_forwards[i].listen_path :
1588
		    (options.local_forwards[i].listen_host == NULL) ?
1589
		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1590
		    options.local_forwards[i].listen_host,
1591
		    options.local_forwards[i].listen_port,
1592
		    (options.local_forwards[i].connect_path != NULL) ?
1593
		    options.local_forwards[i].connect_path :
1594
		    options.local_forwards[i].connect_host,
1595
		    options.local_forwards[i].connect_port);
1596
		success += channel_setup_local_fwd_listener(ssh,
1597
		    &options.local_forwards[i], &options.fwd_opts);
1598
	}
1599

1
	if (i > 0 && success != i && options.exit_on_forward_failure)
1600
		fatal("Could not request local forwarding.");
1601
1
	if (i > 0 && success == 0)
1602
		error("Could not request local forwarding.");
1603
1604
	/* Initiate remote TCP/IP port forwardings. */
1605
2
	for (i = 0; i < options.num_remote_forwards; i++) {
1606
		debug("Remote connections from %.200s:%d forwarded to "
1607
		    "local address %.200s:%d",
1608
		    (options.remote_forwards[i].listen_path != NULL) ?
1609
		    options.remote_forwards[i].listen_path :
1610
		    (options.remote_forwards[i].listen_host == NULL) ?
1611
		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1612
		    options.remote_forwards[i].listen_port,
1613
		    (options.remote_forwards[i].connect_path != NULL) ?
1614
		    options.remote_forwards[i].connect_path :
1615
		    options.remote_forwards[i].connect_host,
1616
		    options.remote_forwards[i].connect_port);
1617
		options.remote_forwards[i].handle =
1618
		    channel_request_remote_forwarding(ssh,
1619
		    &options.remote_forwards[i]);
1620
		if (options.remote_forwards[i].handle < 0) {
1621
			if (options.exit_on_forward_failure)
1622
				fatal("Could not request remote forwarding.");
1623
			else
1624
				logit("Warning: Could not request remote "
1625
				    "forwarding.");
1626
		} else {
1627
			client_register_global_confirm(
1628
			    ssh_confirm_remote_forward,
1629
			    &options.remote_forwards[i]);
1630
		}
1631
	}
1632
1633
	/* Initiate tunnel forwarding. */
1634
1
	if (options.tun_open != SSH_TUNMODE_NO) {
1635
		if (client_request_tun_fwd(ssh, options.tun_open,
1636
		    options.tun_local, options.tun_remote) == -1) {
1637
			if (options.exit_on_forward_failure)
1638
				fatal("Could not request tunnel forwarding.");
1639
			else
1640
				error("Could not request tunnel forwarding.");
1641
		}
1642
	}
1643
1
}
1644
1645
static void
1646
check_agent_present(void)
1647
{
1648
	int r;
1649
1650
2
	if (options.forward_agent) {
1651
		/* Clear agent forwarding if we don't have an agent. */
1652
		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1653
			options.forward_agent = 0;
1654
			if (r != SSH_ERR_AGENT_NOT_PRESENT)
1655
				debug("ssh_get_authentication_socket: %s",
1656
				    ssh_err(r));
1657
		}
1658
	}
1659
1
}
1660
1661
static void
1662
ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
1663
{
1664
	extern char **environ;
1665
	const char *display;
1666
2
	int interactive = tty_flag;
1667
1
	char *proto = NULL, *data = NULL;
1668
1669
1
	if (!success)
1670
		return; /* No need for error message, channels code sens one */
1671
1672
1
	display = getenv("DISPLAY");
1673
1
	if (display == NULL && options.forward_x11)
1674
		debug("X11 forwarding requested but DISPLAY not set");
1675

1
	if (options.forward_x11 && client_x11_get_proto(ssh, display,
1676
	    options.xauth_location, options.forward_x11_trusted,
1677
	    options.forward_x11_timeout, &proto, &data) == 0) {
1678
		/* Request forwarding with authentication spoofing. */
1679
		debug("Requesting X11 forwarding with authentication "
1680
		    "spoofing.");
1681
		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
1682
		    data, 1);
1683
		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
1684
		/* XXX exit_on_forward_failure */
1685
		interactive = 1;
1686
	}
1687
1688
1
	check_agent_present();
1689
1
	if (options.forward_agent) {
1690
		debug("Requesting authentication agent forwarding.");
1691
		channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1692
		packet_send();
1693
	}
1694
1695
	/* Tell the packet module whether this is an interactive session. */
1696
1
	packet_set_interactive(interactive,
1697
	    options.ip_qos_interactive, options.ip_qos_bulk);
1698
1699
2
	client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
1700
3
	    NULL, fileno(stdin), &command, environ);
1701
2
}
1702
1703
/* open new channel for a session */
1704
static int
1705
ssh_session2_open(struct ssh *ssh)
1706
{
1707
	Channel *c;
1708
	int window, packetmax, in, out, err;
1709
1710
2
	if (stdin_null_flag) {
1711
		in = open(_PATH_DEVNULL, O_RDONLY);
1712
	} else {
1713
1
		in = dup(STDIN_FILENO);
1714
	}
1715
1
	out = dup(STDOUT_FILENO);
1716
1
	err = dup(STDERR_FILENO);
1717
1718
1
	if (in < 0 || out < 0 || err < 0)
1719
		fatal("dup() in/out/err failed");
1720
1721
	/* enable nonblocking unless tty */
1722
1
	if (!isatty(in))
1723
1
		set_nonblock(in);
1724
1
	if (!isatty(out))
1725
1
		set_nonblock(out);
1726
1
	if (!isatty(err))
1727
		set_nonblock(err);
1728
1729
	window = CHAN_SES_WINDOW_DEFAULT;
1730
	packetmax = CHAN_SES_PACKET_DEFAULT;
1731
1
	if (tty_flag) {
1732
		window >>= 1;
1733
		packetmax >>= 1;
1734
	}
1735
1
	c = channel_new(ssh,
1736
	    "session", SSH_CHANNEL_OPENING, in, out, err,
1737
	    window, packetmax, CHAN_EXTENDED_WRITE,
1738
	    "client-session", /*nonblock*/0);
1739
1740
1
	debug3("%s: channel_new: %d", __func__, c->self);
1741
1742
1
	channel_send_open(ssh, c->self);
1743
1
	if (!no_shell_flag)
1744
1
		channel_register_open_confirm(ssh, c->self,
1745
		    ssh_session2_setup, NULL);
1746
1747
1
	return c->self;
1748
}
1749
1750
static int
1751
ssh_session2(struct ssh *ssh)
1752
{
1753
	int id = -1;
1754
1755
	/* XXX should be pre-session */
1756
2
	if (!options.control_persist)
1757
1
		ssh_init_stdio_forwarding(ssh);
1758
1
	ssh_init_forwarding(ssh);
1759
1760
	/* Start listening for multiplex clients */
1761
1
	if (!packet_get_mux())
1762
1
		muxserver_listen(ssh);
1763
1764
 	/*
1765
	 * If we are in control persist mode and have a working mux listen
1766
	 * socket, then prepare to background ourselves and have a foreground
1767
	 * client attach as a control slave.
1768
	 * NB. we must save copies of the flags that we override for
1769
	 * the backgrounding, since we defer attachment of the slave until
1770
	 * after the connection is fully established (in particular,
1771
	 * async rfwd replies have been received for ExitOnForwardFailure).
1772
	 */
1773
1
 	if (options.control_persist && muxserver_sock != -1) {
1774
		ostdin_null_flag = stdin_null_flag;
1775
		ono_shell_flag = no_shell_flag;
1776
		orequest_tty = options.request_tty;
1777
		otty_flag = tty_flag;
1778
 		stdin_null_flag = 1;
1779
 		no_shell_flag = 1;
1780
 		tty_flag = 0;
1781
		if (!fork_after_authentication_flag)
1782
			need_controlpersist_detach = 1;
1783
		fork_after_authentication_flag = 1;
1784
 	}
1785
	/*
1786
	 * ControlPersist mux listen socket setup failed, attempt the
1787
	 * stdio forward setup that we skipped earlier.
1788
	 */
1789
1
	if (options.control_persist && muxserver_sock == -1)
1790
		ssh_init_stdio_forwarding(ssh);
1791
1792

1
	if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1793
1
		id = ssh_session2_open(ssh);
1794
	else {
1795
		packet_set_interactive(
1796
		    options.control_master == SSHCTL_MASTER_NO,
1797
		    options.ip_qos_interactive, options.ip_qos_bulk);
1798
	}
1799
1800
	/* If we don't expect to open a new session, then disallow it */
1801

2
	if (options.control_master == SSHCTL_MASTER_NO &&
1802
1
	    (datafellows & SSH_NEW_OPENSSH)) {
1803
1
		debug("Requesting no-more-sessions@openssh.com");
1804
1
		packet_start(SSH2_MSG_GLOBAL_REQUEST);
1805
1
		packet_put_cstring("no-more-sessions@openssh.com");
1806
1
		packet_put_char(0);
1807
1
		packet_send();
1808
1
	}
1809
1810
	/* Execute a local command */
1811
2
	if (options.local_command != NULL &&
1812
1
	    options.permit_local_command)
1813
		ssh_local_cmd(options.local_command);
1814
1815
	/*
1816
	 * If requested and we are not interested in replies to remote
1817
	 * forwarding requests, then let ssh continue in the background.
1818
	 */
1819
1
	if (fork_after_authentication_flag) {
1820
		if (options.exit_on_forward_failure &&
1821
		    options.num_remote_forwards > 0) {
1822
			debug("deferring postauth fork until remote forward "
1823
			    "confirmation received");
1824
		} else
1825
			fork_postauth();
1826
	}
1827
1828
2
	return client_loop(ssh, tty_flag, tty_flag ?
1829
1
	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
1830
}
1831
1832
/* Loads all IdentityFile and CertificateFile keys */
1833
static void
1834
load_public_identity_files(void)
1835
{
1836
2
	char *filename, *cp, thishost[NI_MAXHOST];
1837
	char *pwdir = NULL, *pwname = NULL;
1838
	struct sshkey *public;
1839
	struct passwd *pw;
1840
	int i;
1841
	u_int n_ids, n_certs;
1842
1
	char *identity_files[SSH_MAX_IDENTITY_FILES];
1843
1
	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
1844
1
	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
1845
1
	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
1846
#ifdef ENABLE_PKCS11
1847
1
	struct sshkey **keys;
1848
	int nkeys;
1849
#endif /* PKCS11 */
1850
1851
	n_ids = n_certs = 0;
1852
1
	memset(identity_files, 0, sizeof(identity_files));
1853
1
	memset(identity_keys, 0, sizeof(identity_keys));
1854
1
	memset(certificate_files, 0, sizeof(certificate_files));
1855
1
	memset(certificates, 0, sizeof(certificates));
1856
1857
#ifdef ENABLE_PKCS11
1858

2
	if (options.pkcs11_provider != NULL &&
1859
1
	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1860
	    (pkcs11_init(!options.batch_mode) == 0) &&
1861
	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1862
	    &keys)) > 0) {
1863
		for (i = 0; i < nkeys; i++) {
1864
			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1865
				key_free(keys[i]);
1866
				continue;
1867
			}
1868
			identity_keys[n_ids] = keys[i];
1869
			identity_files[n_ids] =
1870
			    xstrdup(options.pkcs11_provider); /* XXX */
1871
			n_ids++;
1872
		}
1873
		free(keys);
1874
	}
1875
#endif /* ENABLE_PKCS11 */
1876
1
	if ((pw = getpwuid(original_real_uid)) == NULL)
1877
		fatal("load_public_identity_files: getpwuid failed");
1878
1
	pwname = xstrdup(pw->pw_name);
1879
1
	pwdir = xstrdup(pw->pw_dir);
1880
1
	if (gethostname(thishost, sizeof(thishost)) == -1)
1881
		fatal("load_public_identity_files: gethostname: %s",
1882
		    strerror(errno));
1883
10
	for (i = 0; i < options.num_identity_files; i++) {
1884

8
		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
1885
4
		    strcasecmp(options.identity_files[i], "none") == 0) {
1886
			free(options.identity_files[i]);
1887
			options.identity_files[i] = NULL;
1888
			continue;
1889
		}
1890
8
		cp = tilde_expand_filename(options.identity_files[i],
1891
4
		    original_real_uid);
1892
4
		filename = percent_expand(cp, "d", pwdir,
1893
4
		    "u", pwname, "l", thishost, "h", host,
1894
4
		    "r", options.user, (char *)NULL);
1895
4
		free(cp);
1896
4
		public = key_load_public(filename, NULL);
1897
4
		debug("identity file %s type %d", filename,
1898
8
		    public ? public->type : -1);
1899
4
		free(options.identity_files[i]);
1900
4
		identity_files[n_ids] = filename;
1901
4
		identity_keys[n_ids] = public;
1902
1903
8
		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1904
			continue;
1905
1906
		/*
1907
		 * If no certificates have been explicitly listed then try
1908
		 * to add the default certificate variant too.
1909
		 */
1910
4
		if (options.num_certificate_files != 0)
1911
			continue;
1912
4
		xasprintf(&cp, "%s-cert", filename);
1913
4
		public = key_load_public(cp, NULL);
1914
8
		debug("identity file %s type %d", cp,
1915
8
		    public ? public->type : -1);
1916
4
		if (public == NULL) {
1917
4
			free(cp);
1918
4
			continue;
1919
		}
1920
		if (!key_is_cert(public)) {
1921
			debug("%s: key %s type %s is not a certificate",
1922
			    __func__, cp, key_type(public));
1923
			key_free(public);
1924
			free(cp);
1925
			continue;
1926
		}
1927
		/* NB. leave filename pointing to private key */
1928
		identity_files[n_ids] = xstrdup(filename);
1929
		identity_keys[n_ids] = public;
1930
		n_ids++;
1931
	}
1932
1933
1
	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
1934
		fatal("%s: too many certificates", __func__);
1935
2
	for (i = 0; i < options.num_certificate_files; i++) {
1936
		cp = tilde_expand_filename(options.certificate_files[i],
1937
		    original_real_uid);
1938
		filename = percent_expand(cp, "d", pwdir,
1939
		    "u", pwname, "l", thishost, "h", host,
1940
		    "r", options.user, (char *)NULL);
1941
		free(cp);
1942
1943
		public = key_load_public(filename, NULL);
1944
		debug("certificate file %s type %d", filename,
1945
		    public ? public->type : -1);
1946
		free(options.certificate_files[i]);
1947
		options.certificate_files[i] = NULL;
1948
		if (public == NULL) {
1949
			free(filename);
1950
			continue;
1951
		}
1952
		if (!key_is_cert(public)) {
1953
			debug("%s: key %s type %s is not a certificate",
1954
			    __func__, filename, key_type(public));
1955
			key_free(public);
1956
			free(filename);
1957
			continue;
1958
		}
1959
		certificate_files[n_certs] = filename;
1960
		certificates[n_certs] = public;
1961
		++n_certs;
1962
	}
1963
1964
1
	options.num_identity_files = n_ids;
1965
1
	memcpy(options.identity_files, identity_files, sizeof(identity_files));
1966
1
	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1967
1968
1
	options.num_certificate_files = n_certs;
1969
1
	memcpy(options.certificate_files,
1970
	    certificate_files, sizeof(certificate_files));
1971
1
	memcpy(options.certificates, certificates, sizeof(certificates));
1972
1973
1
	explicit_bzero(pwname, strlen(pwname));
1974
1
	free(pwname);
1975
1
	explicit_bzero(pwdir, strlen(pwdir));
1976
1
	free(pwdir);
1977
1
}
1978
1979
static void
1980
main_sigchld_handler(int sig)
1981
{
1982
	int save_errno = errno;
1983
	pid_t pid;
1984
	int status;
1985
1986
	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1987
	    (pid < 0 && errno == EINTR))
1988
		;
1989
1990
	signal(sig, main_sigchld_handler);
1991
	errno = save_errno;
1992
}