xref: /netbsd-src/crypto/external/bsd/openssh/dist/readconf.c (revision a24efa7dea9f1f56c3bdb15a927d3516792ace1c)
1 /*	$NetBSD: readconf.c,v 1.18 2016/03/11 01:55:00 christos Exp $	*/
2 /* $OpenBSD: readconf.c,v 1.250 2016/02/08 23:40:12 djm Exp $ */
3 
4 /*
5  * Author: Tatu Ylonen <ylo@cs.hut.fi>
6  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7  *                    All rights reserved
8  * Functions for reading the configuration files.
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 
17 #include "includes.h"
18 __RCSID("$NetBSD: readconf.c,v 1.18 2016/03/11 01:55:00 christos Exp $");
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/socket.h>
22 #include <sys/wait.h>
23 #include <sys/un.h>
24 
25 #include <netinet/in.h>
26 #include <netinet/ip.h>
27 
28 #include <ctype.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <netdb.h>
32 #include <paths.h>
33 #include <pwd.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <limits.h>
39 #include <util.h>
40 #include <vis.h>
41 
42 #include "xmalloc.h"
43 #include "ssh.h"
44 #include "compat.h"
45 #include "cipher.h"
46 #include "pathnames.h"
47 #include "log.h"
48 #include "sshkey.h"
49 #include "misc.h"
50 #include "readconf.h"
51 #include "match.h"
52 #include "kex.h"
53 #include "mac.h"
54 #include "fmt_scaled.h"
55 #include "uidswap.h"
56 #include "myproposal.h"
57 #include "digest.h"
58 
59 /* Format of the configuration file:
60 
61    # Configuration data is parsed as follows:
62    #  1. command line options
63    #  2. user-specific file
64    #  3. system-wide file
65    # Any configuration value is only changed the first time it is set.
66    # Thus, host-specific definitions should be at the beginning of the
67    # configuration file, and defaults at the end.
68 
69    # Host-specific declarations.  These may override anything above.  A single
70    # host may match multiple declarations; these are processed in the order
71    # that they are given in.
72 
73    Host *.ngs.fi ngs.fi
74      User foo
75 
76    Host fake.com
77      HostName another.host.name.real.org
78      User blaah
79      Port 34289
80      ForwardX11 no
81      ForwardAgent no
82 
83    Host books.com
84      RemoteForward 9999 shadows.cs.hut.fi:9999
85      Cipher 3des
86 
87    Host fascist.blob.com
88      Port 23123
89      User tylonen
90      PasswordAuthentication no
91 
92    Host puukko.hut.fi
93      User t35124p
94      ProxyCommand ssh-proxy %h %p
95 
96    Host *.fr
97      PublicKeyAuthentication no
98 
99    Host *.su
100      Cipher none
101      PasswordAuthentication no
102 
103    Host vpn.fake.com
104      Tunnel yes
105      TunnelDevice 3
106 
107    # Defaults for various options
108    Host *
109      ForwardAgent no
110      ForwardX11 no
111      PasswordAuthentication yes
112      RSAAuthentication yes
113      RhostsRSAAuthentication yes
114      StrictHostKeyChecking yes
115      TcpKeepAlive no
116      IdentityFile ~/.ssh/identity
117      Port 22
118      EscapeChar ~
119 
120 */
121 
122 /* Keyword tokens. */
123 
124 typedef enum {
125 	oBadOption,
126 	oHost, oMatch,
127 	oForwardAgent, oForwardX11, oForwardX11Trusted, oForwardX11Timeout,
128 	oGatewayPorts, oExitOnForwardFailure,
129 	oPasswordAuthentication, oRSAAuthentication,
130 	oChallengeResponseAuthentication, oXAuthLocation,
131 #if defined(KRB4) || defined(KRB5)
132 	oKerberosAuthentication,
133 #endif
134 #if defined(AFS) || defined(KRB5)
135 	oKerberosTgtPassing,
136 #endif
137 #ifdef AFS
138 	oAFSTokenPassing,
139 #endif
140 	oIdentityFile, oHostName, oPort, oCipher, oRemoteForward, oLocalForward,
141 	oCertificateFile, oAddKeysToAgent,
142 	oUser, oEscapeChar, oRhostsRSAAuthentication, oProxyCommand,
143 	oGlobalKnownHostsFile, oUserKnownHostsFile, oConnectionAttempts,
144 	oBatchMode, oCheckHostIP, oStrictHostKeyChecking, oCompression,
145 	oCompressionLevel, oTCPKeepAlive, oNumberOfPasswordPrompts,
146 	oUsePrivilegedPort, oLogLevel, oCiphers, oProtocol, oMacs,
147 	oPubkeyAuthentication,
148 	oKbdInteractiveAuthentication, oKbdInteractiveDevices, oHostKeyAlias,
149 	oDynamicForward, oPreferredAuthentications, oHostbasedAuthentication,
150 	oHostKeyAlgorithms, oBindAddress, oPKCS11Provider,
151 	oClearAllForwardings, oNoHostAuthenticationForLocalhost,
152 	oEnableSSHKeysign, oRekeyLimit, oVerifyHostKeyDNS, oConnectTimeout,
153 	oAddressFamily, oGssAuthentication, oGssDelegateCreds,
154 	oServerAliveInterval, oServerAliveCountMax, oIdentitiesOnly,
155 	oSendEnv, oControlPath, oControlMaster, oControlPersist,
156 	oHashKnownHosts,
157 	oTunnel, oTunnelDevice, oLocalCommand, oPermitLocalCommand,
158 	oVisualHostKey,
159 	oKexAlgorithms, oIPQoS, oRequestTTY, oIgnoreUnknown, oProxyUseFdpass,
160 	oCanonicalDomains, oCanonicalizeHostname, oCanonicalizeMaxDots,
161 	oCanonicalizeFallbackLocal, oCanonicalizePermittedCNAMEs,
162 	oStreamLocalBindMask, oStreamLocalBindUnlink, oRevokedHostKeys,
163 	oFingerprintHash, oUpdateHostkeys, oHostbasedKeyTypes,
164 	oPubkeyAcceptedKeyTypes,
165 	oNoneEnabled, oTcpRcvBufPoll, oTcpRcvBuf, oNoneSwitch, oHPNDisabled,
166 	oHPNBufferSize,
167 	oSendVersionFirst,
168 	oIgnoredUnknownOption, oDeprecated, oUnsupported
169 } OpCodes;
170 
171 /* Textual representations of the tokens. */
172 
173 static struct {
174 	const char *name;
175 	OpCodes opcode;
176 } keywords[] = {
177 	{ "forwardagent", oForwardAgent },
178 	{ "forwardx11", oForwardX11 },
179 	{ "forwardx11trusted", oForwardX11Trusted },
180 	{ "forwardx11timeout", oForwardX11Timeout },
181 	{ "exitonforwardfailure", oExitOnForwardFailure },
182 	{ "xauthlocation", oXAuthLocation },
183 	{ "gatewayports", oGatewayPorts },
184 	{ "useprivilegedport", oUsePrivilegedPort },
185 	{ "rhostsauthentication", oDeprecated },
186 	{ "passwordauthentication", oPasswordAuthentication },
187 	{ "kbdinteractiveauthentication", oKbdInteractiveAuthentication },
188 	{ "kbdinteractivedevices", oKbdInteractiveDevices },
189 	{ "rsaauthentication", oRSAAuthentication },
190 	{ "pubkeyauthentication", oPubkeyAuthentication },
191 	{ "dsaauthentication", oPubkeyAuthentication },		    /* alias */
192 	{ "rhostsrsaauthentication", oRhostsRSAAuthentication },
193 	{ "hostbasedauthentication", oHostbasedAuthentication },
194 	{ "challengeresponseauthentication", oChallengeResponseAuthentication },
195 	{ "skeyauthentication", oChallengeResponseAuthentication }, /* alias */
196 	{ "tisauthentication", oChallengeResponseAuthentication },  /* alias */
197 #if defined(KRB4) || defined(KRB5)
198 	{ "kerberosauthentication", oKerberosAuthentication },
199 #endif
200 #if defined(AFS) || defined(KRB5)
201 	{ "kerberostgtpassing", oKerberosTgtPassing },
202 	{ "kerberos5tgtpassing", oKerberosTgtPassing },		/* alias */
203 	{ "kerberos4tgtpassing", oKerberosTgtPassing },		/* alias */
204 #endif
205 #ifdef AFS
206 	{ "afstokenpassing", oAFSTokenPassing },
207 #endif
208 #if defined(GSSAPI)
209 	{ "gssapiauthentication", oGssAuthentication },
210 	{ "gssapidelegatecredentials", oGssDelegateCreds },
211 #else
212 	{ "gssapiauthentication", oUnsupported },
213 	{ "gssapidelegatecredentials", oUnsupported },
214 #endif
215 	{ "fallbacktorsh", oDeprecated },
216 	{ "usersh", oDeprecated },
217 	{ "identityfile", oIdentityFile },
218 	{ "identityfile2", oIdentityFile },			/* obsolete */
219 	{ "identitiesonly", oIdentitiesOnly },
220 	{ "certificatefile", oCertificateFile },
221 	{ "addkeystoagent", oAddKeysToAgent },
222 	{ "hostname", oHostName },
223 	{ "hostkeyalias", oHostKeyAlias },
224 	{ "proxycommand", oProxyCommand },
225 	{ "port", oPort },
226 	{ "cipher", oCipher },
227 	{ "ciphers", oCiphers },
228 	{ "macs", oMacs },
229 	{ "protocol", oProtocol },
230 	{ "remoteforward", oRemoteForward },
231 	{ "localforward", oLocalForward },
232 	{ "user", oUser },
233 	{ "host", oHost },
234 	{ "match", oMatch },
235 	{ "escapechar", oEscapeChar },
236 	{ "globalknownhostsfile", oGlobalKnownHostsFile },
237 	{ "globalknownhostsfile2", oDeprecated },
238 	{ "userknownhostsfile", oUserKnownHostsFile },
239 	{ "userknownhostsfile2", oDeprecated },
240 	{ "connectionattempts", oConnectionAttempts },
241 	{ "batchmode", oBatchMode },
242 	{ "checkhostip", oCheckHostIP },
243 	{ "stricthostkeychecking", oStrictHostKeyChecking },
244 	{ "compression", oCompression },
245 	{ "compressionlevel", oCompressionLevel },
246 	{ "tcpkeepalive", oTCPKeepAlive },
247 	{ "keepalive", oTCPKeepAlive },				/* obsolete */
248 	{ "numberofpasswordprompts", oNumberOfPasswordPrompts },
249 	{ "loglevel", oLogLevel },
250 	{ "dynamicforward", oDynamicForward },
251 	{ "preferredauthentications", oPreferredAuthentications },
252 	{ "hostkeyalgorithms", oHostKeyAlgorithms },
253 	{ "bindaddress", oBindAddress },
254 #ifdef ENABLE_PKCS11
255 	{ "smartcarddevice", oPKCS11Provider },
256 	{ "pkcs11provider", oPKCS11Provider },
257 #else
258 	{ "smartcarddevice", oUnsupported },
259 	{ "pkcs11provider", oUnsupported },
260 #endif
261 	{ "clearallforwardings", oClearAllForwardings },
262 	{ "enablesshkeysign", oEnableSSHKeysign },
263 	{ "verifyhostkeydns", oVerifyHostKeyDNS },
264 	{ "nohostauthenticationforlocalhost", oNoHostAuthenticationForLocalhost },
265 	{ "rekeylimit", oRekeyLimit },
266 	{ "connecttimeout", oConnectTimeout },
267 	{ "addressfamily", oAddressFamily },
268 	{ "serveraliveinterval", oServerAliveInterval },
269 	{ "serveralivecountmax", oServerAliveCountMax },
270 	{ "sendenv", oSendEnv },
271 	{ "controlpath", oControlPath },
272 	{ "controlmaster", oControlMaster },
273 	{ "controlpersist", oControlPersist },
274 	{ "hashknownhosts", oHashKnownHosts },
275 	{ "tunnel", oTunnel },
276 	{ "tunneldevice", oTunnelDevice },
277 	{ "localcommand", oLocalCommand },
278 	{ "permitlocalcommand", oPermitLocalCommand },
279 	{ "visualhostkey", oVisualHostKey },
280 	{ "useroaming", oDeprecated },
281 	{ "kexalgorithms", oKexAlgorithms },
282 	{ "ipqos", oIPQoS },
283 	{ "requesttty", oRequestTTY },
284 	{ "proxyusefdpass", oProxyUseFdpass },
285 	{ "canonicaldomains", oCanonicalDomains },
286 	{ "canonicalizefallbacklocal", oCanonicalizeFallbackLocal },
287 	{ "canonicalizehostname", oCanonicalizeHostname },
288 	{ "canonicalizemaxdots", oCanonicalizeMaxDots },
289 	{ "canonicalizepermittedcnames", oCanonicalizePermittedCNAMEs },
290 	{ "streamlocalbindmask", oStreamLocalBindMask },
291 	{ "streamlocalbindunlink", oStreamLocalBindUnlink },
292 	{ "revokedhostkeys", oRevokedHostKeys },
293 	{ "fingerprinthash", oFingerprintHash },
294 	{ "updatehostkeys", oUpdateHostkeys },
295 	{ "hostbasedkeytypes", oHostbasedKeyTypes },
296 	{ "pubkeyacceptedkeytypes", oPubkeyAcceptedKeyTypes },
297 	{ "noneenabled", oNoneEnabled },
298 	{ "tcprcvbufpoll", oTcpRcvBufPoll },
299 	{ "tcprcvbuf", oTcpRcvBuf },
300 	{ "noneswitch", oNoneSwitch },
301 	{ "hpndisabled", oHPNDisabled },
302 	{ "hpnbuffersize", oHPNBufferSize },
303 	{ "sendversionfirst", oSendVersionFirst },
304 	{ "ignoreunknown", oIgnoreUnknown },
305 	{ NULL, oBadOption }
306 };
307 
308 /*
309  * Adds a local TCP/IP port forward to options.  Never returns if there is an
310  * error.
311  */
312 
313 void
314 add_local_forward(Options *options, const struct Forward *newfwd)
315 {
316 	struct Forward *fwd;
317 	extern uid_t original_real_uid;
318 
319 	if (newfwd->listen_port < IPPORT_RESERVED && original_real_uid != 0 &&
320 	    newfwd->listen_path == NULL)
321 		fatal("Privileged ports can only be forwarded by root.");
322 	options->local_forwards = xreallocarray(options->local_forwards,
323 	    options->num_local_forwards + 1,
324 	    sizeof(*options->local_forwards));
325 	fwd = &options->local_forwards[options->num_local_forwards++];
326 
327 	fwd->listen_host = newfwd->listen_host;
328 	fwd->listen_port = newfwd->listen_port;
329 	fwd->listen_path = newfwd->listen_path;
330 	fwd->connect_host = newfwd->connect_host;
331 	fwd->connect_port = newfwd->connect_port;
332 	fwd->connect_path = newfwd->connect_path;
333 }
334 
335 /*
336  * Adds a remote TCP/IP port forward to options.  Never returns if there is
337  * an error.
338  */
339 
340 void
341 add_remote_forward(Options *options, const struct Forward *newfwd)
342 {
343 	struct Forward *fwd;
344 
345 	options->remote_forwards = xreallocarray(options->remote_forwards,
346 	    options->num_remote_forwards + 1,
347 	    sizeof(*options->remote_forwards));
348 	fwd = &options->remote_forwards[options->num_remote_forwards++];
349 
350 	fwd->listen_host = newfwd->listen_host;
351 	fwd->listen_port = newfwd->listen_port;
352 	fwd->listen_path = newfwd->listen_path;
353 	fwd->connect_host = newfwd->connect_host;
354 	fwd->connect_port = newfwd->connect_port;
355 	fwd->connect_path = newfwd->connect_path;
356 	fwd->handle = newfwd->handle;
357 	fwd->allocated_port = 0;
358 }
359 
360 static void
361 clear_forwardings(Options *options)
362 {
363 	int i;
364 
365 	for (i = 0; i < options->num_local_forwards; i++) {
366 		free(options->local_forwards[i].listen_host);
367 		free(options->local_forwards[i].listen_path);
368 		free(options->local_forwards[i].connect_host);
369 		free(options->local_forwards[i].connect_path);
370 	}
371 	if (options->num_local_forwards > 0) {
372 		free(options->local_forwards);
373 		options->local_forwards = NULL;
374 	}
375 	options->num_local_forwards = 0;
376 	for (i = 0; i < options->num_remote_forwards; i++) {
377 		free(options->remote_forwards[i].listen_host);
378 		free(options->remote_forwards[i].listen_path);
379 		free(options->remote_forwards[i].connect_host);
380 		free(options->remote_forwards[i].connect_path);
381 	}
382 	if (options->num_remote_forwards > 0) {
383 		free(options->remote_forwards);
384 		options->remote_forwards = NULL;
385 	}
386 	options->num_remote_forwards = 0;
387 	options->tun_open = SSH_TUNMODE_NO;
388 }
389 
390 void
391 add_certificate_file(Options *options, const char *path, int userprovided)
392 {
393 	int i;
394 
395 	if (options->num_certificate_files >= SSH_MAX_CERTIFICATE_FILES)
396 		fatal("Too many certificate files specified (max %d)",
397 		    SSH_MAX_CERTIFICATE_FILES);
398 
399 	/* Avoid registering duplicates */
400 	for (i = 0; i < options->num_certificate_files; i++) {
401 		if (options->certificate_file_userprovided[i] == userprovided &&
402 		    strcmp(options->certificate_files[i], path) == 0) {
403 			debug2("%s: ignoring duplicate key %s", __func__, path);
404 			return;
405 		}
406 	}
407 
408 	options->certificate_file_userprovided[options->num_certificate_files] =
409 	    userprovided;
410 	options->certificate_files[options->num_certificate_files++] =
411 	    xstrdup(path);
412 }
413 
414 void
415 add_identity_file(Options *options, const char *dir, const char *filename,
416     int userprovided)
417 {
418 	char *path;
419 	int i;
420 
421 	if (options->num_identity_files >= SSH_MAX_IDENTITY_FILES)
422 		fatal("Too many identity files specified (max %d)",
423 		    SSH_MAX_IDENTITY_FILES);
424 
425 	if (dir == NULL) /* no dir, filename is absolute */
426 		path = xstrdup(filename);
427 	else
428 		(void)xasprintf(&path, "%.100s%.100s", dir, filename);
429 
430 	/* Avoid registering duplicates */
431 	for (i = 0; i < options->num_identity_files; i++) {
432 		if (options->identity_file_userprovided[i] == userprovided &&
433 		    strcmp(options->identity_files[i], path) == 0) {
434 			debug2("%s: ignoring duplicate key %s", __func__, path);
435 			free(path);
436 			return;
437 		}
438 	}
439 
440 	options->identity_file_userprovided[options->num_identity_files] =
441 	    userprovided;
442 	options->identity_files[options->num_identity_files++] = path;
443 }
444 
445 int
446 default_ssh_port(void)
447 {
448 	static int port;
449 	struct servent *sp;
450 
451 	if (port == 0) {
452 		sp = getservbyname(SSH_SERVICE_NAME, "tcp");
453 		port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
454 	}
455 	return port;
456 }
457 
458 /*
459  * Execute a command in a shell.
460  * Return its exit status or -1 on abnormal exit.
461  */
462 static int
463 execute_in_shell(const char *cmd)
464 {
465 	const char *shell;
466 	pid_t pid;
467 	int devnull, status;
468 	extern uid_t original_real_uid;
469 
470 	if ((shell = getenv("SHELL")) == NULL)
471 		shell = _PATH_BSHELL;
472 
473 	/* Need this to redirect subprocess stdin/out */
474 	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1)
475 		fatal("open(/dev/null): %s", strerror(errno));
476 
477 	debug("Executing command: '%.500s'", cmd);
478 
479 	/* Fork and execute the command. */
480 	if ((pid = fork()) == 0) {
481 		char *argv[4];
482 
483 		/* Child.  Permanently give up superuser privileges. */
484 		permanently_drop_suid(original_real_uid);
485 
486 		/* Redirect child stdin and stdout. Leave stderr */
487 		if (dup2(devnull, STDIN_FILENO) == -1)
488 			fatal("dup2: %s", strerror(errno));
489 		if (dup2(devnull, STDOUT_FILENO) == -1)
490 			fatal("dup2: %s", strerror(errno));
491 		if (devnull > STDERR_FILENO)
492 			close(devnull);
493 		if (closefrom(STDERR_FILENO + 1) == -1)
494 			fatal("closefrom: %s", strerror(errno));
495 
496 		argv[0] = __UNCONST(shell);
497 		argv[1] = __UNCONST("-c");
498 		argv[2] = xstrdup(cmd);
499 		argv[3] = NULL;
500 
501 		execv(argv[0], argv);
502 		error("Unable to execute '%.100s': %s", cmd, strerror(errno));
503 		/* Die with signal to make this error apparent to parent. */
504 		signal(SIGTERM, SIG_DFL);
505 		kill(getpid(), SIGTERM);
506 		_exit(1);
507 	}
508 	/* Parent. */
509 	if (pid < 0)
510 		fatal("%s: fork: %.100s", __func__, strerror(errno));
511 
512 	close(devnull);
513 
514 	while (waitpid(pid, &status, 0) == -1) {
515 		if (errno != EINTR && errno != EAGAIN)
516 			fatal("%s: waitpid: %s", __func__, strerror(errno));
517 	}
518 	if (!WIFEXITED(status)) {
519 		error("command '%.100s' exited abnormally", cmd);
520 		return -1;
521 	}
522 	debug3("command returned status %d", WEXITSTATUS(status));
523 	return WEXITSTATUS(status);
524 }
525 
526 /*
527  * Parse and execute a Match directive.
528  */
529 static int
530 match_cfg_line(Options *options, char **condition, struct passwd *pw,
531     const char *host_arg, const char *original_host, int post_canon,
532     const char *filename, int linenum)
533 {
534 	char *arg, *oattrib, *attrib, *cmd, *cp = *condition, *host, *criteria;
535 	const char *ruser;
536 	int r, port, this_result, result = 1, attributes = 0, negate;
537 	char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
538 
539 	/*
540 	 * Configuration is likely to be incomplete at this point so we
541 	 * must be prepared to use default values.
542 	 */
543 	port = options->port <= 0 ? default_ssh_port() : options->port;
544 	ruser = options->user == NULL ? pw->pw_name : options->user;
545 	if (post_canon) {
546 		host = xstrdup(options->hostname);
547 	} else if (options->hostname != NULL) {
548 		/* NB. Please keep in sync with ssh.c:main() */
549 		host = percent_expand(options->hostname,
550 		    "h", host_arg, (char *)NULL);
551 	} else {
552 		host = xstrdup(host_arg);
553 	}
554 
555 	debug2("checking match for '%s' host %s originally %s",
556 	    cp, host, original_host);
557 	while ((oattrib = attrib = strdelim(&cp)) && *attrib != '\0') {
558 		criteria = NULL;
559 		this_result = 1;
560 		if ((negate = attrib[0] == '!'))
561 			attrib++;
562 		/* criteria "all" and "canonical" have no argument */
563 		if (strcasecmp(attrib, "all") == 0) {
564 			if (attributes > 1 ||
565 			    ((arg = strdelim(&cp)) != NULL && *arg != '\0')) {
566 				error("%.200s line %d: '%s' cannot be combined "
567 				    "with other Match attributes",
568 				    filename, linenum, oattrib);
569 				result = -1;
570 				goto out;
571 			}
572 			if (result)
573 				result = negate ? 0 : 1;
574 			goto out;
575 		}
576 		attributes++;
577 		if (strcasecmp(attrib, "canonical") == 0) {
578 			r = !!post_canon;  /* force bitmask member to boolean */
579 			if (r == (negate ? 1 : 0))
580 				this_result = result = 0;
581 			debug3("%.200s line %d: %smatched '%s'",
582 			    filename, linenum,
583 			    this_result ? "" : "not ", oattrib);
584 			continue;
585 		}
586 		/* All other criteria require an argument */
587 		if ((arg = strdelim(&cp)) == NULL || *arg == '\0') {
588 			error("Missing Match criteria for %s", attrib);
589 			result = -1;
590 			goto out;
591 		}
592 		if (strcasecmp(attrib, "host") == 0) {
593 			criteria = xstrdup(host);
594 			r = match_hostname(host, arg) == 1;
595 			if (r == (negate ? 1 : 0))
596 				this_result = result = 0;
597 		} else if (strcasecmp(attrib, "originalhost") == 0) {
598 			criteria = xstrdup(original_host);
599 			r = match_hostname(original_host, arg) == 1;
600 			if (r == (negate ? 1 : 0))
601 				this_result = result = 0;
602 		} else if (strcasecmp(attrib, "user") == 0) {
603 			criteria = xstrdup(ruser);
604 			r = match_pattern_list(ruser, arg, 0) == 1;
605 			if (r == (negate ? 1 : 0))
606 				this_result = result = 0;
607 		} else if (strcasecmp(attrib, "localuser") == 0) {
608 			criteria = xstrdup(pw->pw_name);
609 			r = match_pattern_list(pw->pw_name, arg, 0) == 1;
610 			if (r == (negate ? 1 : 0))
611 				this_result = result = 0;
612 		} else if (strcasecmp(attrib, "exec") == 0) {
613 			if (gethostname(thishost, sizeof(thishost)) == -1)
614 				fatal("gethostname: %s", strerror(errno));
615 			strlcpy(shorthost, thishost, sizeof(shorthost));
616 			shorthost[strcspn(thishost, ".")] = '\0';
617 			snprintf(portstr, sizeof(portstr), "%d", port);
618 
619 			cmd = percent_expand(arg,
620 			    "L", shorthost,
621 			    "d", pw->pw_dir,
622 			    "h", host,
623 			    "l", thishost,
624 			    "n", original_host,
625 			    "p", portstr,
626 			    "r", ruser,
627 			    "u", pw->pw_name,
628 			    (char *)NULL);
629 			if (result != 1) {
630 				/* skip execution if prior predicate failed */
631 				debug3("%.200s line %d: skipped exec "
632 				    "\"%.100s\"", filename, linenum, cmd);
633 				free(cmd);
634 				continue;
635 			}
636 			r = execute_in_shell(cmd);
637 			if (r == -1) {
638 				fatal("%.200s line %d: match exec "
639 				    "'%.100s' error", filename,
640 				    linenum, cmd);
641 			}
642 			criteria = xstrdup(cmd);
643 			free(cmd);
644 			/* Force exit status to boolean */
645 			r = r == 0;
646 			if (r == (negate ? 1 : 0))
647 				this_result = result = 0;
648 		} else {
649 			error("Unsupported Match attribute %s", attrib);
650 			result = -1;
651 			goto out;
652 		}
653 		debug3("%.200s line %d: %smatched '%s \"%.100s\"' ",
654 		    filename, linenum, this_result ? "": "not ",
655 		    oattrib, criteria);
656 		free(criteria);
657 	}
658 	if (attributes == 0) {
659 		error("One or more attributes required for Match");
660 		result = -1;
661 		goto out;
662 	}
663  out:
664 	if (result != -1)
665 		debug2("match %sfound", result ? "" : "not ");
666 	*condition = cp;
667 	free(host);
668 	return result;
669 }
670 
671 /* Check and prepare a domain name: removes trailing '.' and lowercases */
672 static void
673 valid_domain(char *name, const char *filename, int linenum)
674 {
675 	size_t i, l = strlen(name);
676 	u_char c, last = '\0';
677 
678 	if (l == 0)
679 		fatal("%s line %d: empty hostname suffix", filename, linenum);
680 	if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0]))
681 		fatal("%s line %d: hostname suffix \"%.100s\" "
682 		    "starts with invalid character", filename, linenum, name);
683 	for (i = 0; i < l; i++) {
684 		c = tolower((u_char)name[i]);
685 		name[i] = (char)c;
686 		if (last == '.' && c == '.')
687 			fatal("%s line %d: hostname suffix \"%.100s\" contains "
688 			    "consecutive separators", filename, linenum, name);
689 		if (c != '.' && c != '-' && !isalnum(c) &&
690 		    c != '_') /* technically invalid, but common */
691 			fatal("%s line %d: hostname suffix \"%.100s\" contains "
692 			    "invalid characters", filename, linenum, name);
693 		last = c;
694 	}
695 	if (name[l - 1] == '.')
696 		name[l - 1] = '\0';
697 }
698 
699 /*
700  * Returns the number of the token pointed to by cp or oBadOption.
701  */
702 static OpCodes
703 parse_token(const char *cp, const char *filename, int linenum,
704     const char *ignored_unknown)
705 {
706 	int i;
707 
708 	for (i = 0; keywords[i].name; i++)
709 		if (strcmp(cp, keywords[i].name) == 0)
710 			return keywords[i].opcode;
711 	if (ignored_unknown != NULL &&
712 	    match_pattern_list(cp, ignored_unknown, 1) == 1)
713 		return oIgnoredUnknownOption;
714 	error("%s: line %d: Bad configuration option: %s",
715 	    filename, linenum, cp);
716 	return oBadOption;
717 }
718 
719 /* Multistate option parsing */
720 struct multistate {
721 	const char *key;
722 	int value;
723 };
724 static const struct multistate multistate_flag[] = {
725 	{ "true",			1 },
726 	{ "false",			0 },
727 	{ "yes",			1 },
728 	{ "no",				0 },
729 	{ NULL, -1 }
730 };
731 static const struct multistate multistate_yesnoask[] = {
732 	{ "true",			1 },
733 	{ "false",			0 },
734 	{ "yes",			1 },
735 	{ "no",				0 },
736 	{ "ask",			2 },
737 	{ NULL, -1 }
738 };
739 static const struct multistate multistate_yesnoaskconfirm[] = {
740 	{ "true",			1 },
741 	{ "false",			0 },
742 	{ "yes",			1 },
743 	{ "no",				0 },
744 	{ "ask",			2 },
745 	{ "confirm",			3 },
746 	{ NULL, -1 }
747 };
748 static const struct multistate multistate_addressfamily[] = {
749 	{ "inet",			AF_INET },
750 	{ "inet6",			AF_INET6 },
751 	{ "any",			AF_UNSPEC },
752 	{ NULL, -1 }
753 };
754 static const struct multistate multistate_controlmaster[] = {
755 	{ "true",			SSHCTL_MASTER_YES },
756 	{ "yes",			SSHCTL_MASTER_YES },
757 	{ "false",			SSHCTL_MASTER_NO },
758 	{ "no",				SSHCTL_MASTER_NO },
759 	{ "auto",			SSHCTL_MASTER_AUTO },
760 	{ "ask",			SSHCTL_MASTER_ASK },
761 	{ "autoask",			SSHCTL_MASTER_AUTO_ASK },
762 	{ NULL, -1 }
763 };
764 static const struct multistate multistate_tunnel[] = {
765 	{ "ethernet",			SSH_TUNMODE_ETHERNET },
766 	{ "point-to-point",		SSH_TUNMODE_POINTOPOINT },
767 	{ "true",			SSH_TUNMODE_DEFAULT },
768 	{ "yes",			SSH_TUNMODE_DEFAULT },
769 	{ "false",			SSH_TUNMODE_NO },
770 	{ "no",				SSH_TUNMODE_NO },
771 	{ NULL, -1 }
772 };
773 static const struct multistate multistate_requesttty[] = {
774 	{ "true",			REQUEST_TTY_YES },
775 	{ "yes",			REQUEST_TTY_YES },
776 	{ "false",			REQUEST_TTY_NO },
777 	{ "no",				REQUEST_TTY_NO },
778 	{ "force",			REQUEST_TTY_FORCE },
779 	{ "auto",			REQUEST_TTY_AUTO },
780 	{ NULL, -1 }
781 };
782 static const struct multistate multistate_canonicalizehostname[] = {
783 	{ "true",			SSH_CANONICALISE_YES },
784 	{ "false",			SSH_CANONICALISE_NO },
785 	{ "yes",			SSH_CANONICALISE_YES },
786 	{ "no",				SSH_CANONICALISE_NO },
787 	{ "always",			SSH_CANONICALISE_ALWAYS },
788 	{ NULL, -1 }
789 };
790 
791 /*
792  * Processes a single option line as used in the configuration files. This
793  * only sets those values that have not already been set.
794  */
795 #define WHITESPACE " \t\r\n"
796 int
797 process_config_line(Options *options, struct passwd *pw, const char *host,
798     const char *original_host, char *line, const char *filename,
799     int linenum, int *activep, int flags)
800 {
801 	char *s, **charptr, *endofnumber, *keyword, *arg, *arg2;
802 	char **cpptr, fwdarg[256];
803 	u_int i, *uintptr, max_entries = 0;
804 	int negated, opcode, *intptr, value, value2, cmdline = 0;
805 	LogLevel *log_level_ptr;
806 	long long val64;
807 	size_t len;
808 	struct Forward fwd;
809 	const struct multistate *multistate_ptr;
810 	struct allowed_cname *cname;
811 
812 	if (activep == NULL) { /* We are processing a command line directive */
813 		cmdline = 1;
814 		activep = &cmdline;
815 	}
816 
817 	/* Strip trailing whitespace */
818 	if ((len = strlen(line)) == 0)
819 		return 0;
820 	for (len--; len > 0; len--) {
821 		if (strchr(WHITESPACE, line[len]) == NULL)
822 			break;
823 		line[len] = '\0';
824 	}
825 
826 	s = line;
827 	/* Get the keyword. (Each line is supposed to begin with a keyword). */
828 	if ((keyword = strdelim(&s)) == NULL)
829 		return 0;
830 	/* Ignore leading whitespace. */
831 	if (*keyword == '\0')
832 		keyword = strdelim(&s);
833 	if (keyword == NULL || !*keyword || *keyword == '\n' || *keyword == '#')
834 		return 0;
835 	/* Match lowercase keyword */
836 	lowercase(keyword);
837 
838 	opcode = parse_token(keyword, filename, linenum,
839 	    options->ignored_unknown);
840 
841 	switch (opcode) {
842 	case oBadOption:
843 		/* don't panic, but count bad options */
844 		return -1;
845 		/* NOTREACHED */
846 	case oIgnoredUnknownOption:
847 		debug("%s line %d: Ignored unknown option \"%s\"",
848 		    filename, linenum, keyword);
849 		return 0;
850 	case oConnectTimeout:
851 		intptr = &options->connection_timeout;
852 parse_time:
853 		arg = strdelim(&s);
854 		if (!arg || *arg == '\0')
855 			fatal("%s line %d: missing time value.",
856 			    filename, linenum);
857 		if (strcmp(arg, "none") == 0)
858 			value = -1;
859 		else if ((value = convtime(arg)) == -1)
860 			fatal("%s line %d: invalid time value.",
861 			    filename, linenum);
862 		if (*activep && *intptr == -1)
863 			*intptr = value;
864 		break;
865 
866 	case oForwardAgent:
867 		intptr = &options->forward_agent;
868  parse_flag:
869 		multistate_ptr = multistate_flag;
870  parse_multistate:
871 		arg = strdelim(&s);
872 		if (!arg || *arg == '\0')
873 			fatal("%s line %d: missing argument.",
874 			    filename, linenum);
875 		value = -1;
876 		for (i = 0; multistate_ptr[i].key != NULL; i++) {
877 			if (strcasecmp(arg, multistate_ptr[i].key) == 0) {
878 				value = multistate_ptr[i].value;
879 				break;
880 			}
881 		}
882 		if (value == -1)
883 			fatal("%s line %d: unsupported option \"%s\".",
884 			    filename, linenum, arg);
885 		if (*activep && *intptr == -1)
886 			*intptr = value;
887 		break;
888 
889 	case oForwardX11:
890 		intptr = &options->forward_x11;
891 		goto parse_flag;
892 
893 	case oForwardX11Trusted:
894 		intptr = &options->forward_x11_trusted;
895 		goto parse_flag;
896 
897 	case oForwardX11Timeout:
898 		intptr = &options->forward_x11_timeout;
899 		goto parse_time;
900 
901 	case oGatewayPorts:
902 		intptr = &options->fwd_opts.gateway_ports;
903 		goto parse_flag;
904 
905 	case oExitOnForwardFailure:
906 		intptr = &options->exit_on_forward_failure;
907 		goto parse_flag;
908 
909 	case oUsePrivilegedPort:
910 		intptr = &options->use_privileged_port;
911 		goto parse_flag;
912 
913 	case oPasswordAuthentication:
914 		intptr = &options->password_authentication;
915 		goto parse_flag;
916 
917 	case oKbdInteractiveAuthentication:
918 		intptr = &options->kbd_interactive_authentication;
919 		goto parse_flag;
920 
921 	case oKbdInteractiveDevices:
922 		charptr = &options->kbd_interactive_devices;
923 		goto parse_string;
924 
925 	case oPubkeyAuthentication:
926 		intptr = &options->pubkey_authentication;
927 		goto parse_flag;
928 
929 	case oRSAAuthentication:
930 		intptr = &options->rsa_authentication;
931 		goto parse_flag;
932 
933 	case oRhostsRSAAuthentication:
934 		intptr = &options->rhosts_rsa_authentication;
935 		goto parse_flag;
936 
937 	case oHostbasedAuthentication:
938 		intptr = &options->hostbased_authentication;
939 		goto parse_flag;
940 
941 	case oChallengeResponseAuthentication:
942 		intptr = &options->challenge_response_authentication;
943 		goto parse_flag;
944 
945 #if defined(KRB4) || defined(KRB5)
946 	case oKerberosAuthentication:
947 		intptr = &options->kerberos_authentication;
948 		goto parse_flag;
949 #endif
950 #if defined(AFS) || defined(KRB5)
951 	case oKerberosTgtPassing:
952 		intptr = &options->kerberos_tgt_passing;
953 		goto parse_flag;
954 #endif
955 
956 	case oGssAuthentication:
957 		intptr = &options->gss_authentication;
958 		goto parse_flag;
959 
960 #ifdef AFS
961 	case oAFSTokenPassing:
962 		intptr = &options->afs_token_passing;
963  		goto parse_flag;
964 #endif
965 
966 	case oGssDelegateCreds:
967 		intptr = &options->gss_deleg_creds;
968 		goto parse_flag;
969 
970 	case oBatchMode:
971 		intptr = &options->batch_mode;
972 		goto parse_flag;
973 
974 	case oCheckHostIP:
975 		intptr = &options->check_host_ip;
976 		goto parse_flag;
977 
978 	case oNoneEnabled:
979 		intptr = &options->none_enabled;
980 		goto parse_flag;
981 
982 	/* we check to see if the command comes from the */
983 	/* command line or not. If it does then enable it */
984 	/* otherwise fail. NONE should never be a default configuration */
985 	case oNoneSwitch:
986 		if(strcmp(filename,"command-line")==0)
987 		{
988 		    intptr = &options->none_switch;
989 		    goto parse_flag;
990 		} else {
991 		    error("NoneSwitch is found in %.200s.\nYou may only use this configuration option from the command line", filename);
992 		    error("Continuing...");
993 		    debug("NoneSwitch directive found in %.200s.", filename);
994 		    return 0;
995 	        }
996 
997 	case oHPNDisabled:
998 		intptr = &options->hpn_disabled;
999 		goto parse_flag;
1000 
1001 	case oHPNBufferSize:
1002 		intptr = &options->hpn_buffer_size;
1003 		goto parse_int;
1004 
1005 	case oTcpRcvBufPoll:
1006 		intptr = &options->tcp_rcv_buf_poll;
1007 		goto parse_flag;
1008 
1009 	case oVerifyHostKeyDNS:
1010 		intptr = &options->verify_host_key_dns;
1011 		multistate_ptr = multistate_yesnoask;
1012 		goto parse_multistate;
1013 
1014 	case oStrictHostKeyChecking:
1015 		intptr = &options->strict_host_key_checking;
1016 		multistate_ptr = multistate_yesnoask;
1017 		goto parse_multistate;
1018 
1019 	case oCompression:
1020 		intptr = &options->compression;
1021 		goto parse_flag;
1022 
1023 	case oTCPKeepAlive:
1024 		intptr = &options->tcp_keep_alive;
1025 		goto parse_flag;
1026 
1027 	case oNoHostAuthenticationForLocalhost:
1028 		intptr = &options->no_host_authentication_for_localhost;
1029 		goto parse_flag;
1030 
1031 	case oNumberOfPasswordPrompts:
1032 		intptr = &options->number_of_password_prompts;
1033 		goto parse_int;
1034 
1035 	case oCompressionLevel:
1036 		intptr = &options->compression_level;
1037 		goto parse_int;
1038 
1039 	case oRekeyLimit:
1040 		arg = strdelim(&s);
1041 		if (!arg || *arg == '\0')
1042 			fatal("%.200s line %d: Missing argument.", filename,
1043 			    linenum);
1044 		if (strcmp(arg, "default") == 0) {
1045 			val64 = 0;
1046 		} else {
1047 			if (scan_scaled(arg, &val64) == -1)
1048 				fatal("%.200s line %d: Bad number '%s': %s",
1049 				    filename, linenum, arg, strerror(errno));
1050 			if (val64 != 0 && val64 < 16)
1051 				fatal("%.200s line %d: RekeyLimit too small",
1052 				    filename, linenum);
1053 		}
1054 		if (*activep && options->rekey_limit == -1)
1055 			options->rekey_limit = val64;
1056 		if (s != NULL) { /* optional rekey interval present */
1057 			if (strcmp(s, "none") == 0) {
1058 				(void)strdelim(&s);	/* discard */
1059 				break;
1060 			}
1061 			intptr = &options->rekey_interval;
1062 			goto parse_time;
1063 		}
1064 		break;
1065 
1066 	case oIdentityFile:
1067 		arg = strdelim(&s);
1068 		if (!arg || *arg == '\0')
1069 			fatal("%.200s line %d: Missing argument.", filename, linenum);
1070 		if (*activep) {
1071 			intptr = &options->num_identity_files;
1072 			if (*intptr >= SSH_MAX_IDENTITY_FILES)
1073 				fatal("%.200s line %d: Too many identity files specified (max %d).",
1074 				    filename, linenum, SSH_MAX_IDENTITY_FILES);
1075 			add_identity_file(options, NULL,
1076 			    arg, flags & SSHCONF_USERCONF);
1077 		}
1078 		break;
1079 
1080 	case oCertificateFile:
1081 		arg = strdelim(&s);
1082 		if (!arg || *arg == '\0')
1083 			fatal("%.200s line %d: Missing argument.",
1084 			    filename, linenum);
1085 		if (*activep) {
1086 			intptr = &options->num_certificate_files;
1087 			if (*intptr >= SSH_MAX_CERTIFICATE_FILES) {
1088 				fatal("%.200s line %d: Too many certificate "
1089 				    "files specified (max %d).",
1090 				    filename, linenum,
1091 				    SSH_MAX_CERTIFICATE_FILES);
1092 			}
1093 			add_certificate_file(options, arg,
1094 			    flags & SSHCONF_USERCONF);
1095 		}
1096 		break;
1097 
1098 	case oXAuthLocation:
1099 		charptr=&options->xauth_location;
1100 		goto parse_string;
1101 
1102 	case oUser:
1103 		charptr = &options->user;
1104 parse_string:
1105 		arg = strdelim(&s);
1106 		if (!arg || *arg == '\0')
1107 			fatal("%.200s line %d: Missing argument.",
1108 			    filename, linenum);
1109 		if (*activep && *charptr == NULL)
1110 			*charptr = xstrdup(arg);
1111 		break;
1112 
1113 	case oGlobalKnownHostsFile:
1114 		cpptr = (char **)&options->system_hostfiles;
1115 		uintptr = &options->num_system_hostfiles;
1116 		max_entries = SSH_MAX_HOSTS_FILES;
1117 parse_char_array:
1118 		if (*activep && *uintptr == 0) {
1119 			while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
1120 				if ((*uintptr) >= max_entries)
1121 					fatal("%s line %d: "
1122 					    "too many authorized keys files.",
1123 					    filename, linenum);
1124 				cpptr[(*uintptr)++] = xstrdup(arg);
1125 			}
1126 		}
1127 		return 0;
1128 
1129 	case oUserKnownHostsFile:
1130 		cpptr = (char **)&options->user_hostfiles;
1131 		uintptr = &options->num_user_hostfiles;
1132 		max_entries = SSH_MAX_HOSTS_FILES;
1133 		goto parse_char_array;
1134 
1135 	case oHostName:
1136 		charptr = &options->hostname;
1137 		goto parse_string;
1138 
1139 	case oHostKeyAlias:
1140 		charptr = &options->host_key_alias;
1141 		goto parse_string;
1142 
1143 	case oPreferredAuthentications:
1144 		charptr = &options->preferred_authentications;
1145 		goto parse_string;
1146 
1147 	case oBindAddress:
1148 		charptr = &options->bind_address;
1149 		goto parse_string;
1150 
1151 	case oPKCS11Provider:
1152 		charptr = &options->pkcs11_provider;
1153 		goto parse_string;
1154 
1155 	case oProxyCommand:
1156 		charptr = &options->proxy_command;
1157 parse_command:
1158 		if (s == NULL)
1159 			fatal("%.200s line %d: Missing argument.", filename, linenum);
1160 		len = strspn(s, WHITESPACE "=");
1161 		if (*activep && *charptr == NULL)
1162 			*charptr = xstrdup(s + len);
1163 		return 0;
1164 
1165 	case oPort:
1166 		intptr = &options->port;
1167 parse_int:
1168 		arg = strdelim(&s);
1169 		if (!arg || *arg == '\0')
1170 			fatal("%.200s line %d: Missing argument.", filename, linenum);
1171 		if (arg[0] < '0' || arg[0] > '9')
1172 			fatal("%.200s line %d: Bad number.", filename, linenum);
1173 
1174 		/* Octal, decimal, or hex format? */
1175 		value = strtol(arg, &endofnumber, 0);
1176 		if (arg == endofnumber)
1177 			fatal("%.200s line %d: Bad number.", filename, linenum);
1178 		if (*activep && *intptr == -1)
1179 			*intptr = value;
1180 		break;
1181 
1182 	case oConnectionAttempts:
1183 		intptr = &options->connection_attempts;
1184 		goto parse_int;
1185 
1186 	case oTcpRcvBuf:
1187 		intptr = &options->tcp_rcv_buf;
1188 		goto parse_int;
1189 
1190 	case oCipher:
1191 		intptr = &options->cipher;
1192 		arg = strdelim(&s);
1193 		if (!arg || *arg == '\0')
1194 			fatal("%.200s line %d: Missing argument.", filename, linenum);
1195 		value = cipher_number(arg);
1196 		if (value == -1)
1197 			fatal("%.200s line %d: Bad cipher '%s'.",
1198 			    filename, linenum, arg ? arg : "<NONE>");
1199 		if (*activep && *intptr == -1)
1200 			*intptr = value;
1201 		break;
1202 
1203 	case oCiphers:
1204 		arg = strdelim(&s);
1205 		if (!arg || *arg == '\0')
1206 			fatal("%.200s line %d: Missing argument.", filename, linenum);
1207 		if (!ciphers_valid(*arg == '+' ? arg + 1 : arg))
1208 			fatal("%.200s line %d: Bad SSH2 cipher spec '%s'.",
1209 			    filename, linenum, arg ? arg : "<NONE>");
1210 		if (*activep && options->ciphers == NULL)
1211 			options->ciphers = xstrdup(arg);
1212 		break;
1213 
1214 	case oMacs:
1215 		arg = strdelim(&s);
1216 		if (!arg || *arg == '\0')
1217 			fatal("%.200s line %d: Missing argument.", filename, linenum);
1218 		if (!mac_valid(*arg == '+' ? arg + 1 : arg))
1219 			fatal("%.200s line %d: Bad SSH2 Mac spec '%s'.",
1220 			    filename, linenum, arg ? arg : "<NONE>");
1221 		if (*activep && options->macs == NULL)
1222 			options->macs = xstrdup(arg);
1223 		break;
1224 
1225 	case oKexAlgorithms:
1226 		arg = strdelim(&s);
1227 		if (!arg || *arg == '\0')
1228 			fatal("%.200s line %d: Missing argument.",
1229 			    filename, linenum);
1230 		if (!kex_names_valid(*arg == '+' ? arg + 1 : arg))
1231 			fatal("%.200s line %d: Bad SSH2 KexAlgorithms '%s'.",
1232 			    filename, linenum, arg ? arg : "<NONE>");
1233 		if (*activep && options->kex_algorithms == NULL)
1234 			options->kex_algorithms = xstrdup(arg);
1235 		break;
1236 
1237 	case oHostKeyAlgorithms:
1238 		charptr = &options->hostkeyalgorithms;
1239 parse_keytypes:
1240 		arg = strdelim(&s);
1241 		if (!arg || *arg == '\0')
1242 			fatal("%.200s line %d: Missing argument.",
1243 			    filename, linenum);
1244 		if (!sshkey_names_valid2(*arg == '+' ? arg + 1 : arg, 1))
1245 			fatal("%s line %d: Bad key types '%s'.",
1246 				filename, linenum, arg ? arg : "<NONE>");
1247 		if (*activep && *charptr == NULL)
1248 			*charptr = xstrdup(arg);
1249 		break;
1250 
1251 	case oProtocol:
1252 		intptr = &options->protocol;
1253 		arg = strdelim(&s);
1254 		if (!arg || *arg == '\0')
1255 			fatal("%.200s line %d: Missing argument.", filename, linenum);
1256 		value = proto_spec(arg);
1257 		if (value == SSH_PROTO_UNKNOWN)
1258 			fatal("%.200s line %d: Bad protocol spec '%s'.",
1259 			    filename, linenum, arg ? arg : "<NONE>");
1260 		if (*activep && *intptr == SSH_PROTO_UNKNOWN)
1261 			*intptr = value;
1262 		break;
1263 
1264 	case oLogLevel:
1265 		log_level_ptr = &options->log_level;
1266 		arg = strdelim(&s);
1267 		value = log_level_number(arg);
1268 		if (value == SYSLOG_LEVEL_NOT_SET)
1269 			fatal("%.200s line %d: unsupported log level '%s'",
1270 			    filename, linenum, arg ? arg : "<NONE>");
1271 		if (*activep && *log_level_ptr == SYSLOG_LEVEL_NOT_SET)
1272 			*log_level_ptr = (LogLevel) value;
1273 		break;
1274 
1275 	case oLocalForward:
1276 	case oRemoteForward:
1277 	case oDynamicForward:
1278 		arg = strdelim(&s);
1279 		if (arg == NULL || *arg == '\0')
1280 			fatal("%.200s line %d: Missing port argument.",
1281 			    filename, linenum);
1282 
1283 		if (opcode == oLocalForward ||
1284 		    opcode == oRemoteForward) {
1285 			arg2 = strdelim(&s);
1286 			if (arg2 == NULL || *arg2 == '\0')
1287 				fatal("%.200s line %d: Missing target argument.",
1288 				    filename, linenum);
1289 
1290 			/* construct a string for parse_forward */
1291 			snprintf(fwdarg, sizeof(fwdarg), "%s:%s", arg, arg2);
1292 		} else if (opcode == oDynamicForward) {
1293 			strlcpy(fwdarg, arg, sizeof(fwdarg));
1294 		}
1295 
1296 		if (parse_forward(&fwd, fwdarg,
1297 		    opcode == oDynamicForward ? 1 : 0,
1298 		    opcode == oRemoteForward ? 1 : 0) == 0)
1299 			fatal("%.200s line %d: Bad forwarding specification.",
1300 			    filename, linenum);
1301 
1302 		if (*activep) {
1303 			if (opcode == oLocalForward ||
1304 			    opcode == oDynamicForward)
1305 				add_local_forward(options, &fwd);
1306 			else if (opcode == oRemoteForward)
1307 				add_remote_forward(options, &fwd);
1308 		}
1309 		break;
1310 
1311 	case oClearAllForwardings:
1312 		intptr = &options->clear_forwardings;
1313 		goto parse_flag;
1314 
1315 	case oHost:
1316 		if (cmdline)
1317 			fatal("Host directive not supported as a command-line "
1318 			    "option");
1319 		*activep = 0;
1320 		arg2 = NULL;
1321 		while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
1322 			negated = *arg == '!';
1323 			if (negated)
1324 				arg++;
1325 			if (match_pattern(host, arg)) {
1326 				if (negated) {
1327 					debug("%.200s line %d: Skipping Host "
1328 					    "block because of negated match "
1329 					    "for %.100s", filename, linenum,
1330 					    arg);
1331 					*activep = 0;
1332 					break;
1333 				}
1334 				if (!*activep)
1335 					arg2 = arg; /* logged below */
1336 				*activep = 1;
1337 			}
1338 		}
1339 		if (*activep)
1340 			debug("%.200s line %d: Applying options for %.100s",
1341 			    filename, linenum, arg2);
1342 		/* Avoid garbage check below, as strdelim is done. */
1343 		return 0;
1344 
1345 	case oMatch:
1346 		if (cmdline)
1347 			fatal("Host directive not supported as a command-line "
1348 			    "option");
1349 		value = match_cfg_line(options, &s, pw, host, original_host,
1350 		    flags & SSHCONF_POSTCANON, filename, linenum);
1351 		if (value < 0)
1352 			fatal("%.200s line %d: Bad Match condition", filename,
1353 			    linenum);
1354 		*activep = value;
1355 		break;
1356 
1357 	case oEscapeChar:
1358 		intptr = &options->escape_char;
1359 		arg = strdelim(&s);
1360 		if (!arg || *arg == '\0')
1361 			fatal("%.200s line %d: Missing argument.", filename, linenum);
1362 		value = 0;	/* To avoid compiler warning... */
1363 		if (strcmp(arg, "none") == 0)
1364 			value = SSH_ESCAPECHAR_NONE;
1365 		else if (arg[1] == '\0')
1366 			value = (u_char) arg[0];
1367 		else if (arg[0] == '^' && arg[2] == 0 &&
1368 		    (u_char) arg[1] >= 64 && (u_char) arg[1] < 128)
1369 			value = (u_char) arg[1] & 31;
1370 		else {
1371 			fatal("%.200s line %d: Bad escape character.",
1372 			    filename, linenum);
1373 			/* NOTREACHED */
1374 			value = 0;	/* Avoid compiler warning. */
1375 		}
1376 		if (*activep && *intptr == -1)
1377 			*intptr = value;
1378 		break;
1379 
1380 	case oAddressFamily:
1381 		intptr = &options->address_family;
1382 		multistate_ptr = multistate_addressfamily;
1383 		goto parse_multistate;
1384 
1385 	case oEnableSSHKeysign:
1386 		intptr = &options->enable_ssh_keysign;
1387 		goto parse_flag;
1388 
1389 	case oIdentitiesOnly:
1390 		intptr = &options->identities_only;
1391 		goto parse_flag;
1392 
1393 	case oServerAliveInterval:
1394 		intptr = &options->server_alive_interval;
1395 		goto parse_time;
1396 
1397 	case oServerAliveCountMax:
1398 		intptr = &options->server_alive_count_max;
1399 		goto parse_int;
1400 
1401 	case oSendEnv:
1402 		while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
1403 			if (strchr(arg, '=') != NULL)
1404 				fatal("%s line %d: Invalid environment name.",
1405 				    filename, linenum);
1406 			if (!*activep)
1407 				continue;
1408 			if (options->num_send_env >= MAX_SEND_ENV)
1409 				fatal("%s line %d: too many send env.",
1410 				    filename, linenum);
1411 			options->send_env[options->num_send_env++] =
1412 			    xstrdup(arg);
1413 		}
1414 		break;
1415 
1416 	case oControlPath:
1417 		charptr = &options->control_path;
1418 		goto parse_string;
1419 
1420 	case oControlMaster:
1421 		intptr = &options->control_master;
1422 		multistate_ptr = multistate_controlmaster;
1423 		goto parse_multistate;
1424 
1425 	case oControlPersist:
1426 		/* no/false/yes/true, or a time spec */
1427 		intptr = &options->control_persist;
1428 		arg = strdelim(&s);
1429 		if (!arg || *arg == '\0')
1430 			fatal("%.200s line %d: Missing ControlPersist"
1431 			    " argument.", filename, linenum);
1432 		value = 0;
1433 		value2 = 0;	/* timeout */
1434 		if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0)
1435 			value = 0;
1436 		else if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0)
1437 			value = 1;
1438 		else if ((value2 = convtime(arg)) >= 0)
1439 			value = 1;
1440 		else
1441 			fatal("%.200s line %d: Bad ControlPersist argument.",
1442 			    filename, linenum);
1443 		if (*activep && *intptr == -1) {
1444 			*intptr = value;
1445 			options->control_persist_timeout = value2;
1446 		}
1447 		break;
1448 
1449 	case oHashKnownHosts:
1450 		intptr = &options->hash_known_hosts;
1451 		goto parse_flag;
1452 
1453 	case oTunnel:
1454 		intptr = &options->tun_open;
1455 		multistate_ptr = multistate_tunnel;
1456 		goto parse_multistate;
1457 
1458 	case oTunnelDevice:
1459 		arg = strdelim(&s);
1460 		if (!arg || *arg == '\0')
1461 			fatal("%.200s line %d: Missing argument.", filename, linenum);
1462 		value = a2tun(arg, &value2);
1463 		if (value == SSH_TUNID_ERR)
1464 			fatal("%.200s line %d: Bad tun device.", filename, linenum);
1465 		if (*activep) {
1466 			options->tun_local = value;
1467 			options->tun_remote = value2;
1468 		}
1469 		break;
1470 
1471 	case oLocalCommand:
1472 		charptr = &options->local_command;
1473 		goto parse_command;
1474 
1475 	case oPermitLocalCommand:
1476 		intptr = &options->permit_local_command;
1477 		goto parse_flag;
1478 
1479 	case oVisualHostKey:
1480 		intptr = &options->visual_host_key;
1481 		goto parse_flag;
1482 
1483 	case oIPQoS:
1484 		arg = strdelim(&s);
1485 		if ((value = parse_ipqos(arg)) == -1)
1486 			fatal("%s line %d: Bad IPQoS value: %s",
1487 			    filename, linenum, arg);
1488 		arg = strdelim(&s);
1489 		if (arg == NULL)
1490 			value2 = value;
1491 		else if ((value2 = parse_ipqos(arg)) == -1)
1492 			fatal("%s line %d: Bad IPQoS value: %s",
1493 			    filename, linenum, arg);
1494 		if (*activep) {
1495 			options->ip_qos_interactive = value;
1496 			options->ip_qos_bulk = value2;
1497 		}
1498 		break;
1499 
1500 	case oRequestTTY:
1501 		intptr = &options->request_tty;
1502 		multistate_ptr = multistate_requesttty;
1503 		goto parse_multistate;
1504 
1505 	case oSendVersionFirst:
1506 		intptr = &options->send_version_first;
1507 		goto parse_flag;
1508 
1509 	case oIgnoreUnknown:
1510 		charptr = &options->ignored_unknown;
1511 		goto parse_string;
1512 
1513 	case oProxyUseFdpass:
1514 		intptr = &options->proxy_use_fdpass;
1515 		goto parse_flag;
1516 
1517 	case oCanonicalDomains:
1518 		value = options->num_canonical_domains != 0;
1519 		while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
1520 			valid_domain(arg, filename, linenum);
1521 			if (!*activep || value)
1522 				continue;
1523 			if (options->num_canonical_domains >= MAX_CANON_DOMAINS)
1524 				fatal("%s line %d: too many hostname suffixes.",
1525 				    filename, linenum);
1526 			options->canonical_domains[
1527 			    options->num_canonical_domains++] = xstrdup(arg);
1528 		}
1529 		break;
1530 
1531 	case oCanonicalizePermittedCNAMEs:
1532 		value = options->num_permitted_cnames != 0;
1533 		while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
1534 			/* Either '*' for everything or 'list:list' */
1535 			if (strcmp(arg, "*") == 0)
1536 				arg2 = arg;
1537 			else {
1538 				lowercase(arg);
1539 				if ((arg2 = strchr(arg, ':')) == NULL ||
1540 				    arg2[1] == '\0') {
1541 					fatal("%s line %d: "
1542 					    "Invalid permitted CNAME \"%s\"",
1543 					    filename, linenum, arg);
1544 				}
1545 				*arg2 = '\0';
1546 				arg2++;
1547 			}
1548 			if (!*activep || value)
1549 				continue;
1550 			if (options->num_permitted_cnames >= MAX_CANON_DOMAINS)
1551 				fatal("%s line %d: too many permitted CNAMEs.",
1552 				    filename, linenum);
1553 			cname = options->permitted_cnames +
1554 			    options->num_permitted_cnames++;
1555 			cname->source_list = xstrdup(arg);
1556 			cname->target_list = xstrdup(arg2);
1557 		}
1558 		break;
1559 
1560 	case oCanonicalizeHostname:
1561 		intptr = &options->canonicalize_hostname;
1562 		multistate_ptr = multistate_canonicalizehostname;
1563 		goto parse_multistate;
1564 
1565 	case oCanonicalizeMaxDots:
1566 		intptr = &options->canonicalize_max_dots;
1567 		goto parse_int;
1568 
1569 	case oCanonicalizeFallbackLocal:
1570 		intptr = &options->canonicalize_fallback_local;
1571 		goto parse_flag;
1572 
1573 	case oStreamLocalBindMask:
1574 		arg = strdelim(&s);
1575 		if (!arg || *arg == '\0')
1576 			fatal("%.200s line %d: Missing StreamLocalBindMask argument.", filename, linenum);
1577 		/* Parse mode in octal format */
1578 		value = strtol(arg, &endofnumber, 8);
1579 		if (arg == endofnumber || value < 0 || value > 0777)
1580 			fatal("%.200s line %d: Bad mask.", filename, linenum);
1581 		options->fwd_opts.streamlocal_bind_mask = (mode_t)value;
1582 		break;
1583 
1584 	case oStreamLocalBindUnlink:
1585 		intptr = &options->fwd_opts.streamlocal_bind_unlink;
1586 		goto parse_flag;
1587 
1588 	case oRevokedHostKeys:
1589 		charptr = &options->revoked_host_keys;
1590 		goto parse_string;
1591 
1592 	case oFingerprintHash:
1593 		intptr = &options->fingerprint_hash;
1594 		arg = strdelim(&s);
1595 		if (!arg || *arg == '\0')
1596 			fatal("%.200s line %d: Missing argument.",
1597 			    filename, linenum);
1598 		if ((value = ssh_digest_alg_by_name(arg)) == -1)
1599 			fatal("%.200s line %d: Invalid hash algorithm \"%s\".",
1600 			    filename, linenum, arg);
1601 		if (*activep && *intptr == -1)
1602 			*intptr = value;
1603 		break;
1604 
1605 	case oUpdateHostkeys:
1606 		intptr = &options->update_hostkeys;
1607 		multistate_ptr = multistate_yesnoask;
1608 		goto parse_multistate;
1609 
1610 	case oHostbasedKeyTypes:
1611 		charptr = &options->hostbased_key_types;
1612 		goto parse_keytypes;
1613 
1614 	case oPubkeyAcceptedKeyTypes:
1615 		charptr = &options->pubkey_key_types;
1616 		goto parse_keytypes;
1617 
1618 	case oAddKeysToAgent:
1619 		intptr = &options->add_keys_to_agent;
1620 		multistate_ptr = multistate_yesnoaskconfirm;
1621 		goto parse_multistate;
1622 
1623 	case oDeprecated:
1624 		debug("%s line %d: Deprecated option \"%s\"",
1625 		    filename, linenum, keyword);
1626 		return 0;
1627 
1628 	case oUnsupported:
1629 		error("%s line %d: Unsupported option \"%s\"",
1630 		    filename, linenum, keyword);
1631 		return 0;
1632 
1633 	default:
1634 		fatal("%s: Unimplemented opcode %d", __func__, opcode);
1635 	}
1636 
1637 	/* Check that there is no garbage at end of line. */
1638 	if ((arg = strdelim(&s)) != NULL && *arg != '\0') {
1639 		fatal("%.200s line %d: garbage at end of line; \"%.200s\".",
1640 		    filename, linenum, arg);
1641 	}
1642 	return 0;
1643 }
1644 
1645 
1646 /*
1647  * Reads the config file and modifies the options accordingly.  Options
1648  * should already be initialized before this call.  This never returns if
1649  * there is an error.  If the file does not exist, this returns 0.
1650  */
1651 
1652 int
1653 read_config_file(const char *filename, struct passwd *pw, const char *host,
1654     const char *original_host, Options *options, int flags)
1655 {
1656 	FILE *f;
1657 	char line[1024];
1658 	int active, linenum;
1659 	int bad_options = 0;
1660 
1661 	if ((f = fopen(filename, "r")) == NULL)
1662 		return 0;
1663 
1664 	if (flags & SSHCONF_CHECKPERM) {
1665 		struct stat sb;
1666 
1667 		if (fstat(fileno(f), &sb) == -1)
1668 			fatal("fstat %s: %s", filename, strerror(errno));
1669 		if (((sb.st_uid != 0 && sb.st_uid != getuid()) ||
1670 		    (sb.st_mode & 022) != 0))
1671 			fatal("Bad owner or permissions on %s", filename);
1672 	}
1673 
1674 	debug("Reading configuration data %.200s", filename);
1675 
1676 	/*
1677 	 * Mark that we are now processing the options.  This flag is turned
1678 	 * on/off by Host specifications.
1679 	 */
1680 	active = 1;
1681 	linenum = 0;
1682 	while (fgets(line, sizeof(line), f)) {
1683 		/* Update line number counter. */
1684 		linenum++;
1685 		if (process_config_line(options, pw, host, original_host,
1686 		    line, filename, linenum, &active, flags) != 0)
1687 			bad_options++;
1688 	}
1689 	fclose(f);
1690 	if (bad_options > 0)
1691 		fatal("%s: terminating, %d bad configuration options",
1692 		    filename, bad_options);
1693 	return 1;
1694 }
1695 
1696 /* Returns 1 if a string option is unset or set to "none" or 0 otherwise. */
1697 int
1698 option_clear_or_none(const char *o)
1699 {
1700 	return o == NULL || strcasecmp(o, "none") == 0;
1701 }
1702 
1703 /*
1704  * Initializes options to special values that indicate that they have not yet
1705  * been set.  Read_config_file will only set options with this value. Options
1706  * are processed in the following order: command line, user config file,
1707  * system config file.  Last, fill_default_options is called.
1708  */
1709 
1710 void
1711 initialize_options(Options * options)
1712 {
1713 	memset(options, 'X', sizeof(*options));
1714 	options->forward_agent = -1;
1715 	options->forward_x11 = -1;
1716 	options->forward_x11_trusted = -1;
1717 	options->forward_x11_timeout = -1;
1718 	options->exit_on_forward_failure = -1;
1719 	options->xauth_location = NULL;
1720 	options->fwd_opts.gateway_ports = -1;
1721 	options->fwd_opts.streamlocal_bind_mask = (mode_t)-1;
1722 	options->fwd_opts.streamlocal_bind_unlink = -1;
1723 	options->use_privileged_port = -1;
1724 	options->rsa_authentication = -1;
1725 	options->pubkey_authentication = -1;
1726 	options->challenge_response_authentication = -1;
1727 #if defined(KRB4) || defined(KRB5)
1728 	options->kerberos_authentication = -1;
1729 #endif
1730 #if defined(AFS) || defined(KRB5)
1731 	options->kerberos_tgt_passing = -1;
1732 #endif
1733 #ifdef AFS
1734 	options->afs_token_passing = -1;
1735 #endif
1736 	options->gss_authentication = -1;
1737 	options->gss_deleg_creds = -1;
1738 	options->password_authentication = -1;
1739 	options->kbd_interactive_authentication = -1;
1740 	options->kbd_interactive_devices = NULL;
1741 	options->rhosts_rsa_authentication = -1;
1742 	options->hostbased_authentication = -1;
1743 	options->batch_mode = -1;
1744 	options->check_host_ip = -1;
1745 	options->strict_host_key_checking = -1;
1746 	options->compression = -1;
1747 	options->tcp_keep_alive = -1;
1748 	options->compression_level = -1;
1749 	options->port = -1;
1750 	options->address_family = -1;
1751 	options->connection_attempts = -1;
1752 	options->connection_timeout = -1;
1753 	options->number_of_password_prompts = -1;
1754 	options->cipher = -1;
1755 	options->ciphers = NULL;
1756 	options->macs = NULL;
1757 	options->kex_algorithms = NULL;
1758 	options->hostkeyalgorithms = NULL;
1759 	options->protocol = SSH_PROTO_UNKNOWN;
1760 	options->num_identity_files = 0;
1761 	options->num_certificate_files = 0;
1762 	options->hostname = NULL;
1763 	options->host_key_alias = NULL;
1764 	options->proxy_command = NULL;
1765 	options->user = NULL;
1766 	options->escape_char = -1;
1767 	options->num_system_hostfiles = 0;
1768 	options->num_user_hostfiles = 0;
1769 	options->local_forwards = NULL;
1770 	options->num_local_forwards = 0;
1771 	options->remote_forwards = NULL;
1772 	options->num_remote_forwards = 0;
1773 	options->clear_forwardings = -1;
1774 	options->log_level = SYSLOG_LEVEL_NOT_SET;
1775 	options->preferred_authentications = NULL;
1776 	options->bind_address = NULL;
1777 	options->pkcs11_provider = NULL;
1778 	options->enable_ssh_keysign = - 1;
1779 	options->no_host_authentication_for_localhost = - 1;
1780 	options->identities_only = - 1;
1781 	options->rekey_limit = - 1;
1782 	options->rekey_interval = -1;
1783 	options->verify_host_key_dns = -1;
1784 	options->server_alive_interval = -1;
1785 	options->server_alive_count_max = -1;
1786 	options->num_send_env = 0;
1787 	options->control_path = NULL;
1788 	options->control_master = -1;
1789 	options->control_persist = -1;
1790 	options->control_persist_timeout = 0;
1791 	options->hash_known_hosts = -1;
1792 	options->tun_open = -1;
1793 	options->tun_local = -1;
1794 	options->tun_remote = -1;
1795 	options->local_command = NULL;
1796 	options->permit_local_command = -1;
1797 	options->add_keys_to_agent = -1;
1798 	options->visual_host_key = -1;
1799 	options->ip_qos_interactive = -1;
1800 	options->ip_qos_bulk = -1;
1801 	options->request_tty = -1;
1802 	options->proxy_use_fdpass = -1;
1803 	options->ignored_unknown = NULL;
1804 	options->num_canonical_domains = 0;
1805 	options->num_permitted_cnames = 0;
1806 	options->canonicalize_max_dots = -1;
1807 	options->canonicalize_fallback_local = -1;
1808 	options->canonicalize_hostname = -1;
1809 	options->revoked_host_keys = NULL;
1810 	options->fingerprint_hash = -1;
1811 	options->update_hostkeys = -1;
1812 	options->hostbased_key_types = NULL;
1813 	options->pubkey_key_types = NULL;
1814 	options->none_switch = -1;
1815 	options->none_enabled = -1;
1816 	options->hpn_disabled = -1;
1817 	options->hpn_buffer_size = -1;
1818 	options->tcp_rcv_buf_poll = -1;
1819 	options->tcp_rcv_buf = -1;
1820 	options->send_version_first = -1;
1821 }
1822 
1823 /*
1824  * A petite version of fill_default_options() that just fills the options
1825  * needed for hostname canonicalization to proceed.
1826  */
1827 void
1828 fill_default_options_for_canonicalization(Options *options)
1829 {
1830 	if (options->canonicalize_max_dots == -1)
1831 		options->canonicalize_max_dots = 1;
1832 	if (options->canonicalize_fallback_local == -1)
1833 		options->canonicalize_fallback_local = 1;
1834 	if (options->canonicalize_hostname == -1)
1835 		options->canonicalize_hostname = SSH_CANONICALISE_NO;
1836 }
1837 
1838 /*
1839  * Called after processing other sources of option data, this fills those
1840  * options for which no value has been specified with their default values.
1841  */
1842 void
1843 fill_default_options(Options * options)
1844 {
1845 	if (options->forward_agent == -1)
1846 		options->forward_agent = 0;
1847 	if (options->forward_x11 == -1)
1848 		options->forward_x11 = 0;
1849 	if (options->forward_x11_trusted == -1)
1850 		options->forward_x11_trusted = 0;
1851 	if (options->forward_x11_timeout == -1)
1852 		options->forward_x11_timeout = 1200;
1853 	if (options->exit_on_forward_failure == -1)
1854 		options->exit_on_forward_failure = 0;
1855 	if (options->xauth_location == NULL)
1856 		options->xauth_location = __UNCONST(_PATH_XAUTH);
1857 	if (options->fwd_opts.gateway_ports == -1)
1858 		options->fwd_opts.gateway_ports = 0;
1859 	if (options->fwd_opts.streamlocal_bind_mask == (mode_t)-1)
1860 		options->fwd_opts.streamlocal_bind_mask = 0177;
1861 	if (options->fwd_opts.streamlocal_bind_unlink == -1)
1862 		options->fwd_opts.streamlocal_bind_unlink = 0;
1863 	if (options->use_privileged_port == -1)
1864 		options->use_privileged_port = 0;
1865 	if (options->rsa_authentication == -1)
1866 		options->rsa_authentication = 1;
1867 	if (options->pubkey_authentication == -1)
1868 		options->pubkey_authentication = 1;
1869 	if (options->challenge_response_authentication == -1)
1870 		options->challenge_response_authentication = 1;
1871 #if defined(KRB4) || defined(KRB5)
1872 	if (options->kerberos_authentication == -1)
1873 		options->kerberos_authentication = 1;
1874 #endif
1875 #if defined(AFS) || defined(KRB5)
1876 	if (options->kerberos_tgt_passing == -1)
1877 		options->kerberos_tgt_passing = 1;
1878 #endif
1879 #ifdef AFS
1880 	if (options->afs_token_passing == -1)
1881 		options->afs_token_passing = 1;
1882 #endif
1883 	if (options->gss_authentication == -1)
1884 		options->gss_authentication = 0;
1885 	if (options->gss_deleg_creds == -1)
1886 		options->gss_deleg_creds = 0;
1887 	if (options->password_authentication == -1)
1888 		options->password_authentication = 1;
1889 	if (options->kbd_interactive_authentication == -1)
1890 		options->kbd_interactive_authentication = 1;
1891 	if (options->rhosts_rsa_authentication == -1)
1892 		options->rhosts_rsa_authentication = 0;
1893 	if (options->hostbased_authentication == -1)
1894 		options->hostbased_authentication = 0;
1895 	if (options->batch_mode == -1)
1896 		options->batch_mode = 0;
1897 	if (options->check_host_ip == -1)
1898 		options->check_host_ip = 1;
1899 	if (options->strict_host_key_checking == -1)
1900 		options->strict_host_key_checking = 2;	/* 2 is default */
1901 	if (options->compression == -1)
1902 		options->compression = 0;
1903 	if (options->tcp_keep_alive == -1)
1904 		options->tcp_keep_alive = 1;
1905 	if (options->compression_level == -1)
1906 		options->compression_level = 6;
1907 	if (options->port == -1)
1908 		options->port = 0;	/* Filled in ssh_connect. */
1909 	if (options->address_family == -1)
1910 		options->address_family = AF_UNSPEC;
1911 	if (options->connection_attempts == -1)
1912 		options->connection_attempts = 1;
1913 	if (options->number_of_password_prompts == -1)
1914 		options->number_of_password_prompts = 3;
1915 	/* Selected in ssh_login(). */
1916 	if (options->cipher == -1)
1917 		options->cipher = SSH_CIPHER_NOT_SET;
1918 	/* options->hostkeyalgorithms, default set in myproposals.h */
1919 	if (options->protocol == SSH_PROTO_UNKNOWN)
1920 		options->protocol = SSH_PROTO_2;
1921 	if (options->add_keys_to_agent == -1)
1922 		options->add_keys_to_agent = 0;
1923 	if (options->num_identity_files == 0) {
1924 		if (options->protocol & SSH_PROTO_1) {
1925 			add_identity_file(options, "~/",
1926 			    _PATH_SSH_CLIENT_IDENTITY, 0);
1927 		}
1928 		if (options->protocol & SSH_PROTO_2) {
1929 			add_identity_file(options, "~/",
1930 			    _PATH_SSH_CLIENT_ID_RSA, 0);
1931 			add_identity_file(options, "~/",
1932 			    _PATH_SSH_CLIENT_ID_DSA, 0);
1933 			add_identity_file(options, "~/",
1934 			    _PATH_SSH_CLIENT_ID_ECDSA, 0);
1935 			add_identity_file(options, "~/",
1936 			    _PATH_SSH_CLIENT_ID_ED25519, 0);
1937 		}
1938 	}
1939 	if (options->escape_char == -1)
1940 		options->escape_char = '~';
1941 	if (options->num_system_hostfiles == 0) {
1942 		options->system_hostfiles[options->num_system_hostfiles++] =
1943 		    xstrdup(_PATH_SSH_SYSTEM_HOSTFILE);
1944 		options->system_hostfiles[options->num_system_hostfiles++] =
1945 		    xstrdup(_PATH_SSH_SYSTEM_HOSTFILE2);
1946 	}
1947 	if (options->num_user_hostfiles == 0) {
1948 		options->user_hostfiles[options->num_user_hostfiles++] =
1949 		    xstrdup(_PATH_SSH_USER_HOSTFILE);
1950 		options->user_hostfiles[options->num_user_hostfiles++] =
1951 		    xstrdup(_PATH_SSH_USER_HOSTFILE2);
1952 	}
1953 	if (options->log_level == SYSLOG_LEVEL_NOT_SET)
1954 		options->log_level = SYSLOG_LEVEL_INFO;
1955 	if (options->clear_forwardings == 1)
1956 		clear_forwardings(options);
1957 	if (options->no_host_authentication_for_localhost == - 1)
1958 		options->no_host_authentication_for_localhost = 0;
1959 	if (options->identities_only == -1)
1960 		options->identities_only = 0;
1961 	if (options->enable_ssh_keysign == -1)
1962 		options->enable_ssh_keysign = 0;
1963 	if (options->rekey_limit == -1)
1964 		options->rekey_limit = 0;
1965 	if (options->rekey_interval == -1)
1966 		options->rekey_interval = 0;
1967 	if (options->verify_host_key_dns == -1)
1968 		options->verify_host_key_dns = 0;
1969 	if (options->server_alive_interval == -1)
1970 		options->server_alive_interval = 0;
1971 	if (options->server_alive_count_max == -1)
1972 		options->server_alive_count_max = 3;
1973 	if (options->none_switch == -1)
1974 	        options->none_switch = 0;
1975 	if (options->hpn_disabled == -1)
1976 	        options->hpn_disabled = 0;
1977 	if (options->hpn_buffer_size > -1)
1978 	{
1979 	  /* if a user tries to set the size to 0 set it to 1KB */
1980 		if (options->hpn_buffer_size == 0)
1981 		options->hpn_buffer_size = 1024;
1982 		/*limit the buffer to 64MB*/
1983 		if (options->hpn_buffer_size > 65536)
1984 		{
1985 			options->hpn_buffer_size = 65536*1024;
1986 			debug("User requested buffer larger than 64MB. Request reverted to 64MB");
1987 		}
1988 		debug("hpn_buffer_size set to %d", options->hpn_buffer_size);
1989 	}
1990 	if (options->tcp_rcv_buf == 0)
1991 		options->tcp_rcv_buf = 1;
1992 	if (options->tcp_rcv_buf > -1)
1993 		options->tcp_rcv_buf *=1024;
1994 	if (options->tcp_rcv_buf_poll == -1)
1995 		options->tcp_rcv_buf_poll = 1;
1996 	if (options->control_master == -1)
1997 		options->control_master = 0;
1998 	if (options->control_persist == -1) {
1999 		options->control_persist = 0;
2000 		options->control_persist_timeout = 0;
2001 	}
2002 	if (options->hash_known_hosts == -1)
2003 		options->hash_known_hosts = 0;
2004 	if (options->tun_open == -1)
2005 		options->tun_open = SSH_TUNMODE_NO;
2006 	if (options->tun_local == -1)
2007 		options->tun_local = SSH_TUNID_ANY;
2008 	if (options->tun_remote == -1)
2009 		options->tun_remote = SSH_TUNID_ANY;
2010 	if (options->permit_local_command == -1)
2011 		options->permit_local_command = 0;
2012 	if (options->visual_host_key == -1)
2013 		options->visual_host_key = 0;
2014 	if (options->ip_qos_interactive == -1)
2015 		options->ip_qos_interactive = IPTOS_LOWDELAY;
2016 	if (options->ip_qos_bulk == -1)
2017 		options->ip_qos_bulk = IPTOS_THROUGHPUT;
2018 	if (options->request_tty == -1)
2019 		options->request_tty = REQUEST_TTY_AUTO;
2020 	if (options->proxy_use_fdpass == -1)
2021 		options->proxy_use_fdpass = 0;
2022 	if (options->canonicalize_max_dots == -1)
2023 		options->canonicalize_max_dots = 1;
2024 	if (options->canonicalize_fallback_local == -1)
2025 		options->canonicalize_fallback_local = 1;
2026 	if (options->canonicalize_hostname == -1)
2027 		options->canonicalize_hostname = SSH_CANONICALISE_NO;
2028 	if (options->fingerprint_hash == -1)
2029 		options->fingerprint_hash = SSH_FP_HASH_DEFAULT;
2030 	if (options->update_hostkeys == -1)
2031 		options->update_hostkeys = 0;
2032 	if (kex_assemble_names(KEX_CLIENT_ENCRYPT, &options->ciphers) != 0 ||
2033 	    kex_assemble_names(KEX_CLIENT_MAC, &options->macs) != 0 ||
2034 	    kex_assemble_names(KEX_CLIENT_KEX, &options->kex_algorithms) != 0 ||
2035 	    kex_assemble_names(KEX_DEFAULT_PK_ALG,
2036 	    &options->hostbased_key_types) != 0 ||
2037 	    kex_assemble_names(KEX_DEFAULT_PK_ALG,
2038 	    &options->pubkey_key_types) != 0)
2039 		fatal("%s: kex_assemble_names failed", __func__);
2040 
2041 	if (options->send_version_first == -1)
2042 		options->send_version_first = 1;
2043 #define CLEAR_ON_NONE(v) \
2044 	do { \
2045 		if (option_clear_or_none(v)) { \
2046 			free(v); \
2047 			v = NULL; \
2048 		} \
2049 	} while(0)
2050 	CLEAR_ON_NONE(options->local_command);
2051 	CLEAR_ON_NONE(options->proxy_command);
2052 	CLEAR_ON_NONE(options->control_path);
2053 	CLEAR_ON_NONE(options->revoked_host_keys);
2054 	/* options->user will be set in the main program if appropriate */
2055 	/* options->hostname will be set in the main program if appropriate */
2056 	/* options->host_key_alias should not be set by default */
2057 	/* options->preferred_authentications will be set in ssh */
2058 }
2059 
2060 struct fwdarg {
2061 	char *arg;
2062 	int ispath;
2063 };
2064 
2065 /*
2066  * parse_fwd_field
2067  * parses the next field in a port forwarding specification.
2068  * sets fwd to the parsed field and advances p past the colon
2069  * or sets it to NULL at end of string.
2070  * returns 0 on success, else non-zero.
2071  */
2072 static int
2073 parse_fwd_field(char **p, struct fwdarg *fwd)
2074 {
2075 	char *ep, *cp = *p;
2076 	int ispath = 0;
2077 
2078 	if (*cp == '\0') {
2079 		*p = NULL;
2080 		return -1;	/* end of string */
2081 	}
2082 
2083 	/*
2084 	 * A field escaped with square brackets is used literally.
2085 	 * XXX - allow ']' to be escaped via backslash?
2086 	 */
2087 	if (*cp == '[') {
2088 		/* find matching ']' */
2089 		for (ep = cp + 1; *ep != ']' && *ep != '\0'; ep++) {
2090 			if (*ep == '/')
2091 				ispath = 1;
2092 		}
2093 		/* no matching ']' or not at end of field. */
2094 		if (ep[0] != ']' || (ep[1] != ':' && ep[1] != '\0'))
2095 			return -1;
2096 		/* NUL terminate the field and advance p past the colon */
2097 		*ep++ = '\0';
2098 		if (*ep != '\0')
2099 			*ep++ = '\0';
2100 		fwd->arg = cp + 1;
2101 		fwd->ispath = ispath;
2102 		*p = ep;
2103 		return 0;
2104 	}
2105 
2106 	for (cp = *p; *cp != '\0'; cp++) {
2107 		switch (*cp) {
2108 		case '\\':
2109 			memmove(cp, cp + 1, strlen(cp + 1) + 1);
2110 			if (*cp == '\0')
2111 				return -1;
2112 			break;
2113 		case '/':
2114 			ispath = 1;
2115 			break;
2116 		case ':':
2117 			*cp++ = '\0';
2118 			goto done;
2119 		}
2120 	}
2121 done:
2122 	fwd->arg = *p;
2123 	fwd->ispath = ispath;
2124 	*p = cp;
2125 	return 0;
2126 }
2127 
2128 /*
2129  * parse_forward
2130  * parses a string containing a port forwarding specification of the form:
2131  *   dynamicfwd == 0
2132  *	[listenhost:]listenport|listenpath:connecthost:connectport|connectpath
2133  *	listenpath:connectpath
2134  *   dynamicfwd == 1
2135  *	[listenhost:]listenport
2136  * returns number of arguments parsed or zero on error
2137  */
2138 int
2139 parse_forward(struct Forward *fwd, const char *fwdspec, int dynamicfwd, int remotefwd)
2140 {
2141 	struct fwdarg fwdargs[4];
2142 	char *p, *cp;
2143 	int i;
2144 
2145 	memset(fwd, 0, sizeof(*fwd));
2146 	memset(fwdargs, 0, sizeof(fwdargs));
2147 
2148 	cp = p = xstrdup(fwdspec);
2149 
2150 	/* skip leading spaces */
2151 	while (isspace((u_char)*cp))
2152 		cp++;
2153 
2154 	for (i = 0; i < 4; ++i) {
2155 		if (parse_fwd_field(&cp, &fwdargs[i]) != 0)
2156 			break;
2157 	}
2158 
2159 	/* Check for trailing garbage */
2160 	if (cp != NULL && *cp != '\0') {
2161 		i = 0;	/* failure */
2162 	}
2163 
2164 	switch (i) {
2165 	case 1:
2166 		if (fwdargs[0].ispath) {
2167 			fwd->listen_path = xstrdup(fwdargs[0].arg);
2168 			fwd->listen_port = PORT_STREAMLOCAL;
2169 		} else {
2170 			fwd->listen_host = NULL;
2171 			fwd->listen_port = a2port(fwdargs[0].arg);
2172 		}
2173 		fwd->connect_host = xstrdup("socks");
2174 		break;
2175 
2176 	case 2:
2177 		if (fwdargs[0].ispath && fwdargs[1].ispath) {
2178 			fwd->listen_path = xstrdup(fwdargs[0].arg);
2179 			fwd->listen_port = PORT_STREAMLOCAL;
2180 			fwd->connect_path = xstrdup(fwdargs[1].arg);
2181 			fwd->connect_port = PORT_STREAMLOCAL;
2182 		} else if (fwdargs[1].ispath) {
2183 			fwd->listen_host = NULL;
2184 			fwd->listen_port = a2port(fwdargs[0].arg);
2185 			fwd->connect_path = xstrdup(fwdargs[1].arg);
2186 			fwd->connect_port = PORT_STREAMLOCAL;
2187 		} else {
2188 			fwd->listen_host = xstrdup(fwdargs[0].arg);
2189 			fwd->listen_port = a2port(fwdargs[1].arg);
2190 			fwd->connect_host = xstrdup("socks");
2191 		}
2192 		break;
2193 
2194 	case 3:
2195 		if (fwdargs[0].ispath) {
2196 			fwd->listen_path = xstrdup(fwdargs[0].arg);
2197 			fwd->listen_port = PORT_STREAMLOCAL;
2198 			fwd->connect_host = xstrdup(fwdargs[1].arg);
2199 			fwd->connect_port = a2port(fwdargs[2].arg);
2200 		} else if (fwdargs[2].ispath) {
2201 			fwd->listen_host = xstrdup(fwdargs[0].arg);
2202 			fwd->listen_port = a2port(fwdargs[1].arg);
2203 			fwd->connect_path = xstrdup(fwdargs[2].arg);
2204 			fwd->connect_port = PORT_STREAMLOCAL;
2205 		} else {
2206 			fwd->listen_host = NULL;
2207 			fwd->listen_port = a2port(fwdargs[0].arg);
2208 			fwd->connect_host = xstrdup(fwdargs[1].arg);
2209 			fwd->connect_port = a2port(fwdargs[2].arg);
2210 		}
2211 		break;
2212 
2213 	case 4:
2214 		fwd->listen_host = xstrdup(fwdargs[0].arg);
2215 		fwd->listen_port = a2port(fwdargs[1].arg);
2216 		fwd->connect_host = xstrdup(fwdargs[2].arg);
2217 		fwd->connect_port = a2port(fwdargs[3].arg);
2218 		break;
2219 	default:
2220 		i = 0; /* failure */
2221 	}
2222 
2223 	free(p);
2224 
2225 	if (dynamicfwd) {
2226 		if (!(i == 1 || i == 2))
2227 			goto fail_free;
2228 	} else {
2229 		if (!(i == 3 || i == 4)) {
2230 			if (fwd->connect_path == NULL &&
2231 			    fwd->listen_path == NULL)
2232 				goto fail_free;
2233 		}
2234 		if (fwd->connect_port <= 0 && fwd->connect_path == NULL)
2235 			goto fail_free;
2236 	}
2237 
2238 	if ((fwd->listen_port < 0 && fwd->listen_path == NULL) ||
2239 	    (!remotefwd && fwd->listen_port == 0))
2240 		goto fail_free;
2241 	if (fwd->connect_host != NULL &&
2242 	    strlen(fwd->connect_host) >= NI_MAXHOST)
2243 		goto fail_free;
2244 	/* XXX - if connecting to a remote socket, max sun len may not match this host */
2245 	if (fwd->connect_path != NULL &&
2246 	    strlen(fwd->connect_path) >= PATH_MAX_SUN)
2247 		goto fail_free;
2248 	if (fwd->listen_host != NULL &&
2249 	    strlen(fwd->listen_host) >= NI_MAXHOST)
2250 		goto fail_free;
2251 	if (fwd->listen_path != NULL &&
2252 	    strlen(fwd->listen_path) >= PATH_MAX_SUN)
2253 		goto fail_free;
2254 
2255 	return (i);
2256 
2257  fail_free:
2258 	free(fwd->connect_host);
2259 	fwd->connect_host = NULL;
2260 	free(fwd->connect_path);
2261 	fwd->connect_path = NULL;
2262 	free(fwd->listen_host);
2263 	fwd->listen_host = NULL;
2264 	free(fwd->listen_path);
2265 	fwd->listen_path = NULL;
2266 	return (0);
2267 }
2268 
2269 /* XXX the following is a near-vebatim copy from servconf.c; refactor */
2270 static const char *
2271 fmt_multistate_int(int val, const struct multistate *m)
2272 {
2273 	u_int i;
2274 
2275 	for (i = 0; m[i].key != NULL; i++) {
2276 		if (m[i].value == val)
2277 			return m[i].key;
2278 	}
2279 	return "UNKNOWN";
2280 }
2281 
2282 static const char *
2283 fmt_intarg(OpCodes code, int val)
2284 {
2285 	if (val == -1)
2286 		return "unset";
2287 	switch (code) {
2288 	case oAddressFamily:
2289 		return fmt_multistate_int(val, multistate_addressfamily);
2290 	case oVerifyHostKeyDNS:
2291 	case oStrictHostKeyChecking:
2292 	case oUpdateHostkeys:
2293 		return fmt_multistate_int(val, multistate_yesnoask);
2294 	case oControlMaster:
2295 		return fmt_multistate_int(val, multistate_controlmaster);
2296 	case oTunnel:
2297 		return fmt_multistate_int(val, multistate_tunnel);
2298 	case oRequestTTY:
2299 		return fmt_multistate_int(val, multistate_requesttty);
2300 	case oCanonicalizeHostname:
2301 		return fmt_multistate_int(val, multistate_canonicalizehostname);
2302 	case oFingerprintHash:
2303 		return ssh_digest_alg_name(val);
2304 	case oProtocol:
2305 		switch (val) {
2306 		case SSH_PROTO_1:
2307 			return "1";
2308 		case SSH_PROTO_2:
2309 			return "2";
2310 		case (SSH_PROTO_1|SSH_PROTO_2):
2311 			return "2,1";
2312 		default:
2313 			return "UNKNOWN";
2314 		}
2315 	default:
2316 		switch (val) {
2317 		case 0:
2318 			return "no";
2319 		case 1:
2320 			return "yes";
2321 		default:
2322 			return "UNKNOWN";
2323 		}
2324 	}
2325 }
2326 
2327 static const char *
2328 lookup_opcode_name(OpCodes code)
2329 {
2330 	u_int i;
2331 
2332 	for (i = 0; keywords[i].name != NULL; i++)
2333 		if (keywords[i].opcode == code)
2334 			return(keywords[i].name);
2335 	return "UNKNOWN";
2336 }
2337 
2338 static void
2339 dump_cfg_int(OpCodes code, int val)
2340 {
2341 	printf("%s %d\n", lookup_opcode_name(code), val);
2342 }
2343 
2344 static void
2345 dump_cfg_fmtint(OpCodes code, int val)
2346 {
2347 	printf("%s %s\n", lookup_opcode_name(code), fmt_intarg(code, val));
2348 }
2349 
2350 static void
2351 dump_cfg_string(OpCodes code, const char *val)
2352 {
2353 	if (val == NULL)
2354 		return;
2355 	printf("%s %s\n", lookup_opcode_name(code), val);
2356 }
2357 
2358 static void
2359 dump_cfg_strarray(OpCodes code, u_int count, char **vals)
2360 {
2361 	u_int i;
2362 
2363 	for (i = 0; i < count; i++)
2364 		printf("%s %s\n", lookup_opcode_name(code), vals[i]);
2365 }
2366 
2367 static void
2368 dump_cfg_strarray_oneline(OpCodes code, u_int count, char **vals)
2369 {
2370 	u_int i;
2371 
2372 	printf("%s", lookup_opcode_name(code));
2373 	for (i = 0; i < count; i++)
2374 		printf(" %s",  vals[i]);
2375 	printf("\n");
2376 }
2377 
2378 static void
2379 dump_cfg_forwards(OpCodes code, u_int count, const struct Forward *fwds)
2380 {
2381 	const struct Forward *fwd;
2382 	u_int i;
2383 
2384 	/* oDynamicForward */
2385 	for (i = 0; i < count; i++) {
2386 		fwd = &fwds[i];
2387 		if (code == oDynamicForward &&
2388 		    strcmp(fwd->connect_host, "socks") != 0)
2389 			continue;
2390 		if (code == oLocalForward &&
2391 		    strcmp(fwd->connect_host, "socks") == 0)
2392 			continue;
2393 		printf("%s", lookup_opcode_name(code));
2394 		if (fwd->listen_port == PORT_STREAMLOCAL)
2395 			printf(" %s", fwd->listen_path);
2396 		else if (fwd->listen_host == NULL)
2397 			printf(" %d", fwd->listen_port);
2398 		else {
2399 			printf(" [%s]:%d",
2400 			    fwd->listen_host, fwd->listen_port);
2401 		}
2402 		if (code != oDynamicForward) {
2403 			if (fwd->connect_port == PORT_STREAMLOCAL)
2404 				printf(" %s", fwd->connect_path);
2405 			else if (fwd->connect_host == NULL)
2406 				printf(" %d", fwd->connect_port);
2407 			else {
2408 				printf(" [%s]:%d",
2409 				    fwd->connect_host, fwd->connect_port);
2410 			}
2411 		}
2412 		printf("\n");
2413 	}
2414 }
2415 
2416 void
2417 dump_client_config(Options *o, const char *host)
2418 {
2419 	int i;
2420 	char vbuf[5];
2421 
2422 	/* This is normally prepared in ssh_kex2 */
2423 	if (kex_assemble_names(KEX_DEFAULT_PK_ALG, &o->hostkeyalgorithms) != 0)
2424 		fatal("%s: kex_assemble_names failed", __func__);
2425 
2426 	/* Most interesting options first: user, host, port */
2427 	dump_cfg_string(oUser, o->user);
2428 	dump_cfg_string(oHostName, host);
2429 	dump_cfg_int(oPort, o->port);
2430 
2431 	/* Flag options */
2432 	dump_cfg_fmtint(oAddressFamily, o->address_family);
2433 	dump_cfg_fmtint(oBatchMode, o->batch_mode);
2434 	dump_cfg_fmtint(oCanonicalizeFallbackLocal, o->canonicalize_fallback_local);
2435 	dump_cfg_fmtint(oCanonicalizeHostname, o->canonicalize_hostname);
2436 	dump_cfg_fmtint(oChallengeResponseAuthentication, o->challenge_response_authentication);
2437 	dump_cfg_fmtint(oCheckHostIP, o->check_host_ip);
2438 	dump_cfg_fmtint(oCompression, o->compression);
2439 	dump_cfg_fmtint(oControlMaster, o->control_master);
2440 	dump_cfg_fmtint(oEnableSSHKeysign, o->enable_ssh_keysign);
2441 	dump_cfg_fmtint(oExitOnForwardFailure, o->exit_on_forward_failure);
2442 	dump_cfg_fmtint(oFingerprintHash, o->fingerprint_hash);
2443 	dump_cfg_fmtint(oForwardAgent, o->forward_agent);
2444 	dump_cfg_fmtint(oForwardX11, o->forward_x11);
2445 	dump_cfg_fmtint(oForwardX11Trusted, o->forward_x11_trusted);
2446 	dump_cfg_fmtint(oGatewayPorts, o->fwd_opts.gateway_ports);
2447 #ifdef GSSAPI
2448 	dump_cfg_fmtint(oGssAuthentication, o->gss_authentication);
2449 	dump_cfg_fmtint(oGssDelegateCreds, o->gss_deleg_creds);
2450 #endif /* GSSAPI */
2451 	dump_cfg_fmtint(oHashKnownHosts, o->hash_known_hosts);
2452 	dump_cfg_fmtint(oHostbasedAuthentication, o->hostbased_authentication);
2453 	dump_cfg_fmtint(oIdentitiesOnly, o->identities_only);
2454 	dump_cfg_fmtint(oKbdInteractiveAuthentication, o->kbd_interactive_authentication);
2455 	dump_cfg_fmtint(oNoHostAuthenticationForLocalhost, o->no_host_authentication_for_localhost);
2456 	dump_cfg_fmtint(oPasswordAuthentication, o->password_authentication);
2457 	dump_cfg_fmtint(oPermitLocalCommand, o->permit_local_command);
2458 	dump_cfg_fmtint(oProtocol, o->protocol);
2459 	dump_cfg_fmtint(oProxyUseFdpass, o->proxy_use_fdpass);
2460 	dump_cfg_fmtint(oPubkeyAuthentication, o->pubkey_authentication);
2461 	dump_cfg_fmtint(oRequestTTY, o->request_tty);
2462 	dump_cfg_fmtint(oRhostsRSAAuthentication, o->rhosts_rsa_authentication);
2463 	dump_cfg_fmtint(oRSAAuthentication, o->rsa_authentication);
2464 	dump_cfg_fmtint(oStreamLocalBindUnlink, o->fwd_opts.streamlocal_bind_unlink);
2465 	dump_cfg_fmtint(oStrictHostKeyChecking, o->strict_host_key_checking);
2466 	dump_cfg_fmtint(oTCPKeepAlive, o->tcp_keep_alive);
2467 	dump_cfg_fmtint(oTunnel, o->tun_open);
2468 	dump_cfg_fmtint(oUsePrivilegedPort, o->use_privileged_port);
2469 	dump_cfg_fmtint(oVerifyHostKeyDNS, o->verify_host_key_dns);
2470 	dump_cfg_fmtint(oVisualHostKey, o->visual_host_key);
2471 	dump_cfg_fmtint(oUpdateHostkeys, o->update_hostkeys);
2472 
2473 	/* Integer options */
2474 	dump_cfg_int(oCanonicalizeMaxDots, o->canonicalize_max_dots);
2475 	dump_cfg_int(oCompressionLevel, o->compression_level);
2476 	dump_cfg_int(oConnectionAttempts, o->connection_attempts);
2477 	dump_cfg_int(oForwardX11Timeout, o->forward_x11_timeout);
2478 	dump_cfg_int(oNumberOfPasswordPrompts, o->number_of_password_prompts);
2479 	dump_cfg_int(oServerAliveCountMax, o->server_alive_count_max);
2480 	dump_cfg_int(oServerAliveInterval, o->server_alive_interval);
2481 
2482 	/* String options */
2483 	dump_cfg_string(oBindAddress, o->bind_address);
2484 	dump_cfg_string(oCiphers, o->ciphers ? o->ciphers : KEX_CLIENT_ENCRYPT);
2485 	dump_cfg_string(oControlPath, o->control_path);
2486 	dump_cfg_string(oHostKeyAlgorithms, o->hostkeyalgorithms);
2487 	dump_cfg_string(oHostKeyAlias, o->host_key_alias);
2488 	dump_cfg_string(oHostbasedKeyTypes, o->hostbased_key_types);
2489 	dump_cfg_string(oKbdInteractiveDevices, o->kbd_interactive_devices);
2490 	dump_cfg_string(oKexAlgorithms, o->kex_algorithms ? o->kex_algorithms : KEX_CLIENT_KEX);
2491 	dump_cfg_string(oLocalCommand, o->local_command);
2492 	dump_cfg_string(oLogLevel, log_level_name(o->log_level));
2493 	dump_cfg_string(oMacs, o->macs ? o->macs : KEX_CLIENT_MAC);
2494 	dump_cfg_string(oPKCS11Provider, o->pkcs11_provider);
2495 	dump_cfg_string(oPreferredAuthentications, o->preferred_authentications);
2496 	dump_cfg_string(oProxyCommand, o->proxy_command);
2497 	dump_cfg_string(oPubkeyAcceptedKeyTypes, o->pubkey_key_types);
2498 	dump_cfg_string(oRevokedHostKeys, o->revoked_host_keys);
2499 	dump_cfg_string(oXAuthLocation, o->xauth_location);
2500 
2501 	/* Forwards */
2502 	dump_cfg_forwards(oDynamicForward, o->num_local_forwards, o->local_forwards);
2503 	dump_cfg_forwards(oLocalForward, o->num_local_forwards, o->local_forwards);
2504 	dump_cfg_forwards(oRemoteForward, o->num_remote_forwards, o->remote_forwards);
2505 
2506 	/* String array options */
2507 	dump_cfg_strarray(oIdentityFile, o->num_identity_files, o->identity_files);
2508 	dump_cfg_strarray_oneline(oCanonicalDomains, o->num_canonical_domains, o->canonical_domains);
2509 	dump_cfg_strarray_oneline(oGlobalKnownHostsFile, o->num_system_hostfiles, o->system_hostfiles);
2510 	dump_cfg_strarray_oneline(oUserKnownHostsFile, o->num_user_hostfiles, o->user_hostfiles);
2511 	dump_cfg_strarray(oSendEnv, o->num_send_env, o->send_env);
2512 
2513 	/* Special cases */
2514 
2515 	/* oConnectTimeout */
2516 	if (o->connection_timeout == -1)
2517 		printf("connecttimeout none\n");
2518 	else
2519 		dump_cfg_int(oConnectTimeout, o->connection_timeout);
2520 
2521 	/* oTunnelDevice */
2522 	printf("tunneldevice");
2523 	if (o->tun_local == SSH_TUNID_ANY)
2524 		printf(" any");
2525 	else
2526 		printf(" %d", o->tun_local);
2527 	if (o->tun_remote == SSH_TUNID_ANY)
2528 		printf(":any");
2529 	else
2530 		printf(":%d", o->tun_remote);
2531 	printf("\n");
2532 
2533 	/* oCanonicalizePermittedCNAMEs */
2534 	if ( o->num_permitted_cnames > 0) {
2535 		printf("canonicalizePermittedcnames");
2536 		for (i = 0; i < o->num_permitted_cnames; i++) {
2537 			printf(" %s:%s", o->permitted_cnames[i].source_list,
2538 			    o->permitted_cnames[i].target_list);
2539 		}
2540 		printf("\n");
2541 	}
2542 
2543 	/* oCipher */
2544 	if (o->cipher != SSH_CIPHER_NOT_SET)
2545 		printf("Cipher %s\n", cipher_name(o->cipher));
2546 
2547 	/* oControlPersist */
2548 	if (o->control_persist == 0 || o->control_persist_timeout == 0)
2549 		dump_cfg_fmtint(oControlPersist, o->control_persist);
2550 	else
2551 		dump_cfg_int(oControlPersist, o->control_persist_timeout);
2552 
2553 	/* oEscapeChar */
2554 	if (o->escape_char == SSH_ESCAPECHAR_NONE)
2555 		printf("escapechar none\n");
2556 	else {
2557 		vis(vbuf, o->escape_char, VIS_WHITE, 0);
2558 		printf("escapechar %s\n", vbuf);
2559 	}
2560 
2561 	/* oIPQoS */
2562 	printf("ipqos %s ", iptos2str(o->ip_qos_interactive));
2563 	printf("%s\n", iptos2str(o->ip_qos_bulk));
2564 
2565 	/* oRekeyLimit */
2566 	printf("rekeylimit %llu %d\n",
2567 	    (unsigned long long)o->rekey_limit, o->rekey_interval);
2568 
2569 	/* oStreamLocalBindMask */
2570 	printf("streamlocalbindmask 0%o\n",
2571 	    o->fwd_opts.streamlocal_bind_mask);
2572 }
2573