Home | History | Annotate | Line # | Download | only in dist
readconf.c revision 1.53
      1 /*	$NetBSD: readconf.c,v 1.53 2026/10/07 17:32:08 christos Exp $	*/
      2 /* $OpenBSD: readconf.c,v 1.419 2026/10/05 06:03:40 dtucker Exp $ */
      3 
      4 /*
      5  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      6  * Copyright (c) 1995 Tatu Ylonen <ylo (at) 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.53 2026/10/07 17:32:08 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 <net/if.h>
     26 #include <netinet/in.h>
     27 #include <netinet/ip.h>
     28 
     29 #include <ctype.h>
     30 #include <errno.h>
     31 #include <glob.h>
     32 #include <ifaddrs.h>
     33 #include <limits.h>
     34 #include <netdb.h>
     35 #include <paths.h>
     36 #include <pwd.h>
     37 #include <signal.h>
     38 #include <stdio.h>
     39 #include <string.h>
     40 #include <stdarg.h>
     41 #include <unistd.h>
     42 #include <util.h>
     43 #include <vis.h>
     44 
     45 #include "xmalloc.h"
     46 #include "ssh.h"
     47 #include "cipher.h"
     48 #include "pathnames.h"
     49 #include "log.h"
     50 #include "sshkey.h"
     51 #include "misc.h"
     52 #include "readconf.h"
     53 #include "match.h"
     54 #include "kex.h"
     55 #include "mac.h"
     56 #include "myproposal.h"
     57 #include "digest.h"
     58 #include "version.h"
     59 #include "sshbuf.h"
     60 #include "fmt_scaled.h"
     61 
     62 /* Format of the configuration file:
     63 
     64    # Configuration data is parsed as follows:
     65    #  1. command line options
     66    #  2. user-specific file
     67    #  3. system-wide file
     68    # Any configuration value is only changed the first time it is set.
     69    # Thus, host-specific definitions should be at the beginning of the
     70    # configuration file, and defaults at the end.
     71 
     72    # Host-specific declarations.  These may override anything above.  A single
     73    # host may match multiple declarations; these are processed in the order
     74    # that they are given in.
     75 
     76    Host *.ngs.fi ngs.fi
     77      User foo
     78 
     79    Host fake.com
     80      Hostname another.host.name.real.org
     81      User blaah
     82      Port 34289
     83      ForwardX11 no
     84      ForwardAgent no
     85 
     86    Host books.com
     87      RemoteForward 9999 shadows.cs.hut.fi:9999
     88      Ciphers 3des-cbc
     89 
     90    Host fascist.blob.com
     91      Port 23123
     92      User tylonen
     93      PasswordAuthentication no
     94 
     95    Host puukko.hut.fi
     96      User t35124p
     97      ProxyCommand ssh-proxy %h %p
     98 
     99    Host *.fr
    100      PublicKeyAuthentication no
    101 
    102    Host *.su
    103      Ciphers aes128-ctr
    104      PasswordAuthentication no
    105 
    106    Host vpn.fake.com
    107      Tunnel yes
    108      TunnelDevice 3
    109 
    110    # Defaults for various options
    111    Host *
    112      ForwardAgent no
    113      ForwardX11 no
    114      PasswordAuthentication yes
    115      StrictHostKeyChecking yes
    116      TcpKeepAlive no
    117      IdentityFile ~/.ssh/identity
    118      Port 22
    119      EscapeChar ~
    120 
    121 */
    122 
    123 static int read_config_file_depth(const char *filename, struct passwd *pw,
    124     const char *host, const char *original_host, const char *remote_command,
    125     Options *options, int flags, int *activep, int *want_final_pass, int depth);
    126 static int process_config_line_depth(Options *options, struct passwd *pw,
    127     const char *host, const char *original_host, const char *remote_command,
    128     char *line, const char *filename, int linenum, int *activep, int flags,
    129     int *want_final_pass, int depth);
    130 
    131 /* Keyword tokens. */
    132 
    133 typedef enum {
    134 	oBadOption,
    135 	oHost, oMatch, oInclude, oTag,
    136 	oForwardAgent, oForwardX11, oForwardX11Trusted, oForwardX11Timeout,
    137 	oGatewayPorts, oExitOnForwardFailure,
    138 	oPasswordAuthentication,
    139 	oXAuthLocation,
    140 #if defined(KRB4) || defined(KRB5)
    141 	oKerberosAuthentication,
    142 #endif
    143 #if defined(AFS) || defined(KRB5)
    144 	oKerberosTgtPassing,
    145 #endif
    146 #ifdef AFS
    147 	oAFSTokenPassing,
    148 #endif
    149 	oIdentityFile, oHostname, oPort, oRemoteForward, oLocalForward,
    150 	oPermitRemoteOpen,
    151 	oCertificateFile, oAddKeysToAgent, oIdentityAgent,
    152 	oUser, oEscapeChar, oProxyCommand,
    153 	oGlobalKnownHostsFile, oUserKnownHostsFile, oConnectionAttempts,
    154 	oBatchMode, oCheckHostIP, oStrictHostKeyChecking, oCompression,
    155 	oTCPKeepAlive, oNumberOfPasswordPrompts,
    156 	oLogFacility, oLogLevel, oLogVerbose, oCiphers, oMacs,
    157 	oPubkeyAuthentication,
    158 	oKbdInteractiveAuthentication, oKbdInteractiveDevices, oHostKeyAlias,
    159 	oDynamicForward, oPreferredAuthentications, oHostbasedAuthentication,
    160 	oHostKeyAlgorithms, oBindAddress, oBindInterface, oPKCS11Provider,
    161 	oIPv6PreferTemporary,
    162 	oClearAllForwardings, oNoHostAuthenticationForLocalhost,
    163 	oEnableSSHKeysign, oRekeyLimit, oVerifyHostKeyDNS, oConnectTimeout,
    164 	oAddressFamily, oGssAuthentication, oGssDelegateCreds,
    165 	oServerAliveInterval, oServerAliveCountMax, oIdentitiesOnly,
    166 	oSendEnv, oSetEnv, oControlPath, oControlMaster, oControlPersist,
    167 	oHashKnownHosts,
    168 	oTunnel, oTunnelDevice,
    169 	oLocalCommand, oPermitLocalCommand, oRemoteCommand,
    170 	oVisualHostKey,
    171 	oKexAlgorithms, oIPQoS, oRequestTTY, oSessionType, oStdinNull,
    172 	oForkAfterAuthentication, oIgnoreUnknown, oProxyUseFdpass,
    173 	oCanonicalDomains, oCanonicalizeHostname, oCanonicalizeMaxDots,
    174 	oCanonicalizeFallbackLocal, oCanonicalizePermittedCNAMEs,
    175 	oStreamLocalBindMask, oStreamLocalBindUnlink, oRevokedHostKeys,
    176 	oFingerprintHash, oUpdateHostkeys, oHostbasedAcceptedAlgorithms,
    177 	oPubkeyAcceptedAlgorithms, oCASignatureAlgorithms, oProxyJump,
    178 	oSecurityKeyProvider, oKnownHostsCommand, oRequiredRSASize,
    179 	oEnableEscapeCommandline, oObscureKeystrokeTiming, oChannelTimeout,
    180 	oVersionAddendum, oRefuseConnection, oWarnWeakCrypto,
    181 	oNoneEnabled, oTcpRcvBufPoll, oTcpRcvBuf, oNoneSwitch, oHPNDisabled,
    182 	oHPNBufferSize,
    183 	oSendVersionFirst,
    184 	oIgnore, oIgnoredUnknownOption, oDeprecated, oUnsupported
    185 } OpCodes;
    186 
    187 /* Textual representations of the tokens. */
    188 
    189 static struct {
    190 	const char *name;
    191 	OpCodes opcode;
    192 } keywords[] = {
    193 	/* Deprecated options */
    194 	{ "protocol", oIgnore }, /* NB. silently ignored */
    195 	{ "cipher", oDeprecated },
    196 	{ "fallbacktorsh", oDeprecated },
    197 	{ "globalknownhostsfile2", oDeprecated },
    198 	{ "rhostsauthentication", oDeprecated },
    199 	{ "userknownhostsfile2", oDeprecated },
    200 	{ "useroaming", oDeprecated },
    201 	{ "usersh", oDeprecated },
    202 	{ "useprivilegedport", oDeprecated },
    203 
    204 	/* Unsupported options */
    205 #ifdef AFS
    206 	{ "afstokenpassing", oAFSTokenPassing },
    207 #else
    208 	{ "afstokenpassing", oUnsupported },
    209 #endif
    210 #if defined(KRB4) || defined(KRB5)
    211 	{ "kerberosauthentication", oKerberosAuthentication },
    212 #else
    213 	{ "kerberosauthentication", oUnsupported },
    214 #endif
    215 #if defined(AFS) || defined(KRB5)
    216 	{ "kerberostgtpassing", oKerberosTgtPassing },
    217 	{ "kerberos5tgtpassing", oKerberosTgtPassing },		/* alias */
    218 	{ "kerberos4tgtpassing", oKerberosTgtPassing },		/* alias */
    219 #else
    220 	{ "kerberostgtpassing", oUnsupported },
    221 	{ "kerberos5tgtpassing", oUnsupported },
    222 	{ "kerberos4tgtpassing", oUnsupported },
    223 #endif
    224 	{ "rsaauthentication", oUnsupported },
    225 	{ "rhostsrsaauthentication", oUnsupported },
    226 	{ "compressionlevel", oUnsupported },
    227 
    228 	/* Sometimes-unsupported options */
    229 #if defined(GSSAPI)
    230 	{ "gssapiauthentication", oGssAuthentication },
    231 	{ "gssapidelegatecredentials", oGssDelegateCreds },
    232 # else
    233 	{ "gssapiauthentication", oUnsupported },
    234 	{ "gssapidelegatecredentials", oUnsupported },
    235 #endif
    236 #ifdef ENABLE_PKCS11
    237 	{ "pkcs11provider", oPKCS11Provider },
    238 	{ "smartcarddevice", oPKCS11Provider },
    239 # else
    240 	{ "smartcarddevice", oUnsupported },
    241 	{ "pkcs11provider", oUnsupported },
    242 #endif
    243 
    244 	{ "forwardagent", oForwardAgent },
    245 	{ "forwardx11", oForwardX11 },
    246 	{ "forwardx11trusted", oForwardX11Trusted },
    247 	{ "forwardx11timeout", oForwardX11Timeout },
    248 	{ "exitonforwardfailure", oExitOnForwardFailure },
    249 	{ "xauthlocation", oXAuthLocation },
    250 	{ "gatewayports", oGatewayPorts },
    251 	{ "passwordauthentication", oPasswordAuthentication },
    252 	{ "kbdinteractiveauthentication", oKbdInteractiveAuthentication },
    253 	{ "kbdinteractivedevices", oKbdInteractiveDevices },
    254 	{ "challengeresponseauthentication", oKbdInteractiveAuthentication }, /* alias */
    255 	{ "skeyauthentication", oKbdInteractiveAuthentication }, /* alias */
    256 	{ "tisauthentication", oKbdInteractiveAuthentication },  /* alias */
    257 	{ "pubkeyauthentication", oPubkeyAuthentication },
    258 	{ "dsaauthentication", oPubkeyAuthentication },		    /* alias */
    259 	{ "hostbasedauthentication", oHostbasedAuthentication },
    260 #if defined(GSSAPI)
    261 	{ "gssapiauthentication", oGssAuthentication },
    262 	{ "gssapidelegatecredentials", oGssDelegateCreds },
    263 #else
    264 	{ "gssapiauthentication", oUnsupported },
    265 	{ "gssapidelegatecredentials", oUnsupported },
    266 #endif
    267 	{ "identityfile", oIdentityFile },
    268 	{ "identityfile2", oIdentityFile },			/* obsolete */
    269 	{ "identitiesonly", oIdentitiesOnly },
    270 	{ "certificatefile", oCertificateFile },
    271 	{ "addkeystoagent", oAddKeysToAgent },
    272 	{ "identityagent", oIdentityAgent },
    273 	{ "hostname", oHostname },
    274 	{ "hostkeyalias", oHostKeyAlias },
    275 	{ "proxycommand", oProxyCommand },
    276 	{ "port", oPort },
    277 	{ "ciphers", oCiphers },
    278 	{ "macs", oMacs },
    279 	{ "remoteforward", oRemoteForward },
    280 	{ "localforward", oLocalForward },
    281 	{ "permitremoteopen", oPermitRemoteOpen },
    282 	{ "user", oUser },
    283 	{ "host", oHost },
    284 	{ "match", oMatch },
    285 	{ "tag", oTag },
    286 	{ "escapechar", oEscapeChar },
    287 	{ "globalknownhostsfile", oGlobalKnownHostsFile },
    288 	{ "userknownhostsfile", oUserKnownHostsFile },
    289 	{ "connectionattempts", oConnectionAttempts },
    290 	{ "batchmode", oBatchMode },
    291 	{ "checkhostip", oCheckHostIP },
    292 	{ "stricthostkeychecking", oStrictHostKeyChecking },
    293 	{ "compression", oCompression },
    294 	{ "tcpkeepalive", oTCPKeepAlive },
    295 	{ "keepalive", oTCPKeepAlive },				/* obsolete */
    296 	{ "numberofpasswordprompts", oNumberOfPasswordPrompts },
    297 	{ "syslogfacility", oLogFacility },
    298 	{ "loglevel", oLogLevel },
    299 	{ "logverbose", oLogVerbose },
    300 	{ "dynamicforward", oDynamicForward },
    301 	{ "preferredauthentications", oPreferredAuthentications },
    302 	{ "hostkeyalgorithms", oHostKeyAlgorithms },
    303 	{ "casignaturealgorithms", oCASignatureAlgorithms },
    304 	{ "bindaddress", oBindAddress },
    305 	{ "bindinterface", oBindInterface },
    306 	{ "ipv6prefertemporary", oIPv6PreferTemporary },
    307 	{ "clearallforwardings", oClearAllForwardings },
    308 	{ "enablesshkeysign", oEnableSSHKeysign },
    309 	{ "verifyhostkeydns", oVerifyHostKeyDNS },
    310 	{ "nohostauthenticationforlocalhost", oNoHostAuthenticationForLocalhost },
    311 	{ "rekeylimit", oRekeyLimit },
    312 	{ "connecttimeout", oConnectTimeout },
    313 	{ "addressfamily", oAddressFamily },
    314 	{ "serveraliveinterval", oServerAliveInterval },
    315 	{ "serveralivecountmax", oServerAliveCountMax },
    316 	{ "sendenv", oSendEnv },
    317 	{ "setenv", oSetEnv },
    318 	{ "controlpath", oControlPath },
    319 	{ "controlmaster", oControlMaster },
    320 	{ "controlpersist", oControlPersist },
    321 	{ "hashknownhosts", oHashKnownHosts },
    322 	{ "include", oInclude },
    323 	{ "tunnel", oTunnel },
    324 	{ "tunneldevice", oTunnelDevice },
    325 	{ "localcommand", oLocalCommand },
    326 	{ "permitlocalcommand", oPermitLocalCommand },
    327 	{ "remotecommand", oRemoteCommand },
    328 	{ "visualhostkey", oVisualHostKey },
    329 	{ "kexalgorithms", oKexAlgorithms },
    330 	{ "ipqos", oIPQoS },
    331 	{ "requesttty", oRequestTTY },
    332 	{ "sessiontype", oSessionType },
    333 	{ "stdinnull", oStdinNull },
    334 	{ "forkafterauthentication", oForkAfterAuthentication },
    335 	{ "proxyusefdpass", oProxyUseFdpass },
    336 	{ "canonicaldomains", oCanonicalDomains },
    337 	{ "canonicalizefallbacklocal", oCanonicalizeFallbackLocal },
    338 	{ "canonicalizehostname", oCanonicalizeHostname },
    339 	{ "canonicalizemaxdots", oCanonicalizeMaxDots },
    340 	{ "canonicalizepermittedcnames", oCanonicalizePermittedCNAMEs },
    341 	{ "streamlocalbindmask", oStreamLocalBindMask },
    342 	{ "streamlocalbindunlink", oStreamLocalBindUnlink },
    343 	{ "revokedhostkeys", oRevokedHostKeys },
    344 	{ "fingerprinthash", oFingerprintHash },
    345 	{ "updatehostkeys", oUpdateHostkeys },
    346 	{ "hostbasedacceptedalgorithms", oHostbasedAcceptedAlgorithms },
    347 	{ "hostbasedkeytypes", oHostbasedAcceptedAlgorithms }, /* obsolete */
    348 	{ "pubkeyacceptedalgorithms", oPubkeyAcceptedAlgorithms },
    349 	{ "pubkeyacceptedkeytypes", oPubkeyAcceptedAlgorithms }, /* obsolete */
    350 	{ "proxyjump", oProxyJump },
    351 	{ "noneenabled", oNoneEnabled },
    352 	{ "tcprcvbufpoll", oTcpRcvBufPoll },
    353 	{ "tcprcvbuf", oTcpRcvBuf },
    354 	{ "noneswitch", oNoneSwitch },
    355 	{ "hpndisabled", oHPNDisabled },
    356 	{ "hpnbuffersize", oHPNBufferSize },
    357 	{ "sendversionfirst", oSendVersionFirst },
    358 	{ "ignoreunknown", oIgnoreUnknown },
    359 	{ "proxyjump", oProxyJump },
    360 	{ "securitykeyprovider", oSecurityKeyProvider },
    361 	{ "knownhostscommand", oKnownHostsCommand },
    362 	{ "requiredrsasize", oRequiredRSASize },
    363 	{ "enableescapecommandline", oEnableEscapeCommandline },
    364 	{ "obscurekeystroketiming", oObscureKeystrokeTiming },
    365 	{ "channeltimeout", oChannelTimeout },
    366 	{ "versionaddendum", oVersionAddendum },
    367 	{ "refuseconnection", oRefuseConnection },
    368 	{ "warnweakcrypto", oWarnWeakCrypto },
    369 
    370 	{ NULL, oBadOption }
    371 };
    372 
    373 static const char *lookup_opcode_name(OpCodes code);
    374 
    375 const char *
    376 kex_default_pk_alg(void)
    377 {
    378 	static char *pkalgs;
    379 
    380 	if (pkalgs == NULL) {
    381 		char *all_key;
    382 
    383 		all_key = sshkey_alg_list(0, 0, 1, ',');
    384 		pkalgs = match_filter_allowlist(KEX_DEFAULT_PK_ALG, all_key);
    385 		free(all_key);
    386 	}
    387 	return pkalgs;
    388 }
    389 
    390 char *
    391 ssh_connection_hash(const char *thishost, const char *host, const char *portstr,
    392     const char *user, const char *jumphost)
    393 {
    394 	struct ssh_digest_ctx *md;
    395 	u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
    396 
    397 	if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
    398 	    ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
    399 	    ssh_digest_update(md, host, strlen(host)) < 0 ||
    400 	    ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
    401 	    ssh_digest_update(md, user, strlen(user)) < 0 ||
    402 	    ssh_digest_update(md, jumphost, strlen(jumphost)) < 0 ||
    403 	    ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
    404 		fatal_f("mux digest failed");
    405 	ssh_digest_free(md);
    406 	return tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
    407 }
    408 
    409 /*
    410  * Adds a local TCP/IP port forward to options.  Never returns if there is an
    411  * error.
    412  */
    413 
    414 void
    415 add_local_forward(Options *options, const struct Forward *newfwd)
    416 {
    417 	struct Forward *fwd;
    418 	int i;
    419 
    420 	/* Don't add duplicates */
    421 	for (i = 0; i < options->num_local_forwards; i++) {
    422 		if (forward_equals(newfwd, options->local_forwards + i))
    423 			return;
    424 	}
    425 	options->local_forwards = xreallocarray(options->local_forwards,
    426 	    options->num_local_forwards + 1,
    427 	    sizeof(*options->local_forwards));
    428 	fwd = &options->local_forwards[options->num_local_forwards++];
    429 
    430 	fwd->listen_host = newfwd->listen_host;
    431 	fwd->listen_port = newfwd->listen_port;
    432 	fwd->listen_path = newfwd->listen_path;
    433 	fwd->connect_host = newfwd->connect_host;
    434 	fwd->connect_port = newfwd->connect_port;
    435 	fwd->connect_path = newfwd->connect_path;
    436 }
    437 
    438 /*
    439  * Adds a remote TCP/IP port forward to options.  Never returns if there is
    440  * an error.
    441  */
    442 
    443 void
    444 add_remote_forward(Options *options, const struct Forward *newfwd)
    445 {
    446 	struct Forward *fwd;
    447 	int i;
    448 
    449 	/* Don't add duplicates */
    450 	for (i = 0; i < options->num_remote_forwards; i++) {
    451 		if (forward_equals(newfwd, options->remote_forwards + i))
    452 			return;
    453 	}
    454 	options->remote_forwards = xreallocarray(options->remote_forwards,
    455 	    options->num_remote_forwards + 1,
    456 	    sizeof(*options->remote_forwards));
    457 	fwd = &options->remote_forwards[options->num_remote_forwards++];
    458 
    459 	fwd->listen_host = newfwd->listen_host;
    460 	fwd->listen_port = newfwd->listen_port;
    461 	fwd->listen_path = newfwd->listen_path;
    462 	fwd->connect_host = newfwd->connect_host;
    463 	fwd->connect_port = newfwd->connect_port;
    464 	fwd->connect_path = newfwd->connect_path;
    465 	fwd->handle = newfwd->handle;
    466 	fwd->allocated_port = 0;
    467 }
    468 
    469 static void
    470 clear_forwardings(Options *options)
    471 {
    472 	int i;
    473 
    474 	for (i = 0; i < options->num_local_forwards; i++) {
    475 		free(options->local_forwards[i].listen_host);
    476 		free(options->local_forwards[i].listen_path);
    477 		free(options->local_forwards[i].connect_host);
    478 		free(options->local_forwards[i].connect_path);
    479 	}
    480 	if (options->num_local_forwards > 0) {
    481 		free(options->local_forwards);
    482 		options->local_forwards = NULL;
    483 	}
    484 	options->num_local_forwards = 0;
    485 	for (i = 0; i < options->num_remote_forwards; i++) {
    486 		free(options->remote_forwards[i].listen_host);
    487 		free(options->remote_forwards[i].listen_path);
    488 		free(options->remote_forwards[i].connect_host);
    489 		free(options->remote_forwards[i].connect_path);
    490 	}
    491 	if (options->num_remote_forwards > 0) {
    492 		free(options->remote_forwards);
    493 		options->remote_forwards = NULL;
    494 	}
    495 	options->num_remote_forwards = 0;
    496 	options->tun_open = SSH_TUNMODE_NO;
    497 }
    498 
    499 void
    500 add_certificate_file(Options *options, const char *path, int userprovided)
    501 {
    502 	int i;
    503 
    504 	if (options->num_certificate_files >= SSH_MAX_CERTIFICATE_FILES)
    505 		fatal("Too many certificate files specified (max %d)",
    506 		    SSH_MAX_CERTIFICATE_FILES);
    507 
    508 	/* Avoid registering duplicates */
    509 	for (i = 0; i < options->num_certificate_files; i++) {
    510 		if (options->certificate_file_userprovided[i] == userprovided &&
    511 		    strcmp(options->certificate_files[i], path) == 0) {
    512 			debug2_f("ignoring duplicate key %s", path);
    513 			return;
    514 		}
    515 	}
    516 
    517 	options->certificate_file_userprovided[options->num_certificate_files] =
    518 	    userprovided;
    519 	options->certificate_files[options->num_certificate_files++] =
    520 	    xstrdup(path);
    521 }
    522 
    523 void
    524 add_identity_file(Options *options, const char *dir, const char *filename,
    525     int userprovided)
    526 {
    527 	char *path;
    528 	int i;
    529 
    530 	if (options->num_identity_files >= SSH_MAX_IDENTITY_FILES)
    531 		fatal("Too many identity files specified (max %d)",
    532 		    SSH_MAX_IDENTITY_FILES);
    533 
    534 	if (dir == NULL) /* no dir, filename is absolute */
    535 		path = xstrdup(filename);
    536 	else if (xasprintf(&path, "%s%s", dir, filename) >= PATH_MAX)
    537 		fatal("Identity file path %s too long", path);
    538 
    539 	/* Avoid registering duplicates */
    540 	for (i = 0; i < options->num_identity_files; i++) {
    541 		if (options->identity_file_userprovided[i] == userprovided &&
    542 		    strcmp(options->identity_files[i], path) == 0) {
    543 			debug2_f("ignoring duplicate key %s", path);
    544 			free(path);
    545 			return;
    546 		}
    547 	}
    548 
    549 	options->identity_file_userprovided[options->num_identity_files] =
    550 	    userprovided;
    551 	options->identity_files[options->num_identity_files++] = path;
    552 }
    553 
    554 int
    555 default_ssh_port(void)
    556 {
    557 	static int port;
    558 	struct servent *sp;
    559 
    560 	if (port == 0) {
    561 		sp = getservbyname(SSH_SERVICE_NAME, "tcp");
    562 		port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
    563 	}
    564 	return port;
    565 }
    566 
    567 /*
    568  * Execute a command in a shell.
    569  * Return its exit status or -1 on abnormal exit.
    570  */
    571 static int
    572 execute_in_shell(const char *cmd)
    573 {
    574 	const char *shell;
    575 	pid_t pid;
    576 	int status;
    577 
    578 	if ((shell = getenv("SHELL")) == NULL)
    579 		shell = _PATH_BSHELL;
    580 
    581 	if (access(shell, X_OK) == -1) {
    582 		fatal("Shell \"%s\" is not executable: %s",
    583 		    shell, strerror(errno));
    584 	}
    585 
    586 	debug("Executing command: '%.500s'", cmd);
    587 
    588 	/* Fork and execute the command. */
    589 	if ((pid = fork()) == 0) {
    590 		char *argv[4];
    591 
    592 		if (stdfd_devnull(1, 1, 0) == -1)
    593 			fatal_f("stdfd_devnull failed");
    594 		closefrom(STDERR_FILENO + 1);
    595 
    596 		argv[0] = __UNCONST(shell);
    597 		argv[1] = __UNCONST("-c");
    598 		argv[2] = xstrdup(cmd);
    599 		argv[3] = NULL;
    600 
    601 		execv(argv[0], argv);
    602 		error("Unable to execute '%.100s': %s", cmd, strerror(errno));
    603 		/* Die with signal to make this error apparent to parent. */
    604 		ssh_signal(SIGTERM, SIG_DFL);
    605 		kill(getpid(), SIGTERM);
    606 		_exit(1);
    607 	}
    608 	/* Parent. */
    609 	if (pid == -1)
    610 		fatal_f("fork: %.100s", strerror(errno));
    611 
    612 	while (waitpid(pid, &status, 0) == -1) {
    613 		if (errno != EINTR && errno != EAGAIN)
    614 			fatal_f("waitpid: %s", strerror(errno));
    615 	}
    616 	if (!WIFEXITED(status)) {
    617 		error("command '%.100s' exited abnormally", cmd);
    618 		return -1;
    619 	}
    620 	debug3("command returned status %d", WEXITSTATUS(status));
    621 	return WEXITSTATUS(status);
    622 }
    623 
    624 /*
    625  * Check whether a local network interface address appears in CIDR pattern-
    626  * list 'addrlist'. Returns 1 if matched or 0 otherwise.
    627  */
    628 static int
    629 check_match_ifaddrs(const char *addrlist)
    630 {
    631 	struct ifaddrs *ifa, *ifaddrs = NULL;
    632 	int r, found = 0;
    633 	char addr[NI_MAXHOST];
    634 	socklen_t salen;
    635 
    636 	if (getifaddrs(&ifaddrs) != 0) {
    637 		error("match localnetwork: getifaddrs failed: %s",
    638 		    strerror(errno));
    639 		return 0;
    640 	}
    641 	for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
    642 		if (ifa->ifa_addr == NULL || ifa->ifa_name == NULL ||
    643 		    (ifa->ifa_flags & IFF_UP) == 0)
    644 			continue;
    645 		switch (ifa->ifa_addr->sa_family) {
    646 		case AF_INET:
    647 			salen = sizeof(struct sockaddr_in);
    648 			break;
    649 		case AF_INET6:
    650 			salen = sizeof(struct sockaddr_in6);
    651 			break;
    652 		case AF_LINK:
    653 			/* ignore */
    654 			continue;
    655 		default:
    656 			debug2_f("interface %s: unsupported address family %d",
    657 			    ifa->ifa_name, ifa->ifa_addr->sa_family);
    658 			continue;
    659 		}
    660 		if ((r = getnameinfo(ifa->ifa_addr, salen, addr, sizeof(addr),
    661 		    NULL, 0, NI_NUMERICHOST)) != 0) {
    662 			debug2_f("interface %s getnameinfo failed: %s",
    663 			    ifa->ifa_name, gai_strerror(r));
    664 			continue;
    665 		}
    666 		debug3_f("interface %s addr %s", ifa->ifa_name, addr);
    667 		if (addr_match_cidr_list(addr, addrlist) == 1) {
    668 			debug3_f("matched interface %s: address %s in %s",
    669 			    ifa->ifa_name, addr, addrlist);
    670 			found = 1;
    671 			break;
    672 		}
    673 	}
    674 	freeifaddrs(ifaddrs);
    675 	return found;
    676 }
    677 
    678 /*
    679  * Expand a "match exec" command or an Include path, caller must free returned
    680  * value.
    681  */
    682 static char *
    683 expand_match_exec_or_include_path(const char *path, Options *options,
    684     struct passwd *pw, const char *host_arg, const char *original_host,
    685     int final_pass, int is_include_path)
    686 {
    687 	char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
    688 	char uidstr[32], *conn_hash_hex, *keyalias, *ruser;
    689 	const char *jmphost;
    690 	char *host, *ret;
    691 	int port;
    692 
    693 	port = options->port <= 0 ? default_ssh_port() : options->port;
    694 	ruser = options->user == NULL ? pw->pw_name : options->user;
    695 	if (final_pass) {
    696 		host = xstrdup(options->hostname);
    697 	} else if (options->hostname != NULL) {
    698 		/* NB. Please keep in sync with ssh.c:main() */
    699 		host = percent_expand(options->hostname,
    700 		    "h", host_arg, (char *)NULL);
    701 	} else {
    702 		host = xstrdup(host_arg);
    703 	}
    704 	if (gethostname(thishost, sizeof(thishost)) == -1)
    705 		fatal("gethostname: %s", strerror(errno));
    706 	jmphost = option_clear_or_none(options->jump_host) ?
    707 	    "" : options->jump_host;
    708 	strlcpy(shorthost, thishost, sizeof(shorthost));
    709 	shorthost[strcspn(thishost, ".")] = '\0';
    710 	snprintf(portstr, sizeof(portstr), "%d", port);
    711 	snprintf(uidstr, sizeof(uidstr), "%llu",
    712 	    (unsigned long long)pw->pw_uid);
    713 	conn_hash_hex = ssh_connection_hash(thishost, host,
    714 	    portstr, ruser, jmphost);
    715 	keyalias = options->host_key_alias ?  options->host_key_alias : host;
    716 
    717 	ret = (is_include_path ? percent_dollar_expand : percent_expand)(path,
    718 	    "C", conn_hash_hex,
    719 	    "L", shorthost,
    720 	    "d", pw->pw_dir,
    721 	    "h", host,
    722 	    "k", keyalias,
    723 	    "l", thishost,
    724 	    "n", original_host,
    725 	    "p", portstr,
    726 	    "r", ruser,
    727 	    "u", pw->pw_name,
    728 	    "i", uidstr,
    729 	    "j", jmphost,
    730 	    (char *)NULL);
    731 	free(host);
    732 	free(conn_hash_hex);
    733 	return ret;
    734 }
    735 
    736 /*
    737  * Parse and execute a Match directive.
    738  */
    739 static int
    740 match_cfg_line(Options *options, const char *full_line, int *acp, char ***avp,
    741     struct passwd *pw, const char *host_arg, const char *original_host,
    742     const char *remote_command, int final_pass, int *want_final_pass,
    743     const char *filename, int linenum)
    744 {
    745 	char *arg, *oattrib = NULL, *attrib = NULL, *cmd, *host, *criteria;
    746 	const char *ruser;
    747 	int r, this_result, result = 1, attributes = 0, negate;
    748 
    749 	/*
    750 	 * Configuration is likely to be incomplete at this point so we
    751 	 * must be prepared to use default values.
    752 	 */
    753 	ruser = options->user == NULL ? pw->pw_name : options->user;
    754 	if (final_pass) {
    755 		host = xstrdup(options->hostname);
    756 	} else if (options->hostname != NULL) {
    757 		/* NB. Please keep in sync with ssh.c:main() */
    758 		host = percent_expand(options->hostname,
    759 		    "h", host_arg, (char *)NULL);
    760 	} else {
    761 		host = xstrdup(host_arg);
    762 	}
    763 
    764 	debug2("checking match for '%s' host %s originally %s",
    765 	    full_line, host, original_host);
    766 	while ((attrib = argv_next(acp, avp)) != NULL) {
    767 		/* Terminate on comment */
    768 		if (*attrib == '#') {
    769 			argv_consume(acp);
    770 			break;
    771 		}
    772 		attrib = oattrib = xstrdup(attrib);
    773 		arg = criteria = NULL;
    774 		this_result = 1;
    775 		if ((negate = (attrib[0] == '!')))
    776 			attrib++;
    777 		/* Criterion "all" has no argument and must appear alone */
    778 		if (strcasecmp(attrib, "all") == 0) {
    779 			if (attributes > 1 ||
    780 			    ((arg = argv_next(acp, avp)) != NULL &&
    781 			    *arg != '\0' && *arg != '#')) {
    782 				error("%.200s line %d: '%s' cannot be combined "
    783 				    "with other Match attributes",
    784 				    filename, linenum, oattrib);
    785 				result = -1;
    786 				goto out;
    787 			}
    788 			if (arg != NULL && *arg == '#')
    789 				argv_consume(acp); /* consume remaining args */
    790 			if (result)
    791 				result = negate ? 0 : 1;
    792 			goto out;
    793 		}
    794 		attributes++;
    795 		/* criteria "final" and "canonical" have no argument */
    796 		if (strcasecmp(attrib, "canonical") == 0 ||
    797 		    strcasecmp(attrib, "final") == 0) {
    798 			/*
    799 			 * If the config requests "Match final" without
    800 			 * negation then remember this so we can perform a
    801 			 * second pass later.
    802 			 */
    803 			if (strcasecmp(attrib, "final") == 0 &&
    804 			    want_final_pass != NULL)
    805 				*want_final_pass |= !negate;
    806 			r = !!final_pass;  /* force bitmask member to boolean */
    807 			if (r == (negate ? 1 : 0))
    808 				this_result = result = 0;
    809 			debug3("%.200s line %d: %smatched '%s'",
    810 			    filename, linenum,
    811 			    this_result ? "" : "not ", oattrib);
    812 			goto next;
    813 		}
    814 
    815 		/* Keep this list in sync with below */
    816 		if (strprefix(attrib, "host=", 1)  != NULL ||
    817 		    strprefix(attrib, "originalhost=", 1) != NULL ||
    818 		    strprefix(attrib, "user=", 1) != NULL ||
    819 		    strprefix(attrib, "localuser=", 1) != NULL ||
    820 		    strprefix(attrib, "localnetwork=", 1) != NULL ||
    821 		    strprefix(attrib, "version=", 1) != NULL ||
    822 		    strprefix(attrib, "tagged=", 1) != NULL ||
    823 		    strprefix(attrib, "command=", 1) != NULL ||
    824 		    strprefix(attrib, "exec=", 1) != NULL) {
    825 			arg = strchr(attrib, '=');
    826 			*(arg++) = '\0';
    827 		} else if ((arg = argv_next(acp, avp)) == NULL) {
    828 			error("%.200s line %d: missing argument for Match '%s'",
    829 			    filename, linenum, oattrib);
    830 			result = -1;
    831 			goto out;
    832 		}
    833 
    834 		/*
    835 		 * All other criteria require an argument, though it may
    836 		 * be the empty string for the "tagged" and "command"
    837 		 * options.
    838 		 */
    839 		if (*arg == '\0' &&
    840 		    strcasecmp(attrib, "tagged") != 0 &&
    841 		    strcasecmp(attrib, "command") != 0)
    842 			arg = NULL;
    843 		if (arg == NULL || *arg == '#') {
    844 			error("Missing Match criteria for %s", attrib);
    845 			result = -1;
    846 			goto out;
    847 		}
    848 		if (strcasecmp(attrib, "host") == 0) {
    849 			criteria = xstrdup(host);
    850 			r = match_hostname(host, arg) == 1;
    851 			if (r == (negate ? 1 : 0))
    852 				this_result = result = 0;
    853 		} else if (strcasecmp(attrib, "originalhost") == 0) {
    854 			criteria = xstrdup(original_host);
    855 			r = match_hostname(original_host, arg) == 1;
    856 			if (r == (negate ? 1 : 0))
    857 				this_result = result = 0;
    858 		} else if (strcasecmp(attrib, "user") == 0) {
    859 			criteria = xstrdup(ruser);
    860 			r = match_pattern_list(ruser, arg, 0) == 1;
    861 			if (r == (negate ? 1 : 0))
    862 				this_result = result = 0;
    863 		} else if (strcasecmp(attrib, "localuser") == 0) {
    864 			criteria = xstrdup(pw->pw_name);
    865 			r = match_pattern_list(pw->pw_name, arg, 0) == 1;
    866 			if (r == (negate ? 1 : 0))
    867 				this_result = result = 0;
    868 		} else if (strcasecmp(attrib, "localnetwork") == 0) {
    869 			if (addr_match_cidr_list(NULL, arg) == -1) {
    870 				/* Error already printed */
    871 				result = -1;
    872 				goto out;
    873 			}
    874 			r = check_match_ifaddrs(arg) == 1;
    875 			if (r == (negate ? 1 : 0))
    876 				this_result = result = 0;
    877 		} else if (strcasecmp(attrib, "version") == 0) {
    878 			criteria = xstrdup(SSH_RELEASE);
    879 			r = match_pattern_list(SSH_RELEASE, arg, 0) == 1;
    880 			if (r == (negate ? 1 : 0))
    881 				this_result = result = 0;
    882 		} else if (strcasecmp(attrib, "tagged") == 0) {
    883 			criteria = xstrdup(options->tag == NULL ? "" :
    884 			    options->tag);
    885 			/* Special case: empty criteria matches empty arg */
    886 			r = (*criteria == '\0') ? *arg == '\0' :
    887 			    match_pattern_list(criteria, arg, 0) == 1;
    888 			if (r == (negate ? 1 : 0))
    889 				this_result = result = 0;
    890 		} else if (strcasecmp(attrib, "command") == 0) {
    891 			criteria = xstrdup(remote_command == NULL ?
    892 			    "" : remote_command);
    893 			/* Special case: empty criteria matches empty arg */
    894 			r = (*criteria == '\0') ? *arg == '\0' :
    895 			    match_pattern_list(criteria, arg, 0) == 1;
    896 			if (r == (negate ? 1 : 0))
    897 				this_result = result = 0;
    898 		} else if (strcasecmp(attrib, "sessiontype") == 0) {
    899 			if (options->session_type == SESSION_TYPE_SUBSYSTEM)
    900 				criteria = xstrdup("subsystem");
    901 			else if (options->session_type == SESSION_TYPE_NONE)
    902 				criteria = xstrdup("none");
    903 			else if (remote_command != NULL &&
    904 			    *remote_command != '\0')
    905 				criteria = xstrdup("exec");
    906 			else
    907 				criteria = xstrdup("shell");
    908 			r = match_pattern_list(criteria, arg, 0) == 1;
    909 			if (r == (negate ? 1 : 0))
    910 				this_result = result = 0;
    911 		} else if (strcasecmp(attrib, "exec") == 0) {
    912 			if ((cmd = expand_match_exec_or_include_path(arg,
    913 			    options, pw, host_arg, original_host,
    914 			    final_pass, 0)) == NULL) {
    915 				fatal("%.200s line %d: failed to expand match "
    916 				    "exec '%.100s'", filename, linenum, arg);
    917 			}
    918 			if (result != 1) {
    919 				/* skip execution if prior predicate failed */
    920 				debug3("%.200s line %d: skipped exec "
    921 				    "\"%.100s\"", filename, linenum, cmd);
    922 				free(cmd);
    923 				goto next;
    924 			}
    925 			r = execute_in_shell(cmd);
    926 			if (r == -1) {
    927 				fatal("%.200s line %d: match exec "
    928 				    "'%.100s' error", filename,
    929 				    linenum, cmd);
    930 			}
    931 			criteria = xstrdup(cmd);
    932 			free(cmd);
    933 			/* Force exit status to boolean */
    934 			r = r == 0;
    935 			if (r == (negate ? 1 : 0))
    936 				this_result = result = 0;
    937 		} else {
    938 			error("Unsupported Match attribute %s", attrib);
    939 			result = -1;
    940 			goto out;
    941 		}
    942 		debug3("%.200s line %d: %smatched '%s%s%.100s%s' ",
    943 		    filename, linenum, this_result ? "": "not ", oattrib,
    944 		    criteria == NULL ? "" : " \"",
    945 		    criteria == NULL ? "" : criteria,
    946 		    criteria == NULL ? "" : "\"");
    947  next:
    948 		free(criteria);
    949 		free(oattrib);
    950 		oattrib = attrib = NULL;
    951 	}
    952 	if (attributes == 0) {
    953 		error("One or more attributes required for Match");
    954 		result = -1;
    955 		goto out;
    956 	}
    957  out:
    958 	if (result != -1)
    959 		debug2("match %sfound", result ? "" : "not ");
    960 	free(oattrib);
    961 	free(host);
    962 	return result;
    963 }
    964 
    965 /* Remove environment variable by pattern */
    966 static void
    967 rm_env(Options *options, const char *arg, const char *filename, int linenum)
    968 {
    969 	u_int i, j, onum_send_env = options->num_send_env;
    970 
    971 	/* Remove an environment variable */
    972 	for (i = 0; i < options->num_send_env; ) {
    973 		if (!match_pattern(options->send_env[i], arg + 1)) {
    974 			i++;
    975 			continue;
    976 		}
    977 		debug3("%s line %d: removing environment %s",
    978 		    filename, linenum, options->send_env[i]);
    979 		free(options->send_env[i]);
    980 		options->send_env[i] = NULL;
    981 		for (j = i; j < options->num_send_env - 1; j++) {
    982 			options->send_env[j] = options->send_env[j + 1];
    983 			options->send_env[j + 1] = NULL;
    984 		}
    985 		options->num_send_env--;
    986 		/* NB. don't increment i */
    987 	}
    988 	if (onum_send_env != options->num_send_env) {
    989 		options->send_env = xrecallocarray(options->send_env,
    990 		    onum_send_env, options->num_send_env,
    991 		    sizeof(*options->send_env));
    992 	}
    993 }
    994 
    995 /*
    996  * Returns the number of the token pointed to by cp or oBadOption.
    997  */
    998 static OpCodes
    999 parse_token(const char *cp, const char *filename, int linenum,
   1000     const char *ignored_unknown)
   1001 {
   1002 	int i;
   1003 
   1004 	for (i = 0; keywords[i].name; i++)
   1005 		if (strcmp(cp, keywords[i].name) == 0)
   1006 			return keywords[i].opcode;
   1007 	if (ignored_unknown != NULL &&
   1008 	    match_pattern_list(cp, ignored_unknown, 1) == 1)
   1009 		return oIgnoredUnknownOption;
   1010 	error("%s: line %d: Bad configuration option: %s",
   1011 	    filename, linenum, cp);
   1012 	return oBadOption;
   1013 }
   1014 
   1015 static void
   1016 free_canon_cnames(struct allowed_cname *cnames, u_int n)
   1017 {
   1018 	u_int i;
   1019 
   1020 	if (cnames == NULL || n == 0)
   1021 		return;
   1022 	for (i = 0; i < n; i++) {
   1023 		free(cnames[i].source_list);
   1024 		free(cnames[i].target_list);
   1025 	}
   1026 	free(cnames);
   1027 }
   1028 
   1029 /* Multistate option parsing */
   1030 struct multistate {
   1031 	const char *key;
   1032 	int value;
   1033 };
   1034 static const struct multistate multistate_flag[] = {
   1035 	{ "true",			1 },
   1036 	{ "false",			0 },
   1037 	{ "yes",			1 },
   1038 	{ "no",				0 },
   1039 	{ NULL, -1 }
   1040 };
   1041 static const struct multistate multistate_yesnoask[] = {
   1042 	{ "true",			1 },
   1043 	{ "false",			0 },
   1044 	{ "yes",			1 },
   1045 	{ "no",				0 },
   1046 	{ "ask",			2 },
   1047 	{ NULL, -1 }
   1048 };
   1049 static const struct multistate multistate_strict_hostkey[] = {
   1050 	{ "true",			SSH_STRICT_HOSTKEY_YES },
   1051 	{ "false",			SSH_STRICT_HOSTKEY_OFF },
   1052 	{ "yes",			SSH_STRICT_HOSTKEY_YES },
   1053 	{ "no",				SSH_STRICT_HOSTKEY_OFF },
   1054 	{ "ask",			SSH_STRICT_HOSTKEY_ASK },
   1055 	{ "off",			SSH_STRICT_HOSTKEY_OFF },
   1056 	{ "accept-new",			SSH_STRICT_HOSTKEY_NEW },
   1057 	{ NULL, -1 }
   1058 };
   1059 static const struct multistate multistate_yesnoaskconfirm[] = {
   1060 	{ "true",			1 },
   1061 	{ "false",			0 },
   1062 	{ "yes",			1 },
   1063 	{ "no",				0 },
   1064 	{ "ask",			2 },
   1065 	{ "confirm",			3 },
   1066 	{ NULL, -1 }
   1067 };
   1068 static const struct multistate multistate_addressfamily[] = {
   1069 	{ "inet",			AF_INET },
   1070 	{ "inet6",			AF_INET6 },
   1071 	{ "any",			AF_UNSPEC },
   1072 	{ NULL, -1 }
   1073 };
   1074 static const struct multistate multistate_controlmaster[] = {
   1075 	{ "true",			SSHCTL_MASTER_YES },
   1076 	{ "yes",			SSHCTL_MASTER_YES },
   1077 	{ "false",			SSHCTL_MASTER_NO },
   1078 	{ "no",				SSHCTL_MASTER_NO },
   1079 	{ "auto",			SSHCTL_MASTER_AUTO },
   1080 	{ "ask",			SSHCTL_MASTER_ASK },
   1081 	{ "autoask",			SSHCTL_MASTER_AUTO_ASK },
   1082 	{ NULL, -1 }
   1083 };
   1084 static const struct multistate multistate_tunnel[] = {
   1085 	{ "ethernet",			SSH_TUNMODE_ETHERNET },
   1086 	{ "point-to-point",		SSH_TUNMODE_POINTOPOINT },
   1087 	{ "true",			SSH_TUNMODE_DEFAULT },
   1088 	{ "yes",			SSH_TUNMODE_DEFAULT },
   1089 	{ "false",			SSH_TUNMODE_NO },
   1090 	{ "no",				SSH_TUNMODE_NO },
   1091 	{ NULL, -1 }
   1092 };
   1093 static const struct multistate multistate_requesttty[] = {
   1094 	{ "true",			REQUEST_TTY_YES },
   1095 	{ "yes",			REQUEST_TTY_YES },
   1096 	{ "false",			REQUEST_TTY_NO },
   1097 	{ "no",				REQUEST_TTY_NO },
   1098 	{ "force",			REQUEST_TTY_FORCE },
   1099 	{ "auto",			REQUEST_TTY_AUTO },
   1100 	{ NULL, -1 }
   1101 };
   1102 static const struct multistate multistate_sessiontype[] = {
   1103 	{ "none",			SESSION_TYPE_NONE },
   1104 	{ "subsystem",			SESSION_TYPE_SUBSYSTEM },
   1105 	{ "default",			SESSION_TYPE_DEFAULT },
   1106 	{ NULL, -1 }
   1107 };
   1108 static const struct multistate multistate_canonicalizehostname[] = {
   1109 	{ "true",			SSH_CANONICALISE_YES },
   1110 	{ "false",			SSH_CANONICALISE_NO },
   1111 	{ "yes",			SSH_CANONICALISE_YES },
   1112 	{ "no",				SSH_CANONICALISE_NO },
   1113 	{ "always",			SSH_CANONICALISE_ALWAYS },
   1114 	{ NULL, -1 }
   1115 };
   1116 static const struct multistate multistate_pubkey_auth[] = {
   1117 	{ "true",			SSH_PUBKEY_AUTH_ALL },
   1118 	{ "false",			SSH_PUBKEY_AUTH_NO },
   1119 	{ "yes",			SSH_PUBKEY_AUTH_ALL },
   1120 	{ "no",				SSH_PUBKEY_AUTH_NO },
   1121 	{ "unbound",			SSH_PUBKEY_AUTH_UNBOUND },
   1122 	{ "host-bound",			SSH_PUBKEY_AUTH_HBOUND },
   1123 	{ NULL, -1 }
   1124 };
   1125 static const struct multistate multistate_compression[] = {
   1126 #ifdef WITH_ZLIB
   1127 	{ "yes",			COMP_DELAYED },
   1128 #endif
   1129 	{ "no",				COMP_NONE },
   1130 	{ NULL, -1 }
   1131 };
   1132 static const struct multistate multistate_keepalives[] = {
   1133 	{ "true",			SSH_KEEPALIVES_TRANSPORT },
   1134 	{ "false",			SSH_KEEPALIVES_OFF },
   1135 	{ "yes",			SSH_KEEPALIVES_TRANSPORT },
   1136 	{ "no",				SSH_KEEPALIVES_OFF },
   1137 	{ "transport",			SSH_KEEPALIVES_TRANSPORT },
   1138 	{ "all",			SSH_KEEPALIVES_ALL },
   1139 	{ NULL, -1 }
   1140 };
   1141 /* XXX this will need to be replaced with a bitmask if we add more flags */
   1142 static const struct multistate multistate_warnweakcrypto[] = {
   1143 	{ "true",			1 },
   1144 	{ "false",			0 },
   1145 	{ "yes",			1 },
   1146 	{ "no",				0 },
   1147 	{ "no-pq-kex",			0 },
   1148 	{ NULL, -1 }
   1149 };
   1150 
   1151 static int
   1152 parse_multistate_value(const char *arg, const char *filename, int linenum,
   1153     const struct multistate *multistate_ptr)
   1154 {
   1155 	int i;
   1156 
   1157 	if (!arg || *arg == '\0') {
   1158 		error("%s line %d: missing argument.", filename, linenum);
   1159 		return -1;
   1160 	}
   1161 	for (i = 0; multistate_ptr[i].key != NULL; i++) {
   1162 		if (strcasecmp(arg, multistate_ptr[i].key) == 0)
   1163 			return multistate_ptr[i].value;
   1164 	}
   1165 	return -1;
   1166 }
   1167 
   1168 /*
   1169  * Processes a single option line as used in the configuration files. This
   1170  * only sets those values that have not already been set.
   1171  */
   1172 int
   1173 process_config_line(Options *options, struct passwd *pw, const char *host,
   1174     const char *original_host, const char *remote_command, char *line,
   1175     const char *filename, int linenum, int *activep, int flags)
   1176 {
   1177 	return process_config_line_depth(options, pw, host, original_host,
   1178 	    remote_command, line, filename, linenum, activep, flags, NULL, 0);
   1179 }
   1180 
   1181 #define WHITESPACE " \t\r\n"
   1182 static int
   1183 process_config_line_depth(Options *options, struct passwd *pw, const char *host,
   1184     const char *original_host, const char *remote_command, char *line,
   1185     const char *filename, int linenum, int *activep, int flags,
   1186     int *want_final_pass, int depth)
   1187 {
   1188 	char *str, **charptr, *endofnumber, *keyword, *arg, *arg2, *p;
   1189 	char **cpptr, ***cppptr, fwdarg[256];
   1190 	u_int i, *uintptr, max_entries = 0;
   1191 	int r, oactive, negated, opcode, *intptr, value, value2, cmdline = 0;
   1192 	int remotefwd, dynamicfwd, ca_only = 0, found = 0;
   1193 	LogLevel *log_level_ptr;
   1194 	SyslogFacility *log_facility_ptr;
   1195 	long long val64;
   1196 	size_t len;
   1197 	struct Forward fwd;
   1198 	const struct multistate *multistate_ptr;
   1199 	glob_t gl;
   1200 	const char *errstr;
   1201 	char **oav = NULL, **av;
   1202 	int oac = 0, ac;
   1203 	int ret = -1;
   1204 	struct allowed_cname *cnames = NULL;
   1205 	u_int ncnames = 0;
   1206 	char **strs = NULL; /* string array arguments; freed implicitly */
   1207 	u_int nstrs = 0;
   1208 
   1209 	if (activep == NULL) { /* We are processing a command line directive */
   1210 		cmdline = 1;
   1211 		activep = &cmdline;
   1212 	}
   1213 
   1214 	/* Strip trailing whitespace. Allow \f (form feed) at EOL only */
   1215 	if ((len = strlen(line)) == 0)
   1216 		return 0;
   1217 	for (len--; len > 0; len--) {
   1218 		if (strchr(WHITESPACE "\f", line[len]) == NULL)
   1219 			break;
   1220 		line[len] = '\0';
   1221 	}
   1222 
   1223 	str = line;
   1224 	/* Get the keyword. (Each line is supposed to begin with a keyword). */
   1225 	if ((keyword = strdelim(&str)) == NULL)
   1226 		return 0;
   1227 	/* Ignore leading whitespace. */
   1228 	if (*keyword == '\0')
   1229 		keyword = strdelim(&str);
   1230 	if (keyword == NULL || !*keyword || *keyword == '\n' || *keyword == '#')
   1231 		return 0;
   1232 	/* Match lowercase keyword */
   1233 	lowercase(keyword);
   1234 
   1235 	/* Prepare to parse remainder of line */
   1236 	if (str != NULL)
   1237 		str += strspn(str, WHITESPACE);
   1238 	if (str == NULL || *str == '\0') {
   1239 		error("%s line %d: no argument after keyword \"%s\"",
   1240 		    filename, linenum, keyword);
   1241 		return -1;
   1242 	}
   1243 	opcode = parse_token(keyword, filename, linenum,
   1244 	    options->ignored_unknown);
   1245 	if (argv_split(str, &oac, &oav, 1) != 0) {
   1246 		error("%s line %d: invalid quotes", filename, linenum);
   1247 		return -1;
   1248 	}
   1249 	ac = oac;
   1250 	av = oav;
   1251 
   1252 	switch (opcode) {
   1253 	case oBadOption:
   1254 		/* don't panic, but count bad options */
   1255 		goto out;
   1256 	case oIgnore:
   1257 		argv_consume(&ac);
   1258 		break;
   1259 	case oIgnoredUnknownOption:
   1260 		debug("%s line %d: Ignored unknown option \"%s\"",
   1261 		    filename, linenum, keyword);
   1262 		argv_consume(&ac);
   1263 		break;
   1264 	case oConnectTimeout:
   1265 		intptr = &options->connection_timeout;
   1266 parse_time:
   1267 		arg = argv_next(&ac, &av);
   1268 		if (!arg || *arg == '\0') {
   1269 			error("%s line %d: missing time value.",
   1270 			    filename, linenum);
   1271 			goto out;
   1272 		}
   1273 		if (strcmp(arg, "none") == 0)
   1274 			value = -1;
   1275 		else if ((value = convtime(arg)) == -1) {
   1276 			error("%s line %d: invalid time value.",
   1277 			    filename, linenum);
   1278 			goto out;
   1279 		}
   1280 		if (*activep && *intptr == -1)
   1281 			*intptr = value;
   1282 		break;
   1283 
   1284 	case oForwardAgent:
   1285 		intptr = &options->forward_agent;
   1286 
   1287 		arg = argv_next(&ac, &av);
   1288 		if (!arg || *arg == '\0') {
   1289 			error("%s line %d: missing argument.",
   1290 			    filename, linenum);
   1291 			goto out;
   1292 		}
   1293 
   1294 		value = -1;
   1295 		multistate_ptr = multistate_flag;
   1296 		for (i = 0; multistate_ptr[i].key != NULL; i++) {
   1297 			if (strcasecmp(arg, multistate_ptr[i].key) == 0) {
   1298 				value = multistate_ptr[i].value;
   1299 				break;
   1300 			}
   1301 		}
   1302 		if (value != -1) {
   1303 			if (*activep && *intptr == -1)
   1304 				*intptr = value;
   1305 			break;
   1306 		}
   1307 		/* ForwardAgent wasn't 'yes' or 'no', assume a path */
   1308 		if (*activep && *intptr == -1)
   1309 			*intptr = 1;
   1310 
   1311 		charptr = &options->forward_agent_sock_path;
   1312 		goto parse_agent_path;
   1313 
   1314 	case oForwardX11:
   1315 		intptr = &options->forward_x11;
   1316  parse_flag:
   1317 		multistate_ptr = multistate_flag;
   1318  parse_multistate:
   1319 		arg = argv_next(&ac, &av);
   1320 		if ((value = parse_multistate_value(arg, filename, linenum,
   1321 		    multistate_ptr)) == -1) {
   1322 			error("%s line %d: unsupported option \"%s\".",
   1323 			    filename, linenum, arg);
   1324 			goto out;
   1325 		}
   1326 		if (*activep && *intptr == -1)
   1327 			*intptr = value;
   1328 		break;
   1329 
   1330 	case oForwardX11Trusted:
   1331 		intptr = &options->forward_x11_trusted;
   1332 		goto parse_flag;
   1333 
   1334 	case oForwardX11Timeout:
   1335 		intptr = &options->forward_x11_timeout;
   1336 		goto parse_time;
   1337 
   1338 	case oGatewayPorts:
   1339 		intptr = &options->fwd_opts.gateway_ports;
   1340 		goto parse_flag;
   1341 
   1342 	case oExitOnForwardFailure:
   1343 		intptr = &options->exit_on_forward_failure;
   1344 		goto parse_flag;
   1345 
   1346 	case oPasswordAuthentication:
   1347 		intptr = &options->password_authentication;
   1348 		goto parse_flag;
   1349 
   1350 	case oKbdInteractiveAuthentication:
   1351 		intptr = &options->kbd_interactive_authentication;
   1352 		goto parse_flag;
   1353 
   1354 	case oKbdInteractiveDevices:
   1355 		charptr = &options->kbd_interactive_devices;
   1356 		goto parse_string;
   1357 
   1358 	case oPubkeyAuthentication:
   1359 		multistate_ptr = multistate_pubkey_auth;
   1360 		intptr = &options->pubkey_authentication;
   1361 		goto parse_multistate;
   1362 
   1363 	case oHostbasedAuthentication:
   1364 		intptr = &options->hostbased_authentication;
   1365 		goto parse_flag;
   1366 
   1367 #if defined(KRB4) || defined(KRB5)
   1368 	case oKerberosAuthentication:
   1369 		intptr = &options->kerberos_authentication;
   1370 		goto parse_flag;
   1371 #endif
   1372 #if defined(AFS) || defined(KRB5)
   1373 	case oKerberosTgtPassing:
   1374 		intptr = &options->kerberos_tgt_passing;
   1375 		goto parse_flag;
   1376 #endif
   1377 
   1378 	case oGssAuthentication:
   1379 		intptr = &options->gss_authentication;
   1380 		goto parse_flag;
   1381 
   1382 #ifdef AFS
   1383 	case oAFSTokenPassing:
   1384 		intptr = &options->afs_token_passing;
   1385  		goto parse_flag;
   1386 #endif
   1387 
   1388 	case oGssDelegateCreds:
   1389 		intptr = &options->gss_deleg_creds;
   1390 		goto parse_flag;
   1391 
   1392 	case oBatchMode:
   1393 		intptr = &options->batch_mode;
   1394 		goto parse_flag;
   1395 
   1396 	case oCheckHostIP:
   1397 		intptr = &options->check_host_ip;
   1398 		goto parse_flag;
   1399 
   1400 	case oNoneEnabled:
   1401 		intptr = &options->none_enabled;
   1402 		goto parse_flag;
   1403 
   1404 	/* we check to see if the command comes from the */
   1405 	/* command line or not. If it does then enable it */
   1406 	/* otherwise fail. NONE should never be a default configuration */
   1407 	case oNoneSwitch:
   1408 		if(strcmp(filename,"command-line")==0)
   1409 		{
   1410 		    intptr = &options->none_switch;
   1411 		    goto parse_flag;
   1412 		} else {
   1413 		    error("NoneSwitch is found in %.200s.\nYou may only use this configuration option from the command line", filename);
   1414 		    error("Continuing...");
   1415 		    debug("NoneSwitch directive found in %.200s.", filename);
   1416 		    return 0;
   1417 	        }
   1418 
   1419 	case oHPNDisabled:
   1420 		intptr = &options->hpn_disabled;
   1421 		goto parse_flag;
   1422 
   1423 	case oHPNBufferSize:
   1424 		intptr = &options->hpn_buffer_size;
   1425 		goto parse_int;
   1426 
   1427 	case oTcpRcvBufPoll:
   1428 		intptr = &options->tcp_rcv_buf_poll;
   1429 		goto parse_flag;
   1430 
   1431 	case oVerifyHostKeyDNS:
   1432 		intptr = &options->verify_host_key_dns;
   1433 		multistate_ptr = multistate_yesnoask;
   1434 		goto parse_multistate;
   1435 
   1436 	case oStrictHostKeyChecking:
   1437 		intptr = &options->strict_host_key_checking;
   1438 		multistate_ptr = multistate_strict_hostkey;
   1439 		goto parse_multistate;
   1440 
   1441 	case oCompression:
   1442 		intptr = &options->compression;
   1443 		multistate_ptr = multistate_compression;
   1444 		goto parse_multistate;
   1445 
   1446 	case oTCPKeepAlive:
   1447 		intptr = &options->tcp_keep_alive;
   1448 		multistate_ptr = multistate_keepalives;
   1449 		goto parse_multistate;
   1450 
   1451 	case oNoHostAuthenticationForLocalhost:
   1452 		intptr = &options->no_host_authentication_for_localhost;
   1453 		goto parse_flag;
   1454 
   1455 	case oNumberOfPasswordPrompts:
   1456 		intptr = &options->number_of_password_prompts;
   1457 		goto parse_int;
   1458 
   1459 	case oRekeyLimit:
   1460 		arg = argv_next(&ac, &av);
   1461 		if (!arg || *arg == '\0') {
   1462 			error("%.200s line %d: Missing argument.", filename,
   1463 			    linenum);
   1464 			goto out;
   1465 		}
   1466 		if (strcmp(arg, "default") == 0) {
   1467 			val64 = 0;
   1468 		} else {
   1469 			if (scan_scaled(arg, &val64) == -1) {
   1470 				error("%.200s line %d: Bad number '%s': %s",
   1471 				    filename, linenum, arg, strerror(errno));
   1472 				goto out;
   1473 			}
   1474 			if (val64 != 0 && val64 < 16) {
   1475 				error("%.200s line %d: RekeyLimit too small",
   1476 				    filename, linenum);
   1477 				goto out;
   1478 			}
   1479 		}
   1480 		if (*activep && options->rekey_limit == -1)
   1481 			options->rekey_limit = val64;
   1482 		if (ac != 0) { /* optional rekey interval present */
   1483 			if (strcmp(av[0], "none") == 0) {
   1484 				(void)argv_next(&ac, &av);	/* discard */
   1485 				break;
   1486 			}
   1487 			intptr = &options->rekey_interval;
   1488 			goto parse_time;
   1489 		}
   1490 		break;
   1491 
   1492 	case oIdentityFile:
   1493 		arg = argv_next(&ac, &av);
   1494 		if (!arg || *arg == '\0') {
   1495 			error("%.200s line %d: Missing argument.",
   1496 			    filename, linenum);
   1497 			goto out;
   1498 		}
   1499 		if (*activep) {
   1500 			intptr = &options->num_identity_files;
   1501 			if (*intptr >= SSH_MAX_IDENTITY_FILES) {
   1502 				error("%.200s line %d: Too many identity files "
   1503 				    "specified (max %d).", filename, linenum,
   1504 				    SSH_MAX_IDENTITY_FILES);
   1505 				goto out;
   1506 			}
   1507 			add_identity_file(options, NULL,
   1508 			    arg, flags & SSHCONF_USERCONF);
   1509 		}
   1510 		break;
   1511 
   1512 	case oCertificateFile:
   1513 		arg = argv_next(&ac, &av);
   1514 		if (!arg || *arg == '\0') {
   1515 			error("%.200s line %d: Missing argument.",
   1516 			    filename, linenum);
   1517 			goto out;
   1518 		}
   1519 		if (*activep) {
   1520 			intptr = &options->num_certificate_files;
   1521 			if (*intptr >= SSH_MAX_CERTIFICATE_FILES) {
   1522 				error("%.200s line %d: Too many certificate "
   1523 				    "files specified (max %d).",
   1524 				    filename, linenum,
   1525 				    SSH_MAX_CERTIFICATE_FILES);
   1526 				goto out;
   1527 			}
   1528 			add_certificate_file(options, arg,
   1529 			    flags & SSHCONF_USERCONF);
   1530 		}
   1531 		break;
   1532 
   1533 	case oXAuthLocation:
   1534 		charptr=&options->xauth_location;
   1535 		goto parse_string;
   1536 
   1537 	case oUser:
   1538 		charptr = &options->user;
   1539 parse_string:
   1540 		arg = argv_next(&ac, &av);
   1541 		if (!arg || *arg == '\0') {
   1542 			error("%.200s line %d: Missing argument.",
   1543 			    filename, linenum);
   1544 			goto out;
   1545 		}
   1546 		if (*activep && *charptr == NULL)
   1547 			*charptr = xstrdup(arg);
   1548 		break;
   1549 
   1550 	case oGlobalKnownHostsFile:
   1551 		cpptr = (char **)&options->system_hostfiles;
   1552 		uintptr = &options->num_system_hostfiles;
   1553 		max_entries = SSH_MAX_HOSTS_FILES;
   1554 parse_char_array:
   1555 		i = 0;
   1556 		value = *uintptr == 0; /* was array empty when we started? */
   1557 		while ((arg = argv_next(&ac, &av)) != NULL) {
   1558 			if (*arg == '\0') {
   1559 				error("%s line %d: keyword %s empty argument",
   1560 				    filename, linenum, keyword);
   1561 				goto out;
   1562 			}
   1563 			/* Allow "none" only in first position */
   1564 			if (strcasecmp(arg, "none") == 0) {
   1565 				if (i > 0 || ac > 0) {
   1566 					error("%s line %d: keyword %s \"none\" "
   1567 					    "argument must appear alone.",
   1568 					    filename, linenum, keyword);
   1569 					goto out;
   1570 				}
   1571 			}
   1572 			i++;
   1573 			if (*activep && value) {
   1574 				if ((*uintptr) >= max_entries) {
   1575 					error("%s line %d: too many %s "
   1576 					    "entries.", filename, linenum,
   1577 					    keyword);
   1578 					goto out;
   1579 				}
   1580 				cpptr[(*uintptr)++] = xstrdup(arg);
   1581 			}
   1582 		}
   1583 		break;
   1584 
   1585 	case oUserKnownHostsFile:
   1586 		cpptr = (char **)&options->user_hostfiles;
   1587 		uintptr = &options->num_user_hostfiles;
   1588 		max_entries = SSH_MAX_HOSTS_FILES;
   1589 		goto parse_char_array;
   1590 
   1591 	case oHostname:
   1592 		charptr = &options->hostname;
   1593 		goto parse_string;
   1594 
   1595 	case oTag:
   1596 		charptr = &options->tag;
   1597 		goto parse_string;
   1598 
   1599 	case oHostKeyAlias:
   1600 		charptr = &options->host_key_alias;
   1601 		goto parse_string;
   1602 
   1603 	case oPreferredAuthentications:
   1604 		charptr = &options->preferred_authentications;
   1605 		goto parse_string;
   1606 
   1607 	case oBindAddress:
   1608 		charptr = &options->bind_address;
   1609 		goto parse_string;
   1610 
   1611 	case oBindInterface:
   1612 		charptr = &options->bind_interface;
   1613 		goto parse_string;
   1614 
   1615 	case oIPv6PreferTemporary:
   1616 		intptr = &options->ipv6_prefer_temporary;
   1617 		goto parse_flag;
   1618 
   1619 	case oPKCS11Provider:
   1620 		charptr = &options->pkcs11_provider;
   1621 		goto parse_string;
   1622 
   1623 	case oSecurityKeyProvider:
   1624 		charptr = &options->sk_provider;
   1625 		goto parse_string;
   1626 
   1627 	case oKnownHostsCommand:
   1628 		charptr = &options->known_hosts_command;
   1629 		goto parse_command;
   1630 
   1631 	case oProxyCommand:
   1632 		charptr = &options->proxy_command;
   1633 parse_command:
   1634 		if (str == NULL) {
   1635 			error("%.200s line %d: Missing argument.",
   1636 			    filename, linenum);
   1637 			goto out;
   1638 		}
   1639 		len = strspn(str, WHITESPACE "=");
   1640 		if (*activep && *charptr == NULL)
   1641 			*charptr = xstrdup(str + len);
   1642 		argv_consume(&ac);
   1643 		break;
   1644 
   1645 	case oProxyJump:
   1646 		if (str == NULL) {
   1647 			error("%.200s line %d: Missing argument.",
   1648 			    filename, linenum);
   1649 			goto out;
   1650 		}
   1651 		len = strspn(str, WHITESPACE "=");
   1652 		/* XXX use argv? */
   1653 		if (parse_jump(str + len, options, cmdline, *activep) == -1) {
   1654 			error("%.200s line %d: Invalid ProxyJump \"%s\"",
   1655 			    filename, linenum, str + len);
   1656 			goto out;
   1657 		}
   1658 		argv_consume(&ac);
   1659 		break;
   1660 
   1661 	case oPort:
   1662 		arg = argv_next(&ac, &av);
   1663 		if (!arg || *arg == '\0') {
   1664 			error("%.200s line %d: Missing argument.",
   1665 			    filename, linenum);
   1666 			goto out;
   1667 		}
   1668 		value = a2port(arg);
   1669 		if (value <= 0) {
   1670 			error("%.200s line %d: Bad port '%s'.",
   1671 			    filename, linenum, arg);
   1672 			goto out;
   1673 		}
   1674 		if (*activep && options->port == -1)
   1675 			options->port = value;
   1676 		break;
   1677 
   1678 	case oConnectionAttempts:
   1679 		intptr = &options->connection_attempts;
   1680 parse_int:
   1681 		arg = argv_next(&ac, &av);
   1682 		if ((errstr = atoi_err(arg, &value)) != NULL) {
   1683 			error("%s line %d: integer value %s.",
   1684 			    filename, linenum, errstr);
   1685 			goto out;
   1686 		}
   1687 		if (*activep && *intptr == -1)
   1688 			*intptr = value;
   1689 		break;
   1690 
   1691 	case oTcpRcvBuf:
   1692 		intptr = &options->tcp_rcv_buf;
   1693 		goto parse_int;
   1694 
   1695 	case oCiphers:
   1696 		arg = argv_next(&ac, &av);
   1697 		if (!arg || *arg == '\0') {
   1698 			error("%.200s line %d: Missing argument.",
   1699 			    filename, linenum);
   1700 			goto out;
   1701 		}
   1702 		if (*arg != '-' &&
   1703 		    !ciphers_valid(*arg == '+' || *arg == '^' ? arg + 1 : arg)){
   1704 			error("%.200s line %d: Bad SSH2 cipher spec '%s'.",
   1705 			    filename, linenum, arg ? arg : "<NONE>");
   1706 			goto out;
   1707 		}
   1708 		if (*activep && options->ciphers == NULL)
   1709 			options->ciphers = xstrdup(arg);
   1710 		break;
   1711 
   1712 	case oMacs:
   1713 		arg = argv_next(&ac, &av);
   1714 		if (!arg || *arg == '\0') {
   1715 			error("%.200s line %d: Missing argument.",
   1716 			    filename, linenum);
   1717 			goto out;
   1718 		}
   1719 		if (*arg != '-' &&
   1720 		    !mac_valid(*arg == '+' || *arg == '^' ? arg + 1 : arg)) {
   1721 			error("%.200s line %d: Bad SSH2 MAC spec '%s'.",
   1722 			    filename, linenum, arg ? arg : "<NONE>");
   1723 			goto out;
   1724 		}
   1725 		if (*activep && options->macs == NULL)
   1726 			options->macs = xstrdup(arg);
   1727 		break;
   1728 
   1729 	case oKexAlgorithms:
   1730 		arg = argv_next(&ac, &av);
   1731 		if (!arg || *arg == '\0') {
   1732 			error("%.200s line %d: Missing argument.",
   1733 			    filename, linenum);
   1734 			goto out;
   1735 		}
   1736 		if (*arg != '-' &&
   1737 		    !kex_names_valid(*arg == '+' || *arg == '^' ?
   1738 		    arg + 1 : arg)) {
   1739 			error("%.200s line %d: Bad SSH2 KexAlgorithms '%s'.",
   1740 			    filename, linenum, arg ? arg : "<NONE>");
   1741 			goto out;
   1742 		}
   1743 		if (*activep && options->kex_algorithms == NULL)
   1744 			options->kex_algorithms = xstrdup(arg);
   1745 		break;
   1746 
   1747 	case oHostKeyAlgorithms:
   1748 		charptr = &options->hostkeyalgorithms;
   1749 		ca_only = 0;
   1750 parse_pubkey_algos:
   1751 		arg = argv_next(&ac, &av);
   1752 		if (!arg || *arg == '\0') {
   1753 			error("%.200s line %d: Missing argument.",
   1754 			    filename, linenum);
   1755 			goto out;
   1756 		}
   1757 		if (*arg != '-' &&
   1758 		    !sshkey_names_valid2(*arg == '+' || *arg == '^' ?
   1759 		    arg + 1 : arg, 1, ca_only)) {
   1760 			error("%s line %d: Bad key types '%s'.",
   1761 			    filename, linenum, arg ? arg : "<NONE>");
   1762 			goto out;
   1763 		}
   1764 		if (*activep && *charptr == NULL)
   1765 			*charptr = xstrdup(arg);
   1766 		break;
   1767 
   1768 	case oCASignatureAlgorithms:
   1769 		charptr = &options->ca_sign_algorithms;
   1770 		ca_only = 1;
   1771 		goto parse_pubkey_algos;
   1772 
   1773 	case oLogLevel:
   1774 		log_level_ptr = &options->log_level;
   1775 		arg = argv_next(&ac, &av);
   1776 		value = log_level_number(arg);
   1777 		if (value == SYSLOG_LEVEL_NOT_SET) {
   1778 			error("%.200s line %d: unsupported log level '%s'",
   1779 			    filename, linenum, arg ? arg : "<NONE>");
   1780 			goto out;
   1781 		}
   1782 		if (*activep && *log_level_ptr == SYSLOG_LEVEL_NOT_SET)
   1783 			*log_level_ptr = (LogLevel) value;
   1784 		break;
   1785 
   1786 	case oLogFacility:
   1787 		log_facility_ptr = &options->log_facility;
   1788 		arg = argv_next(&ac, &av);
   1789 		value = log_facility_number(arg);
   1790 		if (value == SYSLOG_FACILITY_NOT_SET) {
   1791 			error("%.200s line %d: unsupported log facility '%s'",
   1792 			    filename, linenum, arg ? arg : "<NONE>");
   1793 			goto out;
   1794 		}
   1795 		if (*log_facility_ptr == -1)
   1796 			*log_facility_ptr = (SyslogFacility) value;
   1797 		break;
   1798 
   1799 	case oLogVerbose:
   1800 		cppptr = &options->log_verbose;
   1801 		uintptr = &options->num_log_verbose;
   1802 		i = 0;
   1803 		while ((arg = argv_next(&ac, &av)) != NULL) {
   1804 			if (*arg == '\0') {
   1805 				error("%s line %d: keyword %s empty argument",
   1806 				    filename, linenum, keyword);
   1807 				goto out;
   1808 			}
   1809 			/* Allow "none" only in first position */
   1810 			if (strcasecmp(arg, "none") == 0) {
   1811 				if (i > 0 || ac > 0) {
   1812 					error("%s line %d: keyword %s \"none\" "
   1813 					    "argument must appear alone.",
   1814 					    filename, linenum, keyword);
   1815 					goto out;
   1816 				}
   1817 			}
   1818 			i++;
   1819 			if (*activep && *uintptr == 0) {
   1820 				*cppptr = xrecallocarray(*cppptr, *uintptr,
   1821 				    *uintptr + 1, sizeof(**cppptr));
   1822 				(*cppptr)[(*uintptr)++] = xstrdup(arg);
   1823 			}
   1824 		}
   1825 		break;
   1826 
   1827 	case oLocalForward:
   1828 	case oRemoteForward:
   1829 	case oDynamicForward:
   1830 		arg = argv_next(&ac, &av);
   1831 		if (!arg || *arg == '\0') {
   1832 			error("%.200s line %d: Missing argument.",
   1833 			    filename, linenum);
   1834 			goto out;
   1835 		}
   1836 
   1837 		remotefwd = (opcode == oRemoteForward);
   1838 		dynamicfwd = (opcode == oDynamicForward);
   1839 
   1840 		if (!dynamicfwd) {
   1841 			arg2 = argv_next(&ac, &av);
   1842 			if (arg2 == NULL || *arg2 == '\0') {
   1843 				if (remotefwd)
   1844 					dynamicfwd = 1;
   1845 				else {
   1846 					error("%.200s line %d: Missing target "
   1847 					    "argument.", filename, linenum);
   1848 					goto out;
   1849 				}
   1850 			} else {
   1851 				/* construct a string for parse_forward */
   1852 				snprintf(fwdarg, sizeof(fwdarg), "%s:%s", arg,
   1853 				    arg2);
   1854 			}
   1855 		}
   1856 		if (dynamicfwd)
   1857 			strlcpy(fwdarg, arg, sizeof(fwdarg));
   1858 
   1859 		if (parse_forward(&fwd, fwdarg, dynamicfwd, remotefwd) == 0) {
   1860 			error("%.200s line %d: Bad forwarding specification.",
   1861 			    filename, linenum);
   1862 			goto out;
   1863 		}
   1864 
   1865 		if (*activep) {
   1866 			if (remotefwd) {
   1867 				add_remote_forward(options, &fwd);
   1868 			} else {
   1869 				add_local_forward(options, &fwd);
   1870 			}
   1871 		}
   1872 		break;
   1873 
   1874 	case oPermitRemoteOpen:
   1875 		uintptr = &options->num_permitted_remote_opens;
   1876 		cppptr = &options->permitted_remote_opens;
   1877 		found = *uintptr == 0;
   1878 		while ((arg = argv_next(&ac, &av)) != NULL) {
   1879 			arg2 = xstrdup(arg);
   1880 			/* Allow any/none only in first position */
   1881 			if (strcasecmp(arg, "none") == 0 ||
   1882 			    strcasecmp(arg, "any") == 0) {
   1883 				if (nstrs > 0 || ac > 0) {
   1884 					error("%s line %d: keyword %s \"%s\" "
   1885 					    "argument must appear alone.",
   1886 					    filename, linenum, keyword, arg);
   1887 					free(arg2);
   1888 					goto out;
   1889 				}
   1890 			} else {
   1891 				p = hpdelim(&arg);
   1892 				if (p == NULL) {
   1893 					fatal("%s line %d: missing host in %s",
   1894 					    filename, linenum,
   1895 					    lookup_opcode_name(opcode));
   1896 				}
   1897 				p = cleanhostname(p);
   1898 				/*
   1899 				 * don't want to use permitopen_port to avoid
   1900 				 * dependency on channels.[ch] here.
   1901 				 */
   1902 				if (arg == NULL || (strcmp(arg, "*") != 0 &&
   1903 				    a2port(arg) <= 0)) {
   1904 					fatal("%s line %d: bad port number "
   1905 					    "in %s", filename, linenum,
   1906 					    lookup_opcode_name(opcode));
   1907 				}
   1908 			}
   1909 			opt_array_append(filename, linenum,
   1910 			    lookup_opcode_name(opcode),
   1911 			    &strs, &nstrs, arg2);
   1912 			free(arg2);
   1913 		}
   1914 		if (nstrs == 0)
   1915 			fatal("%s line %d: missing %s specification",
   1916 			    filename, linenum, lookup_opcode_name(opcode));
   1917 		if (found && *activep) {
   1918 			*cppptr = strs;
   1919 			*uintptr = nstrs;
   1920 			strs = NULL; /* transferred */
   1921 			nstrs = 0;
   1922 		}
   1923 		break;
   1924 
   1925 	case oClearAllForwardings:
   1926 		intptr = &options->clear_forwardings;
   1927 		goto parse_flag;
   1928 
   1929 	case oHost:
   1930 		if (cmdline) {
   1931 			error("Host directive not supported as a command-line "
   1932 			    "option");
   1933 			goto out;
   1934 		}
   1935 		*activep = 0;
   1936 		arg2 = NULL;
   1937 		while ((arg = argv_next(&ac, &av)) != NULL) {
   1938 			if (*arg == '\0') {
   1939 				error("%s line %d: keyword %s empty argument",
   1940 				    filename, linenum, keyword);
   1941 				goto out;
   1942 			}
   1943 			if ((flags & SSHCONF_NEVERMATCH) != 0) {
   1944 				argv_consume(&ac);
   1945 				break;
   1946 			}
   1947 			negated = *arg == '!';
   1948 			if (negated)
   1949 				arg++;
   1950 			if (match_pattern(host, arg)) {
   1951 				if (negated) {
   1952 					debug("%.200s line %d: Skipping Host "
   1953 					    "block because of negated match "
   1954 					    "for %.100s", filename, linenum,
   1955 					    arg);
   1956 					*activep = 0;
   1957 					argv_consume(&ac);
   1958 					break;
   1959 				}
   1960 				if (!*activep)
   1961 					arg2 = arg; /* logged below */
   1962 				*activep = 1;
   1963 			}
   1964 		}
   1965 		if (*activep)
   1966 			debug("%.200s line %d: Applying options for %.100s",
   1967 			    filename, linenum, arg2);
   1968 		break;
   1969 
   1970 	case oMatch:
   1971 		if (cmdline) {
   1972 			error("Match directive not supported as a command-line "
   1973 			    "option");
   1974 			goto out;
   1975 		}
   1976 		value = match_cfg_line(options, str, &ac, &av, pw, host,
   1977 		    original_host, remote_command, flags & SSHCONF_FINAL,
   1978 		    want_final_pass, filename, linenum);
   1979 		if (value < 0) {
   1980 			error("%.200s line %d: Bad Match condition", filename,
   1981 			    linenum);
   1982 			goto out;
   1983 		}
   1984 		*activep = (flags & SSHCONF_NEVERMATCH) ? 0 : value;
   1985 		break;
   1986 
   1987 	case oEscapeChar:
   1988 		intptr = &options->escape_char;
   1989 		arg = argv_next(&ac, &av);
   1990 		if (!arg || *arg == '\0') {
   1991 			error("%.200s line %d: Missing argument.",
   1992 			    filename, linenum);
   1993 			goto out;
   1994 		}
   1995 		if (strcmp(arg, "none") == 0)
   1996 			value = SSH_ESCAPECHAR_NONE;
   1997 		else if (arg[1] == '\0')
   1998 			value = (u_char) arg[0];
   1999 		else if (arg[0] == '^' && arg[2] == 0 &&
   2000 		    (u_char) arg[1] >= 64 && (u_char) arg[1] < 128)
   2001 			value = (u_char) arg[1] & 31;
   2002 		else {
   2003 			error("%.200s line %d: Bad escape character.",
   2004 			    filename, linenum);
   2005 			goto out;
   2006 		}
   2007 		if (*activep && *intptr == -1)
   2008 			*intptr = value;
   2009 		break;
   2010 
   2011 	case oAddressFamily:
   2012 		intptr = &options->address_family;
   2013 		multistate_ptr = multistate_addressfamily;
   2014 		goto parse_multistate;
   2015 
   2016 	case oEnableSSHKeysign:
   2017 		intptr = &options->enable_ssh_keysign;
   2018 		goto parse_flag;
   2019 
   2020 	case oIdentitiesOnly:
   2021 		intptr = &options->identities_only;
   2022 		goto parse_flag;
   2023 
   2024 	case oServerAliveInterval:
   2025 		intptr = &options->server_alive_interval;
   2026 		goto parse_time;
   2027 
   2028 	case oServerAliveCountMax:
   2029 		intptr = &options->server_alive_count_max;
   2030 		goto parse_int;
   2031 
   2032 	case oSendEnv:
   2033 		/* XXX appends to list; doesn't respect first-match-wins */
   2034 		while ((arg = argv_next(&ac, &av)) != NULL) {
   2035 			if (*arg == '\0' || strchr(arg, '=') != NULL) {
   2036 				error("%s line %d: Invalid environment name.",
   2037 				    filename, linenum);
   2038 				goto out;
   2039 			}
   2040 			found = 1;
   2041 			if (!*activep)
   2042 				continue;
   2043 			if (*arg == '-') {
   2044 				/* Removing an env var */
   2045 				rm_env(options, arg, filename, linenum);
   2046 				continue;
   2047 			}
   2048 			opt_array_append(filename, linenum,
   2049 			    lookup_opcode_name(opcode),
   2050 			    &options->send_env, &options->num_send_env, arg);
   2051 		}
   2052 		if (!found) {
   2053 			fatal("%s line %d: no %s specified",
   2054 			    filename, linenum, keyword);
   2055 		}
   2056 		break;
   2057 
   2058 	case oSetEnv:
   2059 		found = options->num_setenv == 0;
   2060 		while ((arg = argv_next(&ac, &av)) != NULL) {
   2061 			if (strchr(arg, '=') == NULL) {
   2062 				error("%s line %d: Invalid SetEnv.",
   2063 				    filename, linenum);
   2064 				goto out;
   2065 			}
   2066 			if (lookup_setenv_in_list(arg, strs, nstrs) != NULL) {
   2067 				debug2("%s line %d: ignoring duplicate env "
   2068 				    "name \"%.64s\"", filename, linenum, arg);
   2069 				continue;
   2070 			}
   2071 			opt_array_append(filename, linenum,
   2072 			    lookup_opcode_name(opcode),
   2073 			    &strs, &nstrs, arg);
   2074 		}
   2075 		if (nstrs == 0) {
   2076 			fatal("%s line %d: no %s specified",
   2077 			    filename, linenum, keyword);
   2078 		}
   2079 		if (found && *activep) {
   2080 			options->setenv = strs;
   2081 			options->num_setenv = nstrs;
   2082 			strs = NULL; /* transferred */
   2083 			nstrs = 0;
   2084 		}
   2085 		break;
   2086 
   2087 	case oControlPath:
   2088 		charptr = &options->control_path;
   2089 		goto parse_string;
   2090 
   2091 	case oControlMaster:
   2092 		intptr = &options->control_master;
   2093 		multistate_ptr = multistate_controlmaster;
   2094 		goto parse_multistate;
   2095 
   2096 	case oControlPersist:
   2097 		/* no/false/yes/true, or a time spec */
   2098 		intptr = &options->control_persist;
   2099 		arg = argv_next(&ac, &av);
   2100 		if (!arg || *arg == '\0') {
   2101 			error("%.200s line %d: Missing ControlPersist"
   2102 			    " argument.", filename, linenum);
   2103 			goto out;
   2104 		}
   2105 		value = 0;
   2106 		value2 = 0;	/* timeout */
   2107 		if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0)
   2108 			value = 0;
   2109 		else if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0)
   2110 			value = 1;
   2111 		else if ((value2 = convtime(arg)) >= 0)
   2112 			value = 1;
   2113 		else {
   2114 			error("%.200s line %d: Bad ControlPersist argument.",
   2115 			    filename, linenum);
   2116 			goto out;
   2117 		}
   2118 		if (*activep && *intptr == -1) {
   2119 			*intptr = value;
   2120 			options->control_persist_timeout = value2;
   2121 		}
   2122 		break;
   2123 
   2124 	case oHashKnownHosts:
   2125 		intptr = &options->hash_known_hosts;
   2126 		goto parse_flag;
   2127 
   2128 	case oTunnel:
   2129 		intptr = &options->tun_open;
   2130 		multistate_ptr = multistate_tunnel;
   2131 		goto parse_multistate;
   2132 
   2133 	case oTunnelDevice:
   2134 		arg = argv_next(&ac, &av);
   2135 		if (!arg || *arg == '\0') {
   2136 			error("%.200s line %d: Missing argument.",
   2137 			    filename, linenum);
   2138 			goto out;
   2139 		}
   2140 		value = a2tun(arg, &value2);
   2141 		if (value == SSH_TUNID_ERR) {
   2142 			error("%.200s line %d: Bad tun device.",
   2143 			    filename, linenum);
   2144 			goto out;
   2145 		}
   2146 		if (*activep && options->tun_local == -1) {
   2147 			options->tun_local = value;
   2148 			options->tun_remote = value2;
   2149 		}
   2150 		break;
   2151 
   2152 	case oLocalCommand:
   2153 		charptr = &options->local_command;
   2154 		goto parse_command;
   2155 
   2156 	case oPermitLocalCommand:
   2157 		intptr = &options->permit_local_command;
   2158 		goto parse_flag;
   2159 
   2160 	case oRemoteCommand:
   2161 		charptr = &options->remote_command;
   2162 		goto parse_command;
   2163 
   2164 	case oVisualHostKey:
   2165 		intptr = &options->visual_host_key;
   2166 		goto parse_flag;
   2167 
   2168 	case oInclude:
   2169 		if (cmdline) {
   2170 			error("Include directive not supported as a "
   2171 			    "command-line option");
   2172 			goto out;
   2173 		}
   2174 		value = 0;
   2175 		while ((arg = argv_next(&ac, &av)) != NULL) {
   2176 			if (*arg == '\0') {
   2177 				error("%s line %d: keyword %s empty argument",
   2178 				    filename, linenum, keyword);
   2179 				goto out;
   2180 			}
   2181 			/* Expand %tokens and environment variables */
   2182 			if ((p = expand_match_exec_or_include_path(arg,
   2183 			    options, pw, host, original_host,
   2184 			    flags & SSHCONF_FINAL, 1)) == NULL) {
   2185 				error("%.200s line %d: Unable to expand user "
   2186 				    "config file '%.100s'",
   2187 				    filename, linenum, arg);
   2188 				continue;
   2189 			}
   2190 			/*
   2191 			 * Ensure all paths are anchored. User configuration
   2192 			 * files may begin with '~/' but system configurations
   2193 			 * must not. If the path is relative, then treat it
   2194 			 * as living in ~/.ssh for user configurations or
   2195 			 * /etc/ssh for system ones.
   2196 			 */
   2197 			if (*p == '~' && (flags & SSHCONF_USERCONF) == 0) {
   2198 				error("%.200s line %d: bad include path %s.",
   2199 				    filename, linenum, p);
   2200 				goto out;
   2201 			}
   2202 			if (!path_absolute(p) && *p != '~') {
   2203 				xasprintf(&arg2, "%s/%s",
   2204 				    (flags & SSHCONF_USERCONF) ?
   2205 				    "~/" _PATH_SSH_USER_DIR : SSHDIR, p);
   2206 			} else {
   2207 				arg2 = xstrdup(p);
   2208 			}
   2209 			free(p);
   2210 			memset(&gl, 0, sizeof(gl));
   2211 			r = glob(arg2, GLOB_TILDE | GLOB_LIMIT, NULL, &gl);
   2212 			if (r == GLOB_NOMATCH) {
   2213 				debug("%.200s line %d: include %s matched no "
   2214 				    "files",filename, linenum, arg2);
   2215 				free(arg2);
   2216 				continue;
   2217 			} else if (r != 0) {
   2218 				error("%.200s line %d: glob failed for %s.",
   2219 				    filename, linenum, arg2);
   2220 				goto out;
   2221 			}
   2222 			free(arg2);
   2223 			oactive = *activep;
   2224 			for (i = 0; i < gl.gl_pathc; i++) {
   2225 				debug3("%.200s line %d: Including file %s "
   2226 				    "depth %d%s", filename, linenum,
   2227 				    gl.gl_pathv[i], depth,
   2228 				    oactive ? "" : " (parse only)");
   2229 				r = read_config_file_depth(gl.gl_pathv[i],
   2230 				    pw, host, original_host, remote_command,
   2231 				    options, flags | SSHCONF_CHECKPERM |
   2232 				    (oactive ? 0 : SSHCONF_NEVERMATCH),
   2233 				    activep, want_final_pass, depth + 1);
   2234 				if (r != 1 && errno != ENOENT) {
   2235 					error("%.200s line %d: Can't open user "
   2236 					    "config file %.100s: %.100s",
   2237 					    filename, linenum, gl.gl_pathv[i],
   2238 					    strerror(errno));
   2239 					globfree(&gl);
   2240 					goto out;
   2241 				}
   2242 				/*
   2243 				 * don't let Match in includes clobber the
   2244 				 * containing file's Match state.
   2245 				 */
   2246 				*activep = oactive;
   2247 				if (r != 1)
   2248 					value = -1;
   2249 			}
   2250 			globfree(&gl);
   2251 		}
   2252 		if (value != 0)
   2253 			ret = value;
   2254 		break;
   2255 
   2256 	case oIPQoS:
   2257 		arg = argv_next(&ac, &av);
   2258 		if ((value = parse_ipqos(arg)) == -1) {
   2259 			error("%s line %d: Bad IPQoS value: %s",
   2260 			    filename, linenum, arg);
   2261 			goto out;
   2262 		}
   2263 		if (value == INT_MIN) {
   2264 			debug("%s line %d: Deprecated IPQoS value \"%s\" "
   2265 			    "ignored - using system default instead. Consider"
   2266 			    " using DSCP values.", filename, linenum, arg);
   2267 			value = INT_MAX;
   2268 		}
   2269 		arg = argv_next(&ac, &av);
   2270 		if (arg == NULL)
   2271 			value2 = value;
   2272 		else if ((value2 = parse_ipqos(arg)) == -1) {
   2273 			error("%s line %d: Bad IPQoS value: %s",
   2274 			    filename, linenum, arg);
   2275 			goto out;
   2276 		}
   2277 		if (value2 == INT_MIN) {
   2278 			debug("%s line %d: Deprecated IPQoS value \"%s\" "
   2279 			    "ignored - using system default instead. Consider"
   2280 			    " using DSCP values.", filename, linenum, arg);
   2281 			value2 = INT_MAX;
   2282 		}
   2283 		if (*activep && options->ip_qos_interactive == -1) {
   2284 			options->ip_qos_interactive = value;
   2285 			options->ip_qos_bulk = value2;
   2286 		}
   2287 		break;
   2288 
   2289 	case oRequestTTY:
   2290 		intptr = &options->request_tty;
   2291 		multistate_ptr = multistate_requesttty;
   2292 		goto parse_multistate;
   2293 
   2294 	case oSendVersionFirst:
   2295 		intptr = &options->send_version_first;
   2296 		goto parse_flag;
   2297 
   2298 	case oSessionType:
   2299 		intptr = &options->session_type;
   2300 		multistate_ptr = multistate_sessiontype;
   2301 		goto parse_multistate;
   2302 
   2303 	case oStdinNull:
   2304 		intptr = &options->stdin_null;
   2305 		goto parse_flag;
   2306 
   2307 	case oForkAfterAuthentication:
   2308 		intptr = &options->fork_after_authentication;
   2309 		goto parse_flag;
   2310 
   2311 	case oIgnoreUnknown:
   2312 		charptr = &options->ignored_unknown;
   2313 		goto parse_string;
   2314 
   2315 	case oProxyUseFdpass:
   2316 		intptr = &options->proxy_use_fdpass;
   2317 		goto parse_flag;
   2318 
   2319 	case oCanonicalDomains:
   2320 		found = options->num_canonical_domains == 0;
   2321 		while ((arg = argv_next(&ac, &av)) != NULL) {
   2322 			/* Allow "none" only in first position */
   2323 			if (strcasecmp(arg, "none") == 0) {
   2324 				if (nstrs > 0 || ac > 0) {
   2325 					error("%s line %d: keyword %s \"none\" "
   2326 					    "argument must appear alone.",
   2327 					    filename, linenum, keyword);
   2328 					goto out;
   2329 				}
   2330 			}
   2331 			if (!valid_domain(arg, 1, &errstr)) {
   2332 				error("%s line %d: %s", filename, linenum,
   2333 				    errstr);
   2334 				goto out;
   2335 			}
   2336 			opt_array_append(filename, linenum, keyword,
   2337 			    &strs, &nstrs, arg);
   2338 		}
   2339 		if (nstrs == 0) {
   2340 			fatal("%s line %d: no %s specified",
   2341 			    filename, linenum, keyword);
   2342 		}
   2343 		if (found && *activep) {
   2344 			options->canonical_domains = strs;
   2345 			options->num_canonical_domains = nstrs;
   2346 			strs = NULL; /* transferred */
   2347 			nstrs = 0;
   2348 		}
   2349 		break;
   2350 
   2351 	case oCanonicalizePermittedCNAMEs:
   2352 		found = options->num_permitted_cnames == 0;
   2353 		while ((arg = argv_next(&ac, &av)) != NULL) {
   2354 			char empty[] = "";
   2355 			/*
   2356 			 * Either 'none' (only in first position), '*' for
   2357 			 * everything or 'list:list'
   2358 			 */
   2359 			if (strcasecmp(arg, "none") == 0) {
   2360 				if (ncnames > 0 || ac > 0) {
   2361 					error("%s line %d: keyword %s \"none\" "
   2362 					    "argument must appear alone.",
   2363 					    filename, linenum, keyword);
   2364 					goto out;
   2365 				}
   2366 				arg2 = empty;
   2367 			} else if (strcmp(arg, "*") == 0) {
   2368 				arg2 = arg;
   2369 			} else {
   2370 				lowercase(arg);
   2371 				if ((arg2 = strchr(arg, ':')) == NULL ||
   2372 				    arg2[1] == '\0') {
   2373 					error("%s line %d: "
   2374 					    "Invalid permitted CNAME \"%s\"",
   2375 					    filename, linenum, arg);
   2376 					goto out;
   2377 				}
   2378 				*arg2 = '\0';
   2379 				arg2++;
   2380 			}
   2381 			cnames = xrecallocarray(cnames, ncnames, ncnames + 1,
   2382 			    sizeof(*cnames));
   2383 			cnames[ncnames].source_list = xstrdup(arg);
   2384 			cnames[ncnames].target_list = xstrdup(arg2);
   2385 			ncnames++;
   2386 		}
   2387 		if (ncnames == 0) {
   2388 			fatal("%s line %d: no %s specified",
   2389 			    filename, linenum, keyword);
   2390 		}
   2391 		if (found && *activep) {
   2392 			options->permitted_cnames = cnames;
   2393 			options->num_permitted_cnames = ncnames;
   2394 			cnames = NULL; /* transferred */
   2395 			ncnames = 0;
   2396 		}
   2397 		/* un-transferred cnames is cleaned up before exit */
   2398 		break;
   2399 
   2400 	case oCanonicalizeHostname:
   2401 		intptr = &options->canonicalize_hostname;
   2402 		multistate_ptr = multistate_canonicalizehostname;
   2403 		goto parse_multistate;
   2404 
   2405 	case oCanonicalizeMaxDots:
   2406 		intptr = &options->canonicalize_max_dots;
   2407 		goto parse_int;
   2408 
   2409 	case oCanonicalizeFallbackLocal:
   2410 		intptr = &options->canonicalize_fallback_local;
   2411 		goto parse_flag;
   2412 
   2413 	case oStreamLocalBindMask:
   2414 		arg = argv_next(&ac, &av);
   2415 		if (!arg || *arg == '\0') {
   2416 			error("%.200s line %d: Missing StreamLocalBindMask "
   2417 			    "argument.", filename, linenum);
   2418 			goto out;
   2419 		}
   2420 		/* Parse mode in octal format */
   2421 		value = strtol(arg, &endofnumber, 8);
   2422 		if (arg == endofnumber || value < 0 || value > 0777) {
   2423 			error("%.200s line %d: Bad mask.", filename, linenum);
   2424 			goto out;
   2425 		}
   2426 		if (*activep &&
   2427 		    options->fwd_opts.streamlocal_bind_mask == (mode_t)-1)
   2428 			options->fwd_opts.streamlocal_bind_mask = (mode_t)value;
   2429 		break;
   2430 
   2431 	case oStreamLocalBindUnlink:
   2432 		intptr = &options->fwd_opts.streamlocal_bind_unlink;
   2433 		goto parse_flag;
   2434 
   2435 	case oRevokedHostKeys:
   2436 		uintptr = &options->num_revoked_host_keys;
   2437 		cppptr = &options->revoked_host_keys;
   2438 		found = *uintptr == 0;
   2439 		while ((arg = argv_next(&ac, &av)) != NULL) {
   2440 			if (*arg == '\0') {
   2441 				error("%s line %d: keyword %s empty argument",
   2442 				    filename, linenum, keyword);
   2443 				goto out;
   2444 			}
   2445 			/* Allow "none" only in first position */
   2446 			if (strcasecmp(arg, "none") == 0) {
   2447 				if (nstrs > 0 || ac > 0) {
   2448 					error("%s line %d: keyword %s \"none\" "
   2449 					    "argument must appear alone.",
   2450 					    filename, linenum, keyword);
   2451 					goto out;
   2452 				}
   2453 			}
   2454 			opt_array_append(filename, linenum, keyword,
   2455 			    &strs, &nstrs, arg);
   2456 		}
   2457 		if (nstrs == 0) {
   2458 			fatal("%s line %d: no %s specified",
   2459 			    filename, linenum, keyword);
   2460 		}
   2461 		if (found && *activep) {
   2462 			*cppptr = strs;
   2463 			*uintptr = nstrs;
   2464 			strs = NULL; /* transferred */
   2465 			nstrs = 0;
   2466 		}
   2467 		break;
   2468 
   2469 	case oFingerprintHash:
   2470 		intptr = &options->fingerprint_hash;
   2471 		arg = argv_next(&ac, &av);
   2472 		if (!arg || *arg == '\0') {
   2473 			error("%.200s line %d: Missing argument.",
   2474 			    filename, linenum);
   2475 			goto out;
   2476 		}
   2477 		if ((value = ssh_digest_alg_by_name(arg)) == -1) {
   2478 			error("%.200s line %d: Invalid hash algorithm \"%s\".",
   2479 			    filename, linenum, arg);
   2480 			goto out;
   2481 		}
   2482 		if (*activep && *intptr == -1)
   2483 			*intptr = value;
   2484 		break;
   2485 
   2486 	case oUpdateHostkeys:
   2487 		intptr = &options->update_hostkeys;
   2488 		multistate_ptr = multistate_yesnoask;
   2489 		goto parse_multistate;
   2490 
   2491 	case oHostbasedAcceptedAlgorithms:
   2492 		charptr = &options->hostbased_accepted_algos;
   2493 		ca_only = 0;
   2494 		goto parse_pubkey_algos;
   2495 
   2496 	case oPubkeyAcceptedAlgorithms:
   2497 		charptr = &options->pubkey_accepted_algos;
   2498 		ca_only = 0;
   2499 		goto parse_pubkey_algos;
   2500 
   2501 	case oAddKeysToAgent:
   2502 		arg = argv_next(&ac, &av);
   2503 		arg2 = argv_next(&ac, &av);
   2504 		value = parse_multistate_value(arg, filename, linenum,
   2505 		    multistate_yesnoaskconfirm);
   2506 		value2 = 0; /* unlimited lifespan by default */
   2507 		if (value == 3 && arg2 != NULL) {
   2508 			/* allow "AddKeysToAgent confirm 5m" */
   2509 			if ((value2 = convtime(arg2)) == -1) {
   2510 				error("%s line %d: invalid time value.",
   2511 				    filename, linenum);
   2512 				goto out;
   2513 			}
   2514 		} else if (value == -1 && arg2 == NULL) {
   2515 			if ((value2 = convtime(arg)) == -1) {
   2516 				error("%s line %d: unsupported option",
   2517 				    filename, linenum);
   2518 				goto out;
   2519 			}
   2520 			value = 1; /* yes */
   2521 		} else if (value == -1 || arg2 != NULL) {
   2522 			error("%s line %d: unsupported option",
   2523 			    filename, linenum);
   2524 			goto out;
   2525 		}
   2526 		if (*activep && options->add_keys_to_agent == -1) {
   2527 			options->add_keys_to_agent = value;
   2528 			options->add_keys_to_agent_lifespan = value2;
   2529 		}
   2530 		break;
   2531 
   2532 	case oIdentityAgent:
   2533 		charptr = &options->identity_agent;
   2534 		arg = argv_next(&ac, &av);
   2535 		if (!arg || *arg == '\0') {
   2536 			error("%.200s line %d: Missing argument.",
   2537 			    filename, linenum);
   2538 			goto out;
   2539 		}
   2540   parse_agent_path:
   2541 		/* Extra validation if the string represents an env var. */
   2542 		if ((arg2 = dollar_expand(&r, arg)) == NULL || r) {
   2543 			error("%.200s line %d: Invalid environment expansion "
   2544 			    "%s.", filename, linenum, arg);
   2545 			goto out;
   2546 		}
   2547 		free(arg2);
   2548 		/* check for legacy environment format */
   2549 		if (arg[0] == '$' && arg[1] != '{' &&
   2550 		    !valid_env_name(arg + 1)) {
   2551 			error("%.200s line %d: Invalid environment name %s.",
   2552 			    filename, linenum, arg);
   2553 			goto out;
   2554 		}
   2555 		if (*activep && *charptr == NULL)
   2556 			*charptr = xstrdup(arg);
   2557 		break;
   2558 
   2559 	case oEnableEscapeCommandline:
   2560 		intptr = &options->enable_escape_commandline;
   2561 		goto parse_flag;
   2562 
   2563 	case oRequiredRSASize:
   2564 		intptr = &options->required_rsa_size;
   2565 		goto parse_int;
   2566 
   2567 	case oWarnWeakCrypto:
   2568 		intptr = &options->warn_weak_crypto;
   2569 		multistate_ptr = multistate_warnweakcrypto;
   2570 		goto parse_multistate;
   2571 
   2572 	case oObscureKeystrokeTiming:
   2573 		value = -1;
   2574 		while ((arg = argv_next(&ac, &av)) != NULL) {
   2575 			if (value != -1) {
   2576 				error("%s line %d: invalid arguments",
   2577 				    filename, linenum);
   2578 				goto out;
   2579 			}
   2580 			if (strcmp(arg, "yes") == 0 ||
   2581 			    strcmp(arg, "true") == 0)
   2582 				value = SSH_KEYSTROKE_DEFAULT_INTERVAL_MS;
   2583 			else if (strcmp(arg, "no") == 0 ||
   2584 			    strcmp(arg, "false") == 0)
   2585 				value = 0;
   2586 			else if (strncmp(arg, "interval:", 9) == 0) {
   2587 				if ((errstr = atoi_err(arg + 9,
   2588 				    &value)) != NULL) {
   2589 					error("%s line %d: integer value %s.",
   2590 					    filename, linenum, errstr);
   2591 					goto out;
   2592 				}
   2593 				if (value <= 0 || value > 1000) {
   2594 					error("%s line %d: value out of range.",
   2595 					    filename, linenum);
   2596 					goto out;
   2597 				}
   2598 			} else {
   2599 				error("%s line %d: unsupported argument \"%s\"",
   2600 				    filename, linenum, arg);
   2601 				goto out;
   2602 			}
   2603 		}
   2604 		if (value == -1) {
   2605 			error("%s line %d: missing argument",
   2606 			    filename, linenum);
   2607 			goto out;
   2608 		}
   2609 		intptr = &options->obscure_keystroke_timing_interval;
   2610 		if (*activep && *intptr == -1)
   2611 			*intptr = value;
   2612 		break;
   2613 
   2614 	case oChannelTimeout:
   2615 		found = options->num_channel_timeouts == 0;
   2616 		while ((arg = argv_next(&ac, &av)) != NULL) {
   2617 			/* Allow "none" only in first position */
   2618 			if (strcasecmp(arg, "none") == 0) {
   2619 				if (nstrs > 0 || ac > 0) {
   2620 					error("%s line %d: keyword %s \"none\" "
   2621 					    "argument must appear alone.",
   2622 					    filename, linenum, keyword);
   2623 					goto out;
   2624 				}
   2625 			} else if (parse_pattern_interval(arg,
   2626 			    NULL, NULL) != 0) {
   2627 				fatal("%s line %d: invalid channel timeout %s",
   2628 				    filename, linenum, arg);
   2629 			}
   2630 			opt_array_append(filename, linenum, keyword,
   2631 			    &strs, &nstrs, arg);
   2632 		}
   2633 		if (nstrs == 0) {
   2634 			fatal("%s line %d: no %s specified",
   2635 			    filename, linenum, keyword);
   2636 		}
   2637 		if (found && *activep) {
   2638 			options->channel_timeouts = strs;
   2639 			options->num_channel_timeouts = nstrs;
   2640 			strs = NULL; /* transferred */
   2641 			nstrs = 0;
   2642 		}
   2643 		break;
   2644 
   2645 	case oVersionAddendum:
   2646 		if (str == NULL || *str == '\0')
   2647 			fatal("%s line %d: %s missing argument.",
   2648 			    filename, linenum, keyword);
   2649 		len = strspn(str, WHITESPACE);
   2650 		if (strchr(str + len, '\r') != NULL) {
   2651 			fatal("%.200s line %d: Invalid %s argument",
   2652 			    filename, linenum, keyword);
   2653 		}
   2654 		if ((arg = strchr(line, '#')) != NULL) {
   2655 			*arg = '\0';
   2656 			rtrim(line);
   2657 		}
   2658 		if (*activep && options->version_addendum == NULL) {
   2659 			if (strcasecmp(str + len, "none") == 0)
   2660 				options->version_addendum = xstrdup("");
   2661 			else
   2662 				options->version_addendum = xstrdup(str + len);
   2663 		}
   2664 		argv_consume(&ac);
   2665 		break;
   2666 
   2667 	case oRefuseConnection:
   2668 		arg = argv_next(&ac, &av);
   2669 		if (!arg || *arg == '\0') {
   2670 			error("%.200s line %d: Missing argument.",
   2671 			    filename, linenum);
   2672 			goto out;
   2673 		}
   2674 		if (*activep) {
   2675 			fatal("%.200s line %d: RefuseConnection: %s",
   2676 			    filename, linenum, arg);
   2677 		}
   2678 		break;
   2679 
   2680 	case oDeprecated:
   2681 		debug("%s line %d: Deprecated option \"%s\"",
   2682 		    filename, linenum, keyword);
   2683 		argv_consume(&ac);
   2684 		break;
   2685 
   2686 	case oUnsupported:
   2687 		error("%s line %d: Unsupported option \"%s\"",
   2688 		    filename, linenum, keyword);
   2689 		argv_consume(&ac);
   2690 		break;
   2691 
   2692 	default:
   2693 		error("%s line %d: Unimplemented opcode %d",
   2694 		    filename, linenum, opcode);
   2695 		goto out;
   2696 	}
   2697 
   2698 	/* Check that there is no garbage at end of line. */
   2699 	if (ac > 0) {
   2700 		error("%.200s line %d: keyword %s extra arguments "
   2701 		    "at end of line", filename, linenum, keyword);
   2702 		goto out;
   2703 	}
   2704 
   2705 	/* success */
   2706 	ret = 0;
   2707  out:
   2708 	free_canon_cnames(cnames, ncnames);
   2709 	opt_array_free2(strs, NULL, nstrs);
   2710 	argv_free(oav, oac);
   2711 	return ret;
   2712 }
   2713 
   2714 /*
   2715  * Reads the config file and modifies the options accordingly.  Options
   2716  * should already be initialized before this call.  This never returns if
   2717  * there is an error.  If the file does not exist, this returns 0.
   2718  */
   2719 int
   2720 read_config_file(const char *filename, struct passwd *pw, const char *host,
   2721     const char *original_host, const char *remote_command, Options *options, int flags,
   2722     int *want_final_pass)
   2723 {
   2724 	int active = 1;
   2725 
   2726 	return read_config_file_depth(filename, pw, host, original_host,
   2727 	    remote_command, options, flags, &active, want_final_pass, 0);
   2728 }
   2729 
   2730 #define READCONF_MAX_DEPTH	16
   2731 static int
   2732 read_config_file_depth(const char *filename, struct passwd *pw,
   2733     const char *host, const char *original_host, const char *remote_command,
   2734     Options *options, int flags, int *activep, int *want_final_pass, int depth)
   2735 {
   2736 	FILE *f;
   2737 	char *line = NULL;
   2738 	size_t linesize = 0;
   2739 	int linenum;
   2740 	int bad_options = 0;
   2741 
   2742 	if (depth < 0 || depth > READCONF_MAX_DEPTH)
   2743 		fatal("Too many recursive configuration includes");
   2744 
   2745 	if ((f = fopen(filename, "r")) == NULL)
   2746 		return 0;
   2747 
   2748 	if (flags & SSHCONF_CHECKPERM) {
   2749 		struct stat sb;
   2750 
   2751 		if (fstat(fileno(f), &sb) == -1)
   2752 			fatal("fstat %s: %s", filename, strerror(errno));
   2753 		if (((sb.st_uid != 0 && sb.st_uid != getuid()) ||
   2754 		    (sb.st_mode & 022) != 0))
   2755 			fatal("Bad owner or permissions on %s", filename);
   2756 	}
   2757 
   2758 	debug("Reading configuration data %.200s", filename);
   2759 
   2760 	/*
   2761 	 * Mark that we are now processing the options.  This flag is turned
   2762 	 * on/off by Host specifications.
   2763 	 */
   2764 	linenum = 0;
   2765 	while (getline(&line, &linesize, f) != -1) {
   2766 		/* Update line number counter. */
   2767 		linenum++;
   2768 		/*
   2769 		 * Trim out comments and strip whitespace.
   2770 		 * NB - preserve newlines, they are needed to reproduce
   2771 		 * line numbers later for error messages.
   2772 		 */
   2773 		if (process_config_line_depth(options, pw, host, original_host,
   2774 		    remote_command, line, filename, linenum, activep, flags,
   2775 		    want_final_pass, depth) != 0)
   2776 			bad_options++;
   2777 	}
   2778 	free(line);
   2779 	fclose(f);
   2780 	if (bad_options > 0)
   2781 		fatal("%s: terminating, %d bad configuration options",
   2782 		    filename, bad_options);
   2783 	return 1;
   2784 }
   2785 
   2786 /* Returns 1 if a string option is unset or set to "none" or 0 otherwise. */
   2787 int
   2788 option_clear_or_none(const char *o)
   2789 {
   2790 	return o == NULL || strcasecmp(o, "none") == 0;
   2791 }
   2792 
   2793 /*
   2794  * Returns 1 if CanonicalizePermittedCNAMEs have been specified, 0 otherwise.
   2795  * Allowed to be called on non-final configuration.
   2796  */
   2797 int
   2798 config_has_permitted_cnames(Options *options)
   2799 {
   2800 	if (options->num_permitted_cnames == 1 &&
   2801 	    strcasecmp(options->permitted_cnames[0].source_list, "none") == 0 &&
   2802 	    strcmp(options->permitted_cnames[0].target_list, "") == 0)
   2803 		return 0;
   2804 	return options->num_permitted_cnames > 0;
   2805 }
   2806 
   2807 /*
   2808  * Initializes options to special values that indicate that they have not yet
   2809  * been set.  Read_config_file will only set options with this value. Options
   2810  * are processed in the following order: command line, user config file,
   2811  * system config file.  Last, fill_default_options is called.
   2812  */
   2813 
   2814 void
   2815 initialize_options(Options * options)
   2816 {
   2817 	memset(options, 'X', sizeof(*options));
   2818 	options->host_arg = NULL;
   2819 	options->forward_agent = -1;
   2820 	options->forward_agent_sock_path = NULL;
   2821 	options->forward_x11 = -1;
   2822 	options->forward_x11_trusted = -1;
   2823 	options->forward_x11_timeout = -1;
   2824 	options->stdio_forward_host = NULL;
   2825 	options->stdio_forward_port = 0;
   2826 	options->clear_forwardings = -1;
   2827 	options->exit_on_forward_failure = -1;
   2828 	options->xauth_location = NULL;
   2829 	options->fwd_opts.gateway_ports = -1;
   2830 	options->fwd_opts.streamlocal_bind_mask = (mode_t)-1;
   2831 	options->fwd_opts.streamlocal_bind_unlink = -1;
   2832 	options->pubkey_authentication = -1;
   2833 #if defined(KRB4) || defined(KRB5)
   2834 	options->kerberos_authentication = -1;
   2835 #endif
   2836 #if defined(AFS) || defined(KRB5)
   2837 	options->kerberos_tgt_passing = -1;
   2838 #endif
   2839 #ifdef AFS
   2840 	options->afs_token_passing = -1;
   2841 #endif
   2842 	options->gss_authentication = -1;
   2843 	options->gss_deleg_creds = -1;
   2844 	options->password_authentication = -1;
   2845 	options->kbd_interactive_authentication = -1;
   2846 	options->kbd_interactive_devices = NULL;
   2847 	options->hostbased_authentication = -1;
   2848 	options->batch_mode = -1;
   2849 	options->check_host_ip = -1;
   2850 	options->strict_host_key_checking = -1;
   2851 	options->compression = -1;
   2852 	options->tcp_keep_alive = -1;
   2853 	options->port = -1;
   2854 	options->address_family = -1;
   2855 	options->connection_attempts = -1;
   2856 	options->connection_timeout = -1;
   2857 	options->number_of_password_prompts = -1;
   2858 	options->ciphers = NULL;
   2859 	options->macs = NULL;
   2860 	options->kex_algorithms = NULL;
   2861 	options->hostkeyalgorithms = NULL;
   2862 	options->ca_sign_algorithms = NULL;
   2863 	options->num_identity_files = 0;
   2864 	memset(options->identity_keys, 0, sizeof(options->identity_keys));
   2865 	options->num_certificate_files = 0;
   2866 	memset(options->certificates, 0, sizeof(options->certificates));
   2867 	options->hostname = NULL;
   2868 	options->host_key_alias = NULL;
   2869 	options->proxy_command = NULL;
   2870 	options->jump_user = NULL;
   2871 	options->jump_host = NULL;
   2872 	options->jump_port = -1;
   2873 	options->jump_extra = NULL;
   2874 	options->user = NULL;
   2875 	options->escape_char = -1;
   2876 	options->num_system_hostfiles = 0;
   2877 	options->num_user_hostfiles = 0;
   2878 	options->local_forwards = NULL;
   2879 	options->num_local_forwards = 0;
   2880 	options->remote_forwards = NULL;
   2881 	options->num_remote_forwards = 0;
   2882 	options->permitted_remote_opens = NULL;
   2883 	options->num_permitted_remote_opens = 0;
   2884 	options->log_facility = SYSLOG_FACILITY_NOT_SET;
   2885 	options->log_level = SYSLOG_LEVEL_NOT_SET;
   2886 	options->num_log_verbose = 0;
   2887 	options->log_verbose = NULL;
   2888 	options->preferred_authentications = NULL;
   2889 	options->bind_address = NULL;
   2890 	options->bind_interface = NULL;
   2891 	options->ipv6_prefer_temporary = -1;
   2892 	options->pkcs11_provider = NULL;
   2893 	options->sk_provider = NULL;
   2894 	options->enable_ssh_keysign = -1;
   2895 	options->no_host_authentication_for_localhost = -1;
   2896 	options->identities_only = -1;
   2897 	options->rekey_limit = -1;
   2898 	options->rekey_interval = -1;
   2899 	options->verify_host_key_dns = -1;
   2900 	options->server_alive_interval = -1;
   2901 	options->server_alive_count_max = -1;
   2902 	options->send_env = NULL;
   2903 	options->num_send_env = 0;
   2904 	options->setenv = NULL;
   2905 	options->num_setenv = 0;
   2906 	options->control_path = NULL;
   2907 	options->control_master = -1;
   2908 	options->control_persist = -1;
   2909 	options->control_persist_timeout = 0;
   2910 	options->hash_known_hosts = -1;
   2911 	options->tun_open = -1;
   2912 	options->tun_local = -1;
   2913 	options->tun_remote = -1;
   2914 	options->local_command = NULL;
   2915 	options->permit_local_command = -1;
   2916 	options->remote_command = NULL;
   2917 	options->add_keys_to_agent = -1;
   2918 	options->add_keys_to_agent_lifespan = -1;
   2919 	options->identity_agent = NULL;
   2920 	options->visual_host_key = -1;
   2921 	options->ip_qos_interactive = -1;
   2922 	options->ip_qos_bulk = -1;
   2923 	options->request_tty = -1;
   2924 	options->session_type = -1;
   2925 	options->stdin_null = -1;
   2926 	options->fork_after_authentication = -1;
   2927 	options->proxy_use_fdpass = -1;
   2928 	options->ignored_unknown = NULL;
   2929 	options->num_canonical_domains = 0;
   2930 	options->num_permitted_cnames = 0;
   2931 	options->canonicalize_max_dots = -1;
   2932 	options->canonicalize_fallback_local = -1;
   2933 	options->canonicalize_hostname = -1;
   2934 	options->revoked_host_keys = NULL;
   2935 	options->num_revoked_host_keys = 0;
   2936 	options->fingerprint_hash = -1;
   2937 	options->update_hostkeys = -1;
   2938 	options->hostbased_accepted_algos = NULL;
   2939 	options->pubkey_accepted_algos = NULL;
   2940 	options->known_hosts_command = NULL;
   2941 	options->required_rsa_size = -1;
   2942 	options->warn_weak_crypto = -1;
   2943 	options->enable_escape_commandline = -1;
   2944 	options->obscure_keystroke_timing_interval = -1;
   2945 	options->tag = NULL;
   2946 	options->channel_timeouts = NULL;
   2947 	options->num_channel_timeouts = 0;
   2948 	options->version_addendum = NULL;
   2949 	options->none_switch = -1;
   2950 	options->none_enabled = -1;
   2951 	options->hpn_disabled = -1;
   2952 	options->hpn_buffer_size = -1;
   2953 	options->tcp_rcv_buf_poll = -1;
   2954 	options->tcp_rcv_buf = -1;
   2955 	options->send_version_first = -1;
   2956 }
   2957 
   2958 /*
   2959  * A petite version of fill_default_options() that just fills the options
   2960  * needed for hostname canonicalization to proceed.
   2961  */
   2962 void
   2963 fill_default_options_for_canonicalization(Options *options)
   2964 {
   2965 	if (options->canonicalize_max_dots == -1)
   2966 		options->canonicalize_max_dots = 1;
   2967 	if (options->canonicalize_fallback_local == -1)
   2968 		options->canonicalize_fallback_local = 1;
   2969 	if (options->canonicalize_hostname == -1)
   2970 		options->canonicalize_hostname = SSH_CANONICALISE_NO;
   2971 }
   2972 
   2973 /*
   2974  * Called after processing other sources of option data, this fills those
   2975  * options for which no value has been specified with their default values.
   2976  */
   2977 int
   2978 fill_default_options(Options * options)
   2979 {
   2980 	char *all_cipher, *all_mac, *all_kex, *all_key, *all_sig;
   2981 	char *def_cipher, *def_mac, *def_kex, *def_key, *def_sig;
   2982 	int ret = -1, r;
   2983 
   2984 	if (options->forward_agent == -1)
   2985 		options->forward_agent = 0;
   2986 	if (options->forward_x11 == -1)
   2987 		options->forward_x11 = 0;
   2988 	if (options->forward_x11_trusted == -1)
   2989 		options->forward_x11_trusted = 0;
   2990 	if (options->forward_x11_timeout == -1)
   2991 		options->forward_x11_timeout = 1200;
   2992 	/*
   2993 	 * stdio forwarding (-W) changes the default for these but we defer
   2994 	 * setting the values so they can be overridden.
   2995 	 */
   2996 	if (options->exit_on_forward_failure == -1)
   2997 		options->exit_on_forward_failure =
   2998 		    options->stdio_forward_host != NULL ? 1 : 0;
   2999 	if (options->clear_forwardings == -1)
   3000 		options->clear_forwardings =
   3001 		    options->stdio_forward_host != NULL ? 1 : 0;
   3002 	if (options->clear_forwardings == 1)
   3003 		clear_forwardings(options);
   3004 
   3005 	if (options->xauth_location == NULL)
   3006 		options->xauth_location = xstrdup(_PATH_XAUTH);
   3007 	if (options->fwd_opts.gateway_ports == -1)
   3008 		options->fwd_opts.gateway_ports = 0;
   3009 	if (options->fwd_opts.streamlocal_bind_mask == (mode_t)-1)
   3010 		options->fwd_opts.streamlocal_bind_mask = 0177;
   3011 	if (options->fwd_opts.streamlocal_bind_unlink == -1)
   3012 		options->fwd_opts.streamlocal_bind_unlink = 0;
   3013 	if (options->pubkey_authentication == -1)
   3014 		options->pubkey_authentication = SSH_PUBKEY_AUTH_ALL;
   3015 #if defined(KRB4) || defined(KRB5)
   3016 	if (options->kerberos_authentication == -1)
   3017 		options->kerberos_authentication = 1;
   3018 #endif
   3019 #if defined(AFS) || defined(KRB5)
   3020 	if (options->kerberos_tgt_passing == -1)
   3021 		options->kerberos_tgt_passing = 1;
   3022 #endif
   3023 #ifdef AFS
   3024 	if (options->afs_token_passing == -1)
   3025 		options->afs_token_passing = 1;
   3026 #endif
   3027 	if (options->gss_authentication == -1)
   3028 		options->gss_authentication = 0;
   3029 	if (options->gss_deleg_creds == -1)
   3030 		options->gss_deleg_creds = 0;
   3031 	if (options->password_authentication == -1)
   3032 		options->password_authentication = 1;
   3033 	if (options->kbd_interactive_authentication == -1)
   3034 		options->kbd_interactive_authentication = 1;
   3035 	if (options->hostbased_authentication == -1)
   3036 		options->hostbased_authentication = 0;
   3037 	if (options->batch_mode == -1)
   3038 		options->batch_mode = 0;
   3039 	if (options->check_host_ip == -1)
   3040 		options->check_host_ip = 0;
   3041 	if (options->strict_host_key_checking == -1)
   3042 		options->strict_host_key_checking = SSH_STRICT_HOSTKEY_ASK;
   3043 	if (options->compression == -1)
   3044 		options->compression = 0;
   3045 	if (options->tcp_keep_alive == -1)
   3046 		options->tcp_keep_alive = SSH_KEEPALIVES_TRANSPORT;
   3047 	if (options->port == -1)
   3048 		options->port = 0;	/* Filled in ssh_connect. */
   3049 	if (options->address_family == -1)
   3050 		options->address_family = AF_UNSPEC;
   3051 	if (options->connection_attempts == -1)
   3052 		options->connection_attempts = 1;
   3053 	if (options->number_of_password_prompts == -1)
   3054 		options->number_of_password_prompts = 3;
   3055 	/* options->hostkeyalgorithms, default set in myproposals.h */
   3056 	if (options->add_keys_to_agent == -1) {
   3057 		options->add_keys_to_agent = 0;
   3058 		options->add_keys_to_agent_lifespan = 0;
   3059 	}
   3060 	if (options->num_identity_files == 0) {
   3061 		add_identity_file(options, "~/", _PATH_SSH_CLIENT_ID_RSA, 0);
   3062 		add_identity_file(options, "~/", _PATH_SSH_CLIENT_ID_ECDSA, 0);
   3063 		add_identity_file(options, "~/",
   3064 		    _PATH_SSH_CLIENT_ID_ECDSA_SK, 0);
   3065 		add_identity_file(options, "~/",
   3066 		    _PATH_SSH_CLIENT_ID_ED25519, 0);
   3067 		add_identity_file(options, "~/",
   3068 		    _PATH_SSH_CLIENT_ID_ED25519_SK, 0);
   3069 		add_identity_file(options, "~/",
   3070 		    _PATH_SSH_CLIENT_ID_MLDSA44_ED25519, 0);
   3071 	}
   3072 	if (options->escape_char == -1)
   3073 		options->escape_char = '~';
   3074 	if (options->num_system_hostfiles == 0) {
   3075 		options->system_hostfiles[options->num_system_hostfiles++] =
   3076 		    xstrdup(_PATH_SSH_SYSTEM_HOSTFILE);
   3077 		options->system_hostfiles[options->num_system_hostfiles++] =
   3078 		    xstrdup(_PATH_SSH_SYSTEM_HOSTFILE2);
   3079 	}
   3080 	if (options->update_hostkeys == -1) {
   3081 		if (options->verify_host_key_dns <= 0 &&
   3082 		    (options->num_user_hostfiles == 0 ||
   3083 		    (options->num_user_hostfiles == 1 && strcmp(options->
   3084 		    user_hostfiles[0], _PATH_SSH_USER_HOSTFILE) == 0)))
   3085 			options->update_hostkeys = SSH_UPDATE_HOSTKEYS_YES;
   3086 		else
   3087 			options->update_hostkeys = SSH_UPDATE_HOSTKEYS_NO;
   3088 	}
   3089 	if (options->num_user_hostfiles == 0) {
   3090 		options->user_hostfiles[options->num_user_hostfiles++] =
   3091 		    xstrdup(_PATH_SSH_USER_HOSTFILE);
   3092 		options->user_hostfiles[options->num_user_hostfiles++] =
   3093 		    xstrdup(_PATH_SSH_USER_HOSTFILE2);
   3094 	}
   3095 	if (options->log_level == SYSLOG_LEVEL_NOT_SET)
   3096 		options->log_level = SYSLOG_LEVEL_INFO;
   3097 	if (options->log_facility == SYSLOG_FACILITY_NOT_SET)
   3098 		options->log_facility = SYSLOG_FACILITY_USER;
   3099 	if (options->no_host_authentication_for_localhost == -1)
   3100 		options->no_host_authentication_for_localhost = 0;
   3101 	if (options->identities_only == -1)
   3102 		options->identities_only = 0;
   3103 	if (options->enable_ssh_keysign == -1)
   3104 		options->enable_ssh_keysign = 0;
   3105 	if (options->rekey_limit == -1)
   3106 		options->rekey_limit = 0;
   3107 	if (options->rekey_interval == -1)
   3108 		options->rekey_interval = 0;
   3109 	if (options->verify_host_key_dns == -1)
   3110 		options->verify_host_key_dns = 0;
   3111 	if (options->server_alive_interval == -1)
   3112 		options->server_alive_interval = 0;
   3113 	if (options->server_alive_count_max == -1)
   3114 		options->server_alive_count_max = 3;
   3115 	if (options->none_switch == -1)
   3116 	        options->none_switch = 0;
   3117 	if (options->hpn_disabled == -1)
   3118 	        options->hpn_disabled = 0;
   3119 	if (options->hpn_buffer_size > -1)
   3120 	{
   3121 	  /* if a user tries to set the size to 0 set it to 1KB */
   3122 		if (options->hpn_buffer_size == 0)
   3123 			options->hpn_buffer_size = 1;
   3124 		/*limit the buffer to 64MB*/
   3125 		if (options->hpn_buffer_size > (SSHBUF_SIZE_MAX / 1024))
   3126 		{
   3127 			options->hpn_buffer_size = SSHBUF_SIZE_MAX;
   3128 			debug("User requested buffer larger than 256MB. Request reverted to 256MB");
   3129 		} else
   3130 			options->hpn_buffer_size *= 1024;
   3131 		debug("hpn_buffer_size set to %d", options->hpn_buffer_size);
   3132 	}
   3133 	if (options->tcp_rcv_buf == 0)
   3134 		options->tcp_rcv_buf = 1;
   3135 	if (options->tcp_rcv_buf > -1)
   3136 		options->tcp_rcv_buf *=1024;
   3137 	if (options->tcp_rcv_buf_poll == -1)
   3138 		options->tcp_rcv_buf_poll = 1;
   3139 	if (options->control_master == -1)
   3140 		options->control_master = 0;
   3141 	if (options->control_persist == -1) {
   3142 		options->control_persist = 0;
   3143 		options->control_persist_timeout = 0;
   3144 	}
   3145 	if (options->hash_known_hosts == -1)
   3146 		options->hash_known_hosts = 0;
   3147 	if (options->tun_open == -1)
   3148 		options->tun_open = SSH_TUNMODE_NO;
   3149 	if (options->tun_local == -1)
   3150 		options->tun_local = SSH_TUNID_ANY;
   3151 	if (options->tun_remote == -1)
   3152 		options->tun_remote = SSH_TUNID_ANY;
   3153 	if (options->permit_local_command == -1)
   3154 		options->permit_local_command = 0;
   3155 	if (options->visual_host_key == -1)
   3156 		options->visual_host_key = 0;
   3157 	if (options->ip_qos_interactive == -1)
   3158 		options->ip_qos_interactive = IPTOS_DSCP_EF;
   3159 	if (options->ip_qos_bulk == -1)
   3160 		options->ip_qos_bulk = IPTOS_DSCP_CS0;
   3161 	if (options->request_tty == -1)
   3162 		options->request_tty = REQUEST_TTY_AUTO;
   3163 	if (options->session_type == -1)
   3164 		options->session_type = SESSION_TYPE_DEFAULT;
   3165 	if (options->stdin_null == -1)
   3166 		options->stdin_null = 0;
   3167 	if (options->fork_after_authentication == -1)
   3168 		options->fork_after_authentication = 0;
   3169 	if (options->proxy_use_fdpass == -1)
   3170 		options->proxy_use_fdpass = 0;
   3171 	if (options->canonicalize_max_dots == -1)
   3172 		options->canonicalize_max_dots = 1;
   3173 	if (options->canonicalize_fallback_local == -1)
   3174 		options->canonicalize_fallback_local = 1;
   3175 	if (options->canonicalize_hostname == -1)
   3176 		options->canonicalize_hostname = SSH_CANONICALISE_NO;
   3177 	if (options->fingerprint_hash == -1)
   3178 		options->fingerprint_hash = SSH_FP_HASH_DEFAULT;
   3179 	if (options->sk_provider == NULL)
   3180 		options->sk_provider = xstrdup("internal");
   3181 	if (options->required_rsa_size == -1)
   3182 		options->required_rsa_size = SSH_RSA_MINIMUM_MODULUS_SIZE;
   3183 	if (options->warn_weak_crypto == -1)
   3184 		options->warn_weak_crypto = 1;
   3185 	if (options->enable_escape_commandline == -1)
   3186 		options->enable_escape_commandline = 0;
   3187 	if (options->obscure_keystroke_timing_interval == -1) {
   3188 		options->obscure_keystroke_timing_interval =
   3189 		    SSH_KEYSTROKE_DEFAULT_INTERVAL_MS;
   3190 	}
   3191 
   3192 	/* Expand KEX name lists */
   3193 	all_cipher = cipher_alg_list(',', 0);
   3194 	all_mac = mac_alg_list(',');
   3195 	all_kex = kex_alg_list(',');
   3196 	all_key = sshkey_alg_list(0, 0, 1, ',');
   3197 	all_sig = sshkey_alg_list(0, 1, 1, ',');
   3198 	/* remove unsupported algos from default lists */
   3199 	def_cipher = match_filter_allowlist(KEX_CLIENT_ENCRYPT, all_cipher);
   3200 	def_mac = match_filter_allowlist(KEX_CLIENT_MAC, all_mac);
   3201 	def_kex = match_filter_allowlist(KEX_CLIENT_KEX, all_kex);
   3202 	def_key = match_filter_allowlist(KEX_DEFAULT_PK_ALG, all_key);
   3203 	def_sig = match_filter_allowlist(SSH_ALLOWED_CA_SIGALGS, all_sig);
   3204 #define ASSEMBLE(what, defaults, all) \
   3205 	do { \
   3206 		if ((r = kex_assemble_names(&options->what, \
   3207 		    defaults, all)) != 0) { \
   3208 			error_fr(r, "%s", #what); \
   3209 			goto fail; \
   3210 		} \
   3211 	} while (0)
   3212 	options->kex_algorithms_set = options->kex_algorithms != NULL;
   3213 	ASSEMBLE(ciphers, def_cipher, all_cipher);
   3214 	ASSEMBLE(macs, def_mac, all_mac);
   3215 	ASSEMBLE(kex_algorithms, def_kex, all_kex);
   3216 	ASSEMBLE(hostbased_accepted_algos, def_key, all_key);
   3217 	ASSEMBLE(pubkey_accepted_algos, def_key, all_key);
   3218 	ASSEMBLE(ca_sign_algorithms, def_sig, all_sig);
   3219 #undef ASSEMBLE
   3220 
   3221 	if (options->send_version_first == -1)
   3222 		options->send_version_first = 1;
   3223 #define CLEAR_ON_NONE(v) \
   3224 	do { \
   3225 		if (option_clear_or_none(v)) { \
   3226 			free(v); \
   3227 			v = NULL; \
   3228 		} \
   3229 	} while(0)
   3230 #define CLEAR_ON_NONE_ARRAY(v, nv, none) \
   3231 	do { \
   3232 		if (options->nv == 1 && \
   3233 		    strcasecmp(options->v[0], none) == 0) { \
   3234 			free(options->v[0]); \
   3235 			free(options->v); \
   3236 			options->v = NULL; \
   3237 			options->nv = 0; \
   3238 		} \
   3239 	} while (0)
   3240 	CLEAR_ON_NONE(options->local_command);
   3241 	CLEAR_ON_NONE(options->remote_command);
   3242 	CLEAR_ON_NONE(options->proxy_command);
   3243 	CLEAR_ON_NONE(options->control_path);
   3244 	CLEAR_ON_NONE(options->pkcs11_provider);
   3245 	CLEAR_ON_NONE(options->sk_provider);
   3246 	CLEAR_ON_NONE(options->known_hosts_command);
   3247 	CLEAR_ON_NONE_ARRAY(channel_timeouts, num_channel_timeouts, "none");
   3248 	CLEAR_ON_NONE_ARRAY(revoked_host_keys, num_revoked_host_keys, "none");
   3249 #undef CLEAR_ON_NONE
   3250 #undef CLEAR_ON_NONE_ARRAY
   3251 	if (options->jump_host != NULL &&
   3252 	    strcmp(options->jump_host, "none") == 0 &&
   3253 	    options->jump_port == 0 && options->jump_user == NULL) {
   3254 		free(options->jump_host);
   3255 		options->jump_host = NULL;
   3256 	}
   3257 	if (options->num_permitted_cnames == 1 &&
   3258 	    !config_has_permitted_cnames(options)) {
   3259 		/* clean up CanonicalizePermittedCNAMEs=none */
   3260 		free(options->permitted_cnames[0].source_list);
   3261 		free(options->permitted_cnames[0].target_list);
   3262 		memset(options->permitted_cnames, '\0',
   3263 		    sizeof(*options->permitted_cnames));
   3264 		options->num_permitted_cnames = 0;
   3265 	}
   3266 	/* options->identity_agent distinguishes NULL from 'none' */
   3267 	/* options->user will be set in the main program if appropriate */
   3268 	/* options->hostname will be set in the main program if appropriate */
   3269 	/* options->host_key_alias should not be set by default */
   3270 	/* options->preferred_authentications will be set in ssh */
   3271 
   3272 	/* success */
   3273 	ret = 0;
   3274  fail:
   3275 	free(all_cipher);
   3276 	free(all_mac);
   3277 	free(all_kex);
   3278 	free(all_key);
   3279 	free(all_sig);
   3280 	free(def_cipher);
   3281 	free(def_mac);
   3282 	free(def_kex);
   3283 	free(def_key);
   3284 	free(def_sig);
   3285 	return ret;
   3286 }
   3287 
   3288 void
   3289 free_options(Options *o)
   3290 {
   3291 	int i;
   3292 
   3293 	if (o == NULL)
   3294 		return;
   3295 
   3296 #define FREE_ARRAY(type, n, a) \
   3297 	do { \
   3298 		type _i; \
   3299 		for (_i = 0; _i < (n); _i++) \
   3300 			free((a)[_i]); \
   3301 	} while (0)
   3302 
   3303 	free(o->forward_agent_sock_path);
   3304 	free(o->xauth_location);
   3305 	FREE_ARRAY(u_int, o->num_log_verbose, o->log_verbose);
   3306 	free(o->log_verbose);
   3307 	free(o->ciphers);
   3308 	free(o->macs);
   3309 	free(o->hostkeyalgorithms);
   3310 	free(o->kex_algorithms);
   3311 	free(o->ca_sign_algorithms);
   3312 	free(o->hostname);
   3313 	free(o->host_key_alias);
   3314 	free(o->proxy_command);
   3315 	free(o->user);
   3316 	FREE_ARRAY(u_int, o->num_system_hostfiles, o->system_hostfiles);
   3317 	FREE_ARRAY(u_int, o->num_user_hostfiles, o->user_hostfiles);
   3318 	free(o->preferred_authentications);
   3319 	free(o->bind_address);
   3320 	free(o->bind_interface);
   3321 	free(o->pkcs11_provider);
   3322 	free(o->sk_provider);
   3323 	for (i = 0; i < o->num_identity_files; i++) {
   3324 		free(o->identity_files[i]);
   3325 		sshkey_free(o->identity_keys[i]);
   3326 	}
   3327 	for (i = 0; i < o->num_certificate_files; i++) {
   3328 		free(o->certificate_files[i]);
   3329 		sshkey_free(o->certificates[i]);
   3330 	}
   3331 	free(o->identity_agent);
   3332 	for (i = 0; i < o->num_local_forwards; i++) {
   3333 		free(o->local_forwards[i].listen_host);
   3334 		free(o->local_forwards[i].listen_path);
   3335 		free(o->local_forwards[i].connect_host);
   3336 		free(o->local_forwards[i].connect_path);
   3337 	}
   3338 	free(o->local_forwards);
   3339 	for (i = 0; i < o->num_remote_forwards; i++) {
   3340 		free(o->remote_forwards[i].listen_host);
   3341 		free(o->remote_forwards[i].listen_path);
   3342 		free(o->remote_forwards[i].connect_host);
   3343 		free(o->remote_forwards[i].connect_path);
   3344 	}
   3345 	free(o->remote_forwards);
   3346 	free(o->stdio_forward_host);
   3347 	FREE_ARRAY(u_int, o->num_send_env, o->send_env);
   3348 	free(o->send_env);
   3349 	FREE_ARRAY(u_int, o->num_setenv, o->setenv);
   3350 	free(o->setenv);
   3351 	free(o->control_path);
   3352 	free(o->local_command);
   3353 	free(o->remote_command);
   3354 	FREE_ARRAY(int, o->num_canonical_domains, o->canonical_domains);
   3355 	for (i = 0; i < o->num_permitted_cnames; i++) {
   3356 		free(o->permitted_cnames[i].source_list);
   3357 		free(o->permitted_cnames[i].target_list);
   3358 	}
   3359 	FREE_ARRAY(u_int, o->num_revoked_host_keys, o->revoked_host_keys);
   3360 	free(o->revoked_host_keys);
   3361 	free(o->hostbased_accepted_algos);
   3362 	free(o->pubkey_accepted_algos);
   3363 	free(o->jump_user);
   3364 	free(o->jump_host);
   3365 	free(o->jump_extra);
   3366 	free(o->ignored_unknown);
   3367 	explicit_bzero(o, sizeof(*o));
   3368 #undef FREE_ARRAY
   3369 }
   3370 
   3371 struct fwdarg {
   3372 	char *arg;
   3373 	int ispath;
   3374 };
   3375 
   3376 /*
   3377  * parse_fwd_field
   3378  * parses the next field in a port forwarding specification.
   3379  * sets fwd to the parsed field and advances p past the colon
   3380  * or sets it to NULL at end of string.
   3381  * returns 0 on success, else non-zero.
   3382  */
   3383 static int
   3384 parse_fwd_field(char **p, struct fwdarg *fwd)
   3385 {
   3386 	char *ep, *cp = *p;
   3387 	int ispath = 0;
   3388 
   3389 	if (*cp == '\0') {
   3390 		*p = NULL;
   3391 		return -1;	/* end of string */
   3392 	}
   3393 
   3394 	/*
   3395 	 * A field escaped with square brackets is used literally.
   3396 	 * XXX - allow ']' to be escaped via backslash?
   3397 	 */
   3398 	if (*cp == '[') {
   3399 		/* find matching ']' */
   3400 		for (ep = cp + 1; *ep != ']' && *ep != '\0'; ep++) {
   3401 			if (*ep == '/')
   3402 				ispath = 1;
   3403 		}
   3404 		/* no matching ']' or not at end of field. */
   3405 		if (ep[0] != ']' || (ep[1] != ':' && ep[1] != '\0'))
   3406 			return -1;
   3407 		/* NUL terminate the field and advance p past the colon */
   3408 		*ep++ = '\0';
   3409 		if (*ep != '\0')
   3410 			*ep++ = '\0';
   3411 		fwd->arg = cp + 1;
   3412 		fwd->ispath = ispath;
   3413 		*p = ep;
   3414 		return 0;
   3415 	}
   3416 
   3417 	for (cp = *p; *cp != '\0'; cp++) {
   3418 		switch (*cp) {
   3419 		case '\\':
   3420 			memmove(cp, cp + 1, strlen(cp + 1) + 1);
   3421 			if (*cp == '\0')
   3422 				return -1;
   3423 			break;
   3424 		case '/':
   3425 			ispath = 1;
   3426 			break;
   3427 		case ':':
   3428 			*cp++ = '\0';
   3429 			goto done;
   3430 		}
   3431 	}
   3432 done:
   3433 	fwd->arg = *p;
   3434 	fwd->ispath = ispath;
   3435 	*p = cp;
   3436 	return 0;
   3437 }
   3438 
   3439 /*
   3440  * parse_forward
   3441  * parses a string containing a port forwarding specification of the form:
   3442  *   dynamicfwd == 0
   3443  *	[listenhost:]listenport|listenpath:connecthost:connectport|connectpath
   3444  *	listenpath:connectpath
   3445  *   dynamicfwd == 1
   3446  *	[listenhost:]listenport
   3447  * returns number of arguments parsed or zero on error
   3448  */
   3449 int
   3450 parse_forward(struct Forward *fwd, const char *fwdspec, int dynamicfwd, int remotefwd)
   3451 {
   3452 	struct fwdarg fwdargs[4];
   3453 	char *p, *cp;
   3454 	int i, err;
   3455 
   3456 	memset(fwd, 0, sizeof(*fwd));
   3457 	memset(fwdargs, 0, sizeof(fwdargs));
   3458 
   3459 	/*
   3460 	 * We expand environment variables before checking if we think they're
   3461 	 * paths so that if ${VAR} expands to a fully qualified path it is
   3462 	 * treated as a path.
   3463 	 */
   3464 	cp = p = dollar_expand(&err, fwdspec);
   3465 	if (p == NULL || err)
   3466 		return 0;
   3467 
   3468 	/* skip leading spaces */
   3469 	while (isspace((u_char)*cp))
   3470 		cp++;
   3471 
   3472 	for (i = 0; i < 4; ++i) {
   3473 		if (parse_fwd_field(&cp, &fwdargs[i]) != 0)
   3474 			break;
   3475 	}
   3476 
   3477 	/* Check for trailing garbage */
   3478 	if (cp != NULL && *cp != '\0') {
   3479 		i = 0;	/* failure */
   3480 	}
   3481 
   3482 	switch (i) {
   3483 	case 1:
   3484 		if (fwdargs[0].ispath) {
   3485 			fwd->listen_path = xstrdup(fwdargs[0].arg);
   3486 			fwd->listen_port = PORT_STREAMLOCAL;
   3487 		} else {
   3488 			fwd->listen_host = NULL;
   3489 			fwd->listen_port = a2port(fwdargs[0].arg);
   3490 		}
   3491 		fwd->connect_host = xstrdup("socks");
   3492 		break;
   3493 
   3494 	case 2:
   3495 		if (fwdargs[0].ispath && fwdargs[1].ispath) {
   3496 			fwd->listen_path = xstrdup(fwdargs[0].arg);
   3497 			fwd->listen_port = PORT_STREAMLOCAL;
   3498 			fwd->connect_path = xstrdup(fwdargs[1].arg);
   3499 			fwd->connect_port = PORT_STREAMLOCAL;
   3500 		} else if (fwdargs[1].ispath) {
   3501 			fwd->listen_host = NULL;
   3502 			fwd->listen_port = a2port(fwdargs[0].arg);
   3503 			fwd->connect_path = xstrdup(fwdargs[1].arg);
   3504 			fwd->connect_port = PORT_STREAMLOCAL;
   3505 		} else {
   3506 			fwd->listen_host = xstrdup(fwdargs[0].arg);
   3507 			fwd->listen_port = a2port(fwdargs[1].arg);
   3508 			fwd->connect_host = xstrdup("socks");
   3509 		}
   3510 		break;
   3511 
   3512 	case 3:
   3513 		if (fwdargs[0].ispath) {
   3514 			fwd->listen_path = xstrdup(fwdargs[0].arg);
   3515 			fwd->listen_port = PORT_STREAMLOCAL;
   3516 			fwd->connect_host = xstrdup(fwdargs[1].arg);
   3517 			fwd->connect_port = a2port(fwdargs[2].arg);
   3518 		} else if (fwdargs[2].ispath) {
   3519 			fwd->listen_host = xstrdup(fwdargs[0].arg);
   3520 			fwd->listen_port = a2port(fwdargs[1].arg);
   3521 			fwd->connect_path = xstrdup(fwdargs[2].arg);
   3522 			fwd->connect_port = PORT_STREAMLOCAL;
   3523 		} else {
   3524 			fwd->listen_host = NULL;
   3525 			fwd->listen_port = a2port(fwdargs[0].arg);
   3526 			fwd->connect_host = xstrdup(fwdargs[1].arg);
   3527 			fwd->connect_port = a2port(fwdargs[2].arg);
   3528 		}
   3529 		break;
   3530 
   3531 	case 4:
   3532 		fwd->listen_host = xstrdup(fwdargs[0].arg);
   3533 		fwd->listen_port = a2port(fwdargs[1].arg);
   3534 		fwd->connect_host = xstrdup(fwdargs[2].arg);
   3535 		fwd->connect_port = a2port(fwdargs[3].arg);
   3536 		break;
   3537 	default:
   3538 		i = 0; /* failure */
   3539 	}
   3540 
   3541 	free(p);
   3542 
   3543 	if (dynamicfwd) {
   3544 		if (!(i == 1 || i == 2))
   3545 			goto fail_free;
   3546 	} else {
   3547 		if (!(i == 3 || i == 4)) {
   3548 			if (fwd->connect_path == NULL &&
   3549 			    fwd->listen_path == NULL)
   3550 				goto fail_free;
   3551 		}
   3552 		if (fwd->connect_port <= 0 && fwd->connect_path == NULL)
   3553 			goto fail_free;
   3554 	}
   3555 
   3556 	if ((fwd->listen_port < 0 && fwd->listen_path == NULL) ||
   3557 	    (!remotefwd && fwd->listen_port == 0))
   3558 		goto fail_free;
   3559 	if (fwd->connect_host != NULL &&
   3560 	    strlen(fwd->connect_host) >= NI_MAXHOST)
   3561 		goto fail_free;
   3562 	/*
   3563 	 * XXX - if connecting to a remote socket, max sun len may not
   3564 	 * match this host
   3565 	 */
   3566 	if (fwd->connect_path != NULL &&
   3567 	    strlen(fwd->connect_path) >= PATH_MAX_SUN)
   3568 		goto fail_free;
   3569 	if (fwd->listen_host != NULL &&
   3570 	    strlen(fwd->listen_host) >= NI_MAXHOST)
   3571 		goto fail_free;
   3572 	if (fwd->listen_path != NULL &&
   3573 	    strlen(fwd->listen_path) >= PATH_MAX_SUN)
   3574 		goto fail_free;
   3575 
   3576 	return (i);
   3577 
   3578  fail_free:
   3579 	free(fwd->connect_host);
   3580 	fwd->connect_host = NULL;
   3581 	free(fwd->connect_path);
   3582 	fwd->connect_path = NULL;
   3583 	free(fwd->listen_host);
   3584 	fwd->listen_host = NULL;
   3585 	free(fwd->listen_path);
   3586 	fwd->listen_path = NULL;
   3587 	return (0);
   3588 }
   3589 
   3590 int
   3591 ssh_valid_hostname(const char *s)
   3592 {
   3593 	size_t i;
   3594 
   3595 	if (*s == '-')
   3596 		return 0;
   3597 	for (i = 0; s[i] != 0; i++) {
   3598 		if (strchr("'`\"$\\;&<>|(){},", s[i]) != NULL ||
   3599 		    isspace((u_char)s[i]) || iscntrl((u_char)s[i]))
   3600 			return 0;
   3601 	}
   3602 	return 1;
   3603 }
   3604 
   3605 int
   3606 ssh_valid_ruser(const char *s)
   3607 {
   3608 	size_t i;
   3609 
   3610 	if (*s == '-')
   3611 		return 0;
   3612 	for (i = 0; s[i] != 0; i++) {
   3613 		if (iscntrl((u_char)s[i]))
   3614 			return 0;
   3615 		if (strchr("'`\";&<>|(){}$\\", s[i]) != NULL)
   3616 			return 0;
   3617 		/* Disallow '-' after whitespace */
   3618 		if (isspace((u_char)s[i]) && s[i + 1] == '-')
   3619 			return 0;
   3620 	}
   3621 	return 1;
   3622 }
   3623 
   3624 int
   3625 parse_jump(const char *s, Options *o, int strict, int active)
   3626 {
   3627 	char *orig = NULL, *sdup = NULL, *cp;
   3628 	char *tmp_user = NULL, *tmp_host = NULL, *host = NULL, *user = NULL;
   3629 	int r, ret = -1, tmp_port = -1, port = -1, first = 1;
   3630 
   3631 	if (strcasecmp(s, "none") == 0) {
   3632 		if (active && o->jump_host == NULL) {
   3633 			o->jump_host = xstrdup("none");
   3634 			o->jump_port = 0;
   3635 		}
   3636 		return 0;
   3637 	}
   3638 
   3639 	orig = xstrdup(s);
   3640 	if ((cp = strchr(orig, '#')) != NULL)
   3641 		*cp = '\0';
   3642 	rtrim(orig);
   3643 
   3644 	active &= o->proxy_command == NULL && o->jump_host == NULL;
   3645 	sdup = xstrdup(orig);
   3646 	do {
   3647 		/* Work backwards through string */
   3648 		if ((cp = strrchr(sdup, ',')) == NULL)
   3649 			cp = sdup; /* last */
   3650 		else
   3651 			*cp++ = '\0';
   3652 
   3653 		r = parse_ssh_uri(cp, &tmp_user, &tmp_host, &tmp_port);
   3654 		if (r == -1 || (r == 1 && parse_user_host_port(cp,
   3655 		    &tmp_user, &tmp_host, &tmp_port) != 0))
   3656 			goto out; /* error already logged */
   3657 		if (strict) {
   3658 			if (!ssh_valid_hostname(tmp_host)) {
   3659 				error_f("invalid hostname \"%s\"", tmp_host);
   3660 				goto out;
   3661 			}
   3662 			if (tmp_user != NULL && !ssh_valid_ruser(tmp_user)) {
   3663 				error_f("invalid username \"%s\"", tmp_user);
   3664 				goto out;
   3665 			}
   3666 		}
   3667 		if (first) {
   3668 			user = tmp_user;
   3669 			host = tmp_host;
   3670 			port = tmp_port;
   3671 			tmp_user = tmp_host = NULL; /* transferred */
   3672 		}
   3673 		first = 0; /* only check syntax for subsequent hosts */
   3674 		free(tmp_user);
   3675 		free(tmp_host);
   3676 		tmp_user = tmp_host = NULL;
   3677 		tmp_port = -1;
   3678 	} while (cp != sdup);
   3679 
   3680 	/* success */
   3681 	if (active) {
   3682 		o->jump_user = user;
   3683 		o->jump_host = host;
   3684 		o->jump_port = port;
   3685 		o->proxy_command = xstrdup("none");
   3686 		user = host = NULL; /* transferred */
   3687 		if (orig != NULL && (cp = strrchr(orig, ',')) != NULL) {
   3688 			o->jump_extra = xstrdup(orig);
   3689 			o->jump_extra[cp - orig] = '\0';
   3690 		}
   3691 	}
   3692 	ret = 0;
   3693  out:
   3694 	free(orig);
   3695 	free(sdup);
   3696 	free(tmp_user);
   3697 	free(tmp_host);
   3698 	free(user);
   3699 	free(host);
   3700 	return ret;
   3701 }
   3702 
   3703 int
   3704 parse_ssh_uri(const char *uri, char **userp, char **hostp, int *portp)
   3705 {
   3706 	char *user = NULL, *host = NULL, *path = NULL;
   3707 	int r, port;
   3708 
   3709 	r = parse_uri("ssh", uri, &user, &host, &port, &path);
   3710 	if (r == 0 && path != NULL)
   3711 		r = -1;		/* path not allowed */
   3712 	if (r == 0) {
   3713 		if (userp != NULL) {
   3714 			*userp = user;
   3715 			user = NULL;
   3716 		}
   3717 		if (hostp != NULL) {
   3718 			*hostp = host;
   3719 			host = NULL;
   3720 		}
   3721 		if (portp != NULL)
   3722 			*portp = port;
   3723 	}
   3724 	free(user);
   3725 	free(host);
   3726 	free(path);
   3727 	return r;
   3728 }
   3729 
   3730 /* XXX the following is a near-verbatim copy from servconf.c; refactor */
   3731 static const char *
   3732 fmt_multistate_int(int val, const struct multistate *m)
   3733 {
   3734 	u_int i;
   3735 
   3736 	for (i = 0; m[i].key != NULL; i++) {
   3737 		if (m[i].value == val)
   3738 			return m[i].key;
   3739 	}
   3740 	return "UNKNOWN";
   3741 }
   3742 
   3743 static const char *
   3744 fmt_intarg(OpCodes code, int val)
   3745 {
   3746 	if (val == -1)
   3747 		return "unset";
   3748 	switch (code) {
   3749 	case oAddressFamily:
   3750 		return fmt_multistate_int(val, multistate_addressfamily);
   3751 	case oCompression:
   3752 		return fmt_multistate_int(val, multistate_compression);
   3753 	case oVerifyHostKeyDNS:
   3754 	case oUpdateHostkeys:
   3755 		return fmt_multistate_int(val, multistate_yesnoask);
   3756 	case oStrictHostKeyChecking:
   3757 		return fmt_multistate_int(val, multistate_strict_hostkey);
   3758 	case oControlMaster:
   3759 		return fmt_multistate_int(val, multistate_controlmaster);
   3760 	case oTunnel:
   3761 		return fmt_multistate_int(val, multistate_tunnel);
   3762 	case oRequestTTY:
   3763 		return fmt_multistate_int(val, multistate_requesttty);
   3764 	case oSessionType:
   3765 		return fmt_multistate_int(val, multistate_sessiontype);
   3766 	case oCanonicalizeHostname:
   3767 		return fmt_multistate_int(val, multistate_canonicalizehostname);
   3768 	case oAddKeysToAgent:
   3769 		return fmt_multistate_int(val, multistate_yesnoaskconfirm);
   3770 	case oPubkeyAuthentication:
   3771 		return fmt_multistate_int(val, multistate_pubkey_auth);
   3772 	case oTCPKeepAlive:
   3773 		return fmt_multistate_int(val, multistate_keepalives);
   3774 	case oFingerprintHash:
   3775 		return ssh_digest_alg_name(val);
   3776 	default:
   3777 		switch (val) {
   3778 		case 0:
   3779 			return "no";
   3780 		case 1:
   3781 			return "yes";
   3782 		default:
   3783 			return "UNKNOWN";
   3784 		}
   3785 	}
   3786 }
   3787 
   3788 static const char *
   3789 lookup_opcode_name(OpCodes code)
   3790 {
   3791 	u_int i;
   3792 
   3793 	for (i = 0; keywords[i].name != NULL; i++)
   3794 		if (keywords[i].opcode == code)
   3795 			return(keywords[i].name);
   3796 	return "UNKNOWN";
   3797 }
   3798 
   3799 static void
   3800 dump_cfg_int(OpCodes code, int val)
   3801 {
   3802 	if (code == oObscureKeystrokeTiming) {
   3803 		if (val == 0) {
   3804 			printf("%s no\n", lookup_opcode_name(code));
   3805 			return;
   3806 		} else if (val == SSH_KEYSTROKE_DEFAULT_INTERVAL_MS) {
   3807 			printf("%s yes\n", lookup_opcode_name(code));
   3808 			return;
   3809 		}
   3810 		/* FALLTHROUGH */
   3811 	}
   3812 	printf("%s %d\n", lookup_opcode_name(code), val);
   3813 }
   3814 
   3815 static void
   3816 dump_cfg_fmtint(OpCodes code, int val)
   3817 {
   3818 	printf("%s %s\n", lookup_opcode_name(code), fmt_intarg(code, val));
   3819 }
   3820 
   3821 static void
   3822 dump_cfg_string(OpCodes code, const char *val)
   3823 {
   3824 	if (val == NULL)
   3825 		return;
   3826 	printf("%s %s\n", lookup_opcode_name(code), val);
   3827 }
   3828 
   3829 static void
   3830 dump_cfg_strarray(OpCodes code, u_int count, char **vals)
   3831 {
   3832 	u_int i;
   3833 
   3834 	for (i = 0; i < count; i++)
   3835 		printf("%s %s\n", lookup_opcode_name(code), vals[i]);
   3836 }
   3837 
   3838 static void
   3839 dump_cfg_strarray_oneline(OpCodes code, u_int count, char **vals)
   3840 {
   3841 	u_int i;
   3842 
   3843 	printf("%s", lookup_opcode_name(code));
   3844 	if (count == 0)
   3845 		printf(" none");
   3846 	for (i = 0; i < count; i++)
   3847 		printf(" %s",  vals[i]);
   3848 	printf("\n");
   3849 }
   3850 
   3851 static void
   3852 dump_cfg_forwards(OpCodes code, u_int count, const struct Forward *fwds)
   3853 {
   3854 	const struct Forward *fwd;
   3855 	u_int i;
   3856 
   3857 	/* oDynamicForward */
   3858 	for (i = 0; i < count; i++) {
   3859 		fwd = &fwds[i];
   3860 		if (code == oDynamicForward && fwd->connect_host != NULL &&
   3861 		    strcmp(fwd->connect_host, "socks") != 0)
   3862 			continue;
   3863 		if (code == oLocalForward && fwd->connect_host != NULL &&
   3864 		    strcmp(fwd->connect_host, "socks") == 0)
   3865 			continue;
   3866 		printf("%s", lookup_opcode_name(code));
   3867 		if (fwd->listen_port == PORT_STREAMLOCAL)
   3868 			printf(" %s", fwd->listen_path);
   3869 		else if (fwd->listen_host == NULL)
   3870 			printf(" %d", fwd->listen_port);
   3871 		else {
   3872 			printf(" [%s]:%d",
   3873 			    fwd->listen_host, fwd->listen_port);
   3874 		}
   3875 		if (code != oDynamicForward) {
   3876 			if (fwd->connect_port == PORT_STREAMLOCAL)
   3877 				printf(" %s", fwd->connect_path);
   3878 			else if (fwd->connect_host == NULL)
   3879 				printf(" %d", fwd->connect_port);
   3880 			else {
   3881 				printf(" [%s]:%d",
   3882 				    fwd->connect_host, fwd->connect_port);
   3883 			}
   3884 		}
   3885 		printf("\n");
   3886 	}
   3887 }
   3888 
   3889 void
   3890 dump_client_config(Options *o, const char *host)
   3891 {
   3892 	int i, r;
   3893 	char buf[8], *all_key;
   3894 
   3895 	/*
   3896 	 * Expand HostKeyAlgorithms name lists. This isn't handled in
   3897 	 * fill_default_options() like the other algorithm lists because
   3898 	 * the host key algorithms are by default dynamically chosen based
   3899 	 * on the host's keys found in known_hosts.
   3900 	 */
   3901 	all_key = sshkey_alg_list(0, 0, 1, ',');
   3902 	if ((r = kex_assemble_names(&o->hostkeyalgorithms, kex_default_pk_alg(),
   3903 	    all_key)) != 0)
   3904 		fatal_fr(r, "expand HostKeyAlgorithms");
   3905 	free(all_key);
   3906 
   3907 	/* Most interesting options first: user, host, port */
   3908 	dump_cfg_string(oHost, o->host_arg);
   3909 	dump_cfg_string(oUser, o->user);
   3910 	dump_cfg_string(oHostname, host);
   3911 	dump_cfg_int(oPort, o->port);
   3912 
   3913 	/* Flag options */
   3914 	dump_cfg_fmtint(oAddressFamily, o->address_family);
   3915 	dump_cfg_fmtint(oBatchMode, o->batch_mode);
   3916 	dump_cfg_fmtint(oCanonicalizeFallbackLocal, o->canonicalize_fallback_local);
   3917 	dump_cfg_fmtint(oCanonicalizeHostname, o->canonicalize_hostname);
   3918 	dump_cfg_fmtint(oCheckHostIP, o->check_host_ip);
   3919 	dump_cfg_fmtint(oCompression, o->compression);
   3920 	dump_cfg_fmtint(oControlMaster, o->control_master);
   3921 	dump_cfg_fmtint(oEnableSSHKeysign, o->enable_ssh_keysign);
   3922 	dump_cfg_fmtint(oClearAllForwardings, o->clear_forwardings);
   3923 	dump_cfg_fmtint(oExitOnForwardFailure, o->exit_on_forward_failure);
   3924 	dump_cfg_fmtint(oFingerprintHash, o->fingerprint_hash);
   3925 	dump_cfg_fmtint(oForwardX11, o->forward_x11);
   3926 	dump_cfg_fmtint(oForwardX11Trusted, o->forward_x11_trusted);
   3927 	dump_cfg_fmtint(oGatewayPorts, o->fwd_opts.gateway_ports);
   3928 #ifdef GSSAPI
   3929 	dump_cfg_fmtint(oGssAuthentication, o->gss_authentication);
   3930 	dump_cfg_fmtint(oGssDelegateCreds, o->gss_deleg_creds);
   3931 #endif /* GSSAPI */
   3932 	dump_cfg_fmtint(oHashKnownHosts, o->hash_known_hosts);
   3933 	dump_cfg_fmtint(oHostbasedAuthentication, o->hostbased_authentication);
   3934 	dump_cfg_fmtint(oIdentitiesOnly, o->identities_only);
   3935 	dump_cfg_fmtint(oKbdInteractiveAuthentication, o->kbd_interactive_authentication);
   3936 	dump_cfg_fmtint(oNoHostAuthenticationForLocalhost, o->no_host_authentication_for_localhost);
   3937 	dump_cfg_fmtint(oPasswordAuthentication, o->password_authentication);
   3938 	dump_cfg_fmtint(oPermitLocalCommand, o->permit_local_command);
   3939 	dump_cfg_fmtint(oProxyUseFdpass, o->proxy_use_fdpass);
   3940 	dump_cfg_fmtint(oPubkeyAuthentication, o->pubkey_authentication);
   3941 	dump_cfg_fmtint(oRequestTTY, o->request_tty);
   3942 	dump_cfg_fmtint(oSessionType, o->session_type);
   3943 	dump_cfg_fmtint(oStdinNull, o->stdin_null);
   3944 	dump_cfg_fmtint(oForkAfterAuthentication, o->fork_after_authentication);
   3945 	dump_cfg_fmtint(oStreamLocalBindUnlink, o->fwd_opts.streamlocal_bind_unlink);
   3946 	dump_cfg_fmtint(oStrictHostKeyChecking, o->strict_host_key_checking);
   3947 	dump_cfg_fmtint(oTCPKeepAlive, o->tcp_keep_alive);
   3948 	dump_cfg_fmtint(oTunnel, o->tun_open);
   3949 	dump_cfg_fmtint(oVerifyHostKeyDNS, o->verify_host_key_dns);
   3950 	dump_cfg_fmtint(oVisualHostKey, o->visual_host_key);
   3951 	dump_cfg_fmtint(oUpdateHostkeys, o->update_hostkeys);
   3952 	dump_cfg_fmtint(oEnableEscapeCommandline, o->enable_escape_commandline);
   3953 	dump_cfg_fmtint(oWarnWeakCrypto, o->warn_weak_crypto);
   3954 
   3955 	/* Integer options */
   3956 	dump_cfg_int(oCanonicalizeMaxDots, o->canonicalize_max_dots);
   3957 	dump_cfg_int(oConnectionAttempts, o->connection_attempts);
   3958 	dump_cfg_int(oForwardX11Timeout, o->forward_x11_timeout);
   3959 	dump_cfg_int(oNumberOfPasswordPrompts, o->number_of_password_prompts);
   3960 	dump_cfg_int(oServerAliveCountMax, o->server_alive_count_max);
   3961 	dump_cfg_int(oServerAliveInterval, o->server_alive_interval);
   3962 	dump_cfg_int(oRequiredRSASize, o->required_rsa_size);
   3963 	dump_cfg_int(oObscureKeystrokeTiming,
   3964 	    o->obscure_keystroke_timing_interval);
   3965 
   3966 	/* String options */
   3967 	dump_cfg_string(oBindAddress, o->bind_address);
   3968 	dump_cfg_string(oBindInterface, o->bind_interface);
   3969 	dump_cfg_string(oCiphers, o->ciphers);
   3970 	dump_cfg_string(oControlPath, o->control_path);
   3971 	dump_cfg_string(oHostKeyAlgorithms, o->hostkeyalgorithms);
   3972 	dump_cfg_string(oHostKeyAlias, o->host_key_alias);
   3973 	dump_cfg_string(oHostbasedAcceptedAlgorithms, o->hostbased_accepted_algos);
   3974 	dump_cfg_string(oIdentityAgent, o->identity_agent);
   3975 	dump_cfg_string(oIgnoreUnknown, o->ignored_unknown);
   3976 	dump_cfg_string(oKbdInteractiveDevices, o->kbd_interactive_devices);
   3977 	dump_cfg_string(oKexAlgorithms, o->kex_algorithms);
   3978 	dump_cfg_string(oCASignatureAlgorithms, o->ca_sign_algorithms);
   3979 	dump_cfg_string(oLocalCommand, o->local_command);
   3980 	dump_cfg_string(oRemoteCommand, o->remote_command);
   3981 	dump_cfg_string(oLogLevel, log_level_name(o->log_level));
   3982 	dump_cfg_string(oMacs, o->macs);
   3983 #ifdef ENABLE_PKCS11
   3984 	dump_cfg_string(oPKCS11Provider, o->pkcs11_provider);
   3985 #endif
   3986 	dump_cfg_string(oSecurityKeyProvider, o->sk_provider);
   3987 	dump_cfg_string(oPreferredAuthentications, o->preferred_authentications);
   3988 	dump_cfg_string(oPubkeyAcceptedAlgorithms, o->pubkey_accepted_algos);
   3989 	dump_cfg_string(oXAuthLocation, o->xauth_location);
   3990 	dump_cfg_string(oKnownHostsCommand, o->known_hosts_command);
   3991 	dump_cfg_string(oTag, o->tag);
   3992 	dump_cfg_string(oVersionAddendum, o->version_addendum);
   3993 
   3994 	/* Forwards */
   3995 	dump_cfg_forwards(oDynamicForward, o->num_local_forwards, o->local_forwards);
   3996 	dump_cfg_forwards(oLocalForward, o->num_local_forwards, o->local_forwards);
   3997 	dump_cfg_forwards(oRemoteForward, o->num_remote_forwards, o->remote_forwards);
   3998 
   3999 	/* String array options */
   4000 	dump_cfg_strarray(oIdentityFile, o->num_identity_files, o->identity_files);
   4001 	dump_cfg_strarray_oneline(oCanonicalDomains, o->num_canonical_domains, o->canonical_domains);
   4002 	dump_cfg_strarray(oCertificateFile, o->num_certificate_files, o->certificate_files);
   4003 	dump_cfg_strarray_oneline(oGlobalKnownHostsFile, o->num_system_hostfiles, o->system_hostfiles);
   4004 	dump_cfg_strarray_oneline(oUserKnownHostsFile, o->num_user_hostfiles, o->user_hostfiles);
   4005 	dump_cfg_strarray_oneline(oRevokedHostKeys, o->num_revoked_host_keys, o->revoked_host_keys);
   4006 	dump_cfg_strarray(oSendEnv, o->num_send_env, o->send_env);
   4007 	dump_cfg_strarray(oSetEnv, o->num_setenv, o->setenv);
   4008 	dump_cfg_strarray_oneline(oLogVerbose,
   4009 	    o->num_log_verbose, o->log_verbose);
   4010 	dump_cfg_strarray_oneline(oChannelTimeout,
   4011 	    o->num_channel_timeouts, o->channel_timeouts);
   4012 
   4013 	/* Special cases */
   4014 
   4015 	/* PermitRemoteOpen */
   4016 	if (o->num_permitted_remote_opens == 0)
   4017 		printf("%s any\n", lookup_opcode_name(oPermitRemoteOpen));
   4018 	else
   4019 		dump_cfg_strarray_oneline(oPermitRemoteOpen,
   4020 		    o->num_permitted_remote_opens, o->permitted_remote_opens);
   4021 
   4022 	/* AddKeysToAgent */
   4023 	if (o->add_keys_to_agent_lifespan <= 0)
   4024 		dump_cfg_fmtint(oAddKeysToAgent, o->add_keys_to_agent);
   4025 	else {
   4026 		printf("addkeystoagent%s %d\n",
   4027 		    o->add_keys_to_agent == 3 ? " confirm" : "",
   4028 		    o->add_keys_to_agent_lifespan);
   4029 	}
   4030 
   4031 	/* oForwardAgent */
   4032 	if (o->forward_agent_sock_path == NULL)
   4033 		dump_cfg_fmtint(oForwardAgent, o->forward_agent);
   4034 	else
   4035 		dump_cfg_string(oForwardAgent, o->forward_agent_sock_path);
   4036 
   4037 	/* oConnectTimeout */
   4038 	if (o->connection_timeout == -1)
   4039 		printf("connecttimeout none\n");
   4040 	else
   4041 		dump_cfg_int(oConnectTimeout, o->connection_timeout);
   4042 
   4043 	/* oTunnelDevice */
   4044 	printf("tunneldevice");
   4045 	if (o->tun_local == SSH_TUNID_ANY)
   4046 		printf(" any");
   4047 	else
   4048 		printf(" %d", o->tun_local);
   4049 	if (o->tun_remote == SSH_TUNID_ANY)
   4050 		printf(":any");
   4051 	else
   4052 		printf(":%d", o->tun_remote);
   4053 	printf("\n");
   4054 
   4055 	/* oCanonicalizePermittedCNAMEs */
   4056 	printf("canonicalizepermittedcnames");
   4057 	if (o->num_permitted_cnames == 0)
   4058 		printf(" none");
   4059 	for (i = 0; i < o->num_permitted_cnames; i++) {
   4060 		printf(" %s:%s", o->permitted_cnames[i].source_list,
   4061 		    o->permitted_cnames[i].target_list);
   4062 	}
   4063 	printf("\n");
   4064 
   4065 	/* oControlPersist */
   4066 	if (o->control_persist == 0 || o->control_persist_timeout == 0)
   4067 		dump_cfg_fmtint(oControlPersist, o->control_persist);
   4068 	else
   4069 		dump_cfg_int(oControlPersist, o->control_persist_timeout);
   4070 
   4071 	/* oEscapeChar */
   4072 	if (o->escape_char == SSH_ESCAPECHAR_NONE)
   4073 		printf("escapechar none\n");
   4074 	else {
   4075 		vis(buf, o->escape_char, VIS_WHITE, 0);
   4076 		printf("escapechar %s\n", buf);
   4077 	}
   4078 
   4079 	/* oIPQoS */
   4080 	printf("ipqos %s ", iptos2str(o->ip_qos_interactive));
   4081 	printf("%s\n", iptos2str(o->ip_qos_bulk));
   4082 
   4083 	/* oRekeyLimit */
   4084 	printf("rekeylimit %llu %d\n",
   4085 	    (unsigned long long)o->rekey_limit, o->rekey_interval);
   4086 
   4087 	/* oStreamLocalBindMask */
   4088 	printf("streamlocalbindmask 0%o\n",
   4089 	    o->fwd_opts.streamlocal_bind_mask);
   4090 
   4091 	/* oLogFacility */
   4092 	printf("syslogfacility %s\n", log_facility_name(o->log_facility));
   4093 
   4094 	/* oProxyCommand / oProxyJump */
   4095 	if (o->jump_host == NULL)
   4096 		dump_cfg_string(oProxyCommand, o->proxy_command);
   4097 	else {
   4098 		/* Check for numeric addresses */
   4099 		i = strchr(o->jump_host, ':') != NULL ||
   4100 		    strspn(o->jump_host, "1234567890.") == strlen(o->jump_host);
   4101 		snprintf(buf, sizeof(buf), "%d", o->jump_port);
   4102 		printf("proxyjump %s%s%s%s%s%s%s%s%s\n",
   4103 		    /* optional additional jump spec */
   4104 		    o->jump_extra == NULL ? "" : o->jump_extra,
   4105 		    o->jump_extra == NULL ? "" : ",",
   4106 		    /* optional user */
   4107 		    o->jump_user == NULL ? "" : o->jump_user,
   4108 		    o->jump_user == NULL ? "" : "@",
   4109 		    /* opening [ if hostname is numeric */
   4110 		    i ? "[" : "",
   4111 		    /* mandatory hostname */
   4112 		    o->jump_host,
   4113 		    /* closing ] if hostname is numeric */
   4114 		    i ? "]" : "",
   4115 		    /* optional port number */
   4116 		    o->jump_port <= 0 ? "" : ":",
   4117 		    o->jump_port <= 0 ? "" : buf);
   4118 	}
   4119 }
   4120