xref: /freebsd/crypto/openssh/readconf.c (revision 6486b015fc84e96725fef22b0e3363351399ae83)
1 /* $OpenBSD: readconf.c,v 1.193 2011/05/24 07:15:47 djm Exp $ */
2 /* $FreeBSD$ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * Functions for reading the configuration files.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  */
15 
16 #include "includes.h"
17 __RCSID("$FreeBSD$");
18 
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/socket.h>
22 #include <sys/sysctl.h>
23 
24 #include <netinet/in.h>
25 #include <netinet/in_systm.h>
26 #include <netinet/ip.h>
27 
28 #include <ctype.h>
29 #include <errno.h>
30 #include <netdb.h>
31 #include <signal.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <unistd.h>
36 
37 #include "xmalloc.h"
38 #include "ssh.h"
39 #include "compat.h"
40 #include "cipher.h"
41 #include "pathnames.h"
42 #include "log.h"
43 #include "key.h"
44 #include "readconf.h"
45 #include "match.h"
46 #include "misc.h"
47 #include "buffer.h"
48 #include "kex.h"
49 #include "mac.h"
50 #include "version.h"
51 
52 /* Format of the configuration file:
53 
54    # Configuration data is parsed as follows:
55    #  1. command line options
56    #  2. user-specific file
57    #  3. system-wide file
58    # Any configuration value is only changed the first time it is set.
59    # Thus, host-specific definitions should be at the beginning of the
60    # configuration file, and defaults at the end.
61 
62    # Host-specific declarations.  These may override anything above.  A single
63    # host may match multiple declarations; these are processed in the order
64    # that they are given in.
65 
66    Host *.ngs.fi ngs.fi
67      User foo
68 
69    Host fake.com
70      HostName another.host.name.real.org
71      User blaah
72      Port 34289
73      ForwardX11 no
74      ForwardAgent no
75 
76    Host books.com
77      RemoteForward 9999 shadows.cs.hut.fi:9999
78      Cipher 3des
79 
80    Host fascist.blob.com
81      Port 23123
82      User tylonen
83      PasswordAuthentication no
84 
85    Host puukko.hut.fi
86      User t35124p
87      ProxyCommand ssh-proxy %h %p
88 
89    Host *.fr
90      PublicKeyAuthentication no
91 
92    Host *.su
93      Cipher none
94      PasswordAuthentication no
95 
96    Host vpn.fake.com
97      Tunnel yes
98      TunnelDevice 3
99 
100    # Defaults for various options
101    Host *
102      ForwardAgent no
103      ForwardX11 no
104      PasswordAuthentication yes
105      RSAAuthentication yes
106      RhostsRSAAuthentication yes
107      StrictHostKeyChecking yes
108      TcpKeepAlive no
109      IdentityFile ~/.ssh/identity
110      Port 22
111      EscapeChar ~
112 
113 */
114 
115 /* Keyword tokens. */
116 
117 typedef enum {
118 	oBadOption,
119 	oForwardAgent, oForwardX11, oForwardX11Trusted, oForwardX11Timeout,
120 	oGatewayPorts, oExitOnForwardFailure,
121 	oPasswordAuthentication, oRSAAuthentication,
122 	oChallengeResponseAuthentication, oXAuthLocation,
123 	oIdentityFile, oHostName, oPort, oCipher, oRemoteForward, oLocalForward,
124 	oUser, oHost, oEscapeChar, oRhostsRSAAuthentication, oProxyCommand,
125 	oGlobalKnownHostsFile, oUserKnownHostsFile, oConnectionAttempts,
126 	oBatchMode, oCheckHostIP, oStrictHostKeyChecking, oCompression,
127 	oCompressionLevel, oTCPKeepAlive, oNumberOfPasswordPrompts,
128 	oUsePrivilegedPort, oLogLevel, oCiphers, oProtocol, oMacs,
129 	oGlobalKnownHostsFile2, oUserKnownHostsFile2, oPubkeyAuthentication,
130 	oKbdInteractiveAuthentication, oKbdInteractiveDevices, oHostKeyAlias,
131 	oDynamicForward, oPreferredAuthentications, oHostbasedAuthentication,
132 	oHostKeyAlgorithms, oBindAddress, oPKCS11Provider,
133 	oClearAllForwardings, oNoHostAuthenticationForLocalhost,
134 	oEnableSSHKeysign, oRekeyLimit, oVerifyHostKeyDNS, oConnectTimeout,
135 	oAddressFamily, oGssAuthentication, oGssDelegateCreds,
136 	oServerAliveInterval, oServerAliveCountMax, oIdentitiesOnly,
137 	oSendEnv, oControlPath, oControlMaster, oControlPersist,
138 	oHashKnownHosts,
139 	oTunnel, oTunnelDevice, oLocalCommand, oPermitLocalCommand,
140 	oVisualHostKey, oUseRoaming, oZeroKnowledgePasswordAuthentication,
141 	oKexAlgorithms, oIPQoS, oRequestTTY,
142 	oHPNDisabled, oHPNBufferSize, oTcpRcvBufPoll, oTcpRcvBuf,
143 #ifdef NONE_CIPHER_ENABLED
144 	oNoneEnabled, oNoneSwitch,
145 #endif
146 	oVersionAddendum,
147 	oDeprecated, oUnsupported
148 } OpCodes;
149 
150 /* Textual representations of the tokens. */
151 
152 static struct {
153 	const char *name;
154 	OpCodes opcode;
155 } keywords[] = {
156 	{ "forwardagent", oForwardAgent },
157 	{ "forwardx11", oForwardX11 },
158 	{ "forwardx11trusted", oForwardX11Trusted },
159 	{ "forwardx11timeout", oForwardX11Timeout },
160 	{ "exitonforwardfailure", oExitOnForwardFailure },
161 	{ "xauthlocation", oXAuthLocation },
162 	{ "gatewayports", oGatewayPorts },
163 	{ "useprivilegedport", oUsePrivilegedPort },
164 	{ "rhostsauthentication", oDeprecated },
165 	{ "passwordauthentication", oPasswordAuthentication },
166 	{ "kbdinteractiveauthentication", oKbdInteractiveAuthentication },
167 	{ "kbdinteractivedevices", oKbdInteractiveDevices },
168 	{ "rsaauthentication", oRSAAuthentication },
169 	{ "pubkeyauthentication", oPubkeyAuthentication },
170 	{ "dsaauthentication", oPubkeyAuthentication },		    /* alias */
171 	{ "rhostsrsaauthentication", oRhostsRSAAuthentication },
172 	{ "hostbasedauthentication", oHostbasedAuthentication },
173 	{ "challengeresponseauthentication", oChallengeResponseAuthentication },
174 	{ "skeyauthentication", oChallengeResponseAuthentication }, /* alias */
175 	{ "tisauthentication", oChallengeResponseAuthentication },  /* alias */
176 	{ "kerberosauthentication", oUnsupported },
177 	{ "kerberostgtpassing", oUnsupported },
178 	{ "afstokenpassing", oUnsupported },
179 #if defined(GSSAPI)
180 	{ "gssapiauthentication", oGssAuthentication },
181 	{ "gssapidelegatecredentials", oGssDelegateCreds },
182 #else
183 	{ "gssapiauthentication", oUnsupported },
184 	{ "gssapidelegatecredentials", oUnsupported },
185 #endif
186 	{ "fallbacktorsh", oDeprecated },
187 	{ "usersh", oDeprecated },
188 	{ "identityfile", oIdentityFile },
189 	{ "identityfile2", oIdentityFile },			/* obsolete */
190 	{ "identitiesonly", oIdentitiesOnly },
191 	{ "hostname", oHostName },
192 	{ "hostkeyalias", oHostKeyAlias },
193 	{ "proxycommand", oProxyCommand },
194 	{ "port", oPort },
195 	{ "cipher", oCipher },
196 	{ "ciphers", oCiphers },
197 	{ "macs", oMacs },
198 	{ "protocol", oProtocol },
199 	{ "remoteforward", oRemoteForward },
200 	{ "localforward", oLocalForward },
201 	{ "user", oUser },
202 	{ "host", oHost },
203 	{ "escapechar", oEscapeChar },
204 	{ "globalknownhostsfile", oGlobalKnownHostsFile },
205 	{ "globalknownhostsfile2", oDeprecated },
206 	{ "userknownhostsfile", oUserKnownHostsFile },
207 	{ "userknownhostsfile2", oDeprecated },
208 	{ "connectionattempts", oConnectionAttempts },
209 	{ "batchmode", oBatchMode },
210 	{ "checkhostip", oCheckHostIP },
211 	{ "stricthostkeychecking", oStrictHostKeyChecking },
212 	{ "compression", oCompression },
213 	{ "compressionlevel", oCompressionLevel },
214 	{ "tcpkeepalive", oTCPKeepAlive },
215 	{ "keepalive", oTCPKeepAlive },				/* obsolete */
216 	{ "numberofpasswordprompts", oNumberOfPasswordPrompts },
217 	{ "loglevel", oLogLevel },
218 	{ "dynamicforward", oDynamicForward },
219 	{ "preferredauthentications", oPreferredAuthentications },
220 	{ "hostkeyalgorithms", oHostKeyAlgorithms },
221 	{ "bindaddress", oBindAddress },
222 #ifdef ENABLE_PKCS11
223 	{ "smartcarddevice", oPKCS11Provider },
224 	{ "pkcs11provider", oPKCS11Provider },
225 #else
226 	{ "smartcarddevice", oUnsupported },
227 	{ "pkcs11provider", oUnsupported },
228 #endif
229 	{ "clearallforwardings", oClearAllForwardings },
230 	{ "enablesshkeysign", oEnableSSHKeysign },
231 	{ "verifyhostkeydns", oVerifyHostKeyDNS },
232 	{ "nohostauthenticationforlocalhost", oNoHostAuthenticationForLocalhost },
233 	{ "rekeylimit", oRekeyLimit },
234 	{ "connecttimeout", oConnectTimeout },
235 	{ "addressfamily", oAddressFamily },
236 	{ "serveraliveinterval", oServerAliveInterval },
237 	{ "serveralivecountmax", oServerAliveCountMax },
238 	{ "sendenv", oSendEnv },
239 	{ "controlpath", oControlPath },
240 	{ "controlmaster", oControlMaster },
241 	{ "controlpersist", oControlPersist },
242 	{ "hashknownhosts", oHashKnownHosts },
243 	{ "tunnel", oTunnel },
244 	{ "tunneldevice", oTunnelDevice },
245 	{ "localcommand", oLocalCommand },
246 	{ "permitlocalcommand", oPermitLocalCommand },
247 	{ "visualhostkey", oVisualHostKey },
248 	{ "useroaming", oUseRoaming },
249 #ifdef JPAKE
250 	{ "zeroknowledgepasswordauthentication",
251 	    oZeroKnowledgePasswordAuthentication },
252 #else
253 	{ "zeroknowledgepasswordauthentication", oUnsupported },
254 #endif
255 	{ "kexalgorithms", oKexAlgorithms },
256 	{ "ipqos", oIPQoS },
257 	{ "requesttty", oRequestTTY },
258 	{ "hpndisabled", oHPNDisabled },
259 	{ "hpnbuffersize", oHPNBufferSize },
260 	{ "tcprcvbufpoll", oTcpRcvBufPoll },
261 	{ "tcprcvbuf", oTcpRcvBuf },
262 #ifdef	NONE_CIPHER_ENABLED
263 	{ "noneenabled", oNoneEnabled },
264 	{ "noneswitch", oNoneSwitch },
265 #endif
266 	{ "versionaddendum", oVersionAddendum },
267 
268 	{ NULL, oBadOption }
269 };
270 
271 /*
272  * Adds a local TCP/IP port forward to options.  Never returns if there is an
273  * error.
274  */
275 
276 void
277 add_local_forward(Options *options, const Forward *newfwd)
278 {
279 	Forward *fwd;
280 #ifndef NO_IPPORT_RESERVED_CONCEPT
281 	extern uid_t original_real_uid;
282 	int ipport_reserved;
283 #ifdef __FreeBSD__
284 	size_t len_ipport_reserved = sizeof(ipport_reserved);
285 
286 	if (sysctlbyname("net.inet.ip.portrange.reservedhigh",
287 	    &ipport_reserved, &len_ipport_reserved, NULL, 0) != 0)
288 		ipport_reserved = IPPORT_RESERVED;
289 	else
290 		ipport_reserved++;
291 #else
292 	ipport_reserved = IPPORT_RESERVED;
293 #endif
294 	if (newfwd->listen_port < ipport_reserved && original_real_uid != 0)
295 		fatal("Privileged ports can only be forwarded by root.");
296 #endif
297 	options->local_forwards = xrealloc(options->local_forwards,
298 	    options->num_local_forwards + 1,
299 	    sizeof(*options->local_forwards));
300 	fwd = &options->local_forwards[options->num_local_forwards++];
301 
302 	fwd->listen_host = newfwd->listen_host;
303 	fwd->listen_port = newfwd->listen_port;
304 	fwd->connect_host = newfwd->connect_host;
305 	fwd->connect_port = newfwd->connect_port;
306 }
307 
308 /*
309  * Adds a remote TCP/IP port forward to options.  Never returns if there is
310  * an error.
311  */
312 
313 void
314 add_remote_forward(Options *options, const Forward *newfwd)
315 {
316 	Forward *fwd;
317 
318 	options->remote_forwards = xrealloc(options->remote_forwards,
319 	    options->num_remote_forwards + 1,
320 	    sizeof(*options->remote_forwards));
321 	fwd = &options->remote_forwards[options->num_remote_forwards++];
322 
323 	fwd->listen_host = newfwd->listen_host;
324 	fwd->listen_port = newfwd->listen_port;
325 	fwd->connect_host = newfwd->connect_host;
326 	fwd->connect_port = newfwd->connect_port;
327 	fwd->allocated_port = 0;
328 }
329 
330 static void
331 clear_forwardings(Options *options)
332 {
333 	int i;
334 
335 	for (i = 0; i < options->num_local_forwards; i++) {
336 		if (options->local_forwards[i].listen_host != NULL)
337 			xfree(options->local_forwards[i].listen_host);
338 		xfree(options->local_forwards[i].connect_host);
339 	}
340 	if (options->num_local_forwards > 0) {
341 		xfree(options->local_forwards);
342 		options->local_forwards = NULL;
343 	}
344 	options->num_local_forwards = 0;
345 	for (i = 0; i < options->num_remote_forwards; i++) {
346 		if (options->remote_forwards[i].listen_host != NULL)
347 			xfree(options->remote_forwards[i].listen_host);
348 		xfree(options->remote_forwards[i].connect_host);
349 	}
350 	if (options->num_remote_forwards > 0) {
351 		xfree(options->remote_forwards);
352 		options->remote_forwards = NULL;
353 	}
354 	options->num_remote_forwards = 0;
355 	options->tun_open = SSH_TUNMODE_NO;
356 }
357 
358 /*
359  * Returns the number of the token pointed to by cp or oBadOption.
360  */
361 
362 static OpCodes
363 parse_token(const char *cp, const char *filename, int linenum)
364 {
365 	u_int i;
366 
367 	for (i = 0; keywords[i].name; i++)
368 		if (strcasecmp(cp, keywords[i].name) == 0)
369 			return keywords[i].opcode;
370 
371 	error("%s: line %d: Bad configuration option: %s",
372 	    filename, linenum, cp);
373 	return oBadOption;
374 }
375 
376 /*
377  * Processes a single option line as used in the configuration files. This
378  * only sets those values that have not already been set.
379  */
380 #define WHITESPACE " \t\r\n"
381 
382 int
383 process_config_line(Options *options, const char *host,
384 		    char *line, const char *filename, int linenum,
385 		    int *activep)
386 {
387 	char *s, **charptr, *endofnumber, *keyword, *arg, *arg2;
388 	char **cpptr, fwdarg[256];
389 	u_int *uintptr, max_entries = 0;
390 	int negated, opcode, *intptr, value, value2, scale;
391 	LogLevel *log_level_ptr;
392 	long long orig, val64;
393 	size_t len;
394 	Forward fwd;
395 
396 	/* Strip trailing whitespace */
397 	for (len = strlen(line) - 1; len > 0; len--) {
398 		if (strchr(WHITESPACE, line[len]) == NULL)
399 			break;
400 		line[len] = '\0';
401 	}
402 
403 	s = line;
404 	/* Get the keyword. (Each line is supposed to begin with a keyword). */
405 	if ((keyword = strdelim(&s)) == NULL)
406 		return 0;
407 	/* Ignore leading whitespace. */
408 	if (*keyword == '\0')
409 		keyword = strdelim(&s);
410 	if (keyword == NULL || !*keyword || *keyword == '\n' || *keyword == '#')
411 		return 0;
412 
413 	opcode = parse_token(keyword, filename, linenum);
414 
415 	switch (opcode) {
416 	case oBadOption:
417 		/* don't panic, but count bad options */
418 		return -1;
419 		/* NOTREACHED */
420 	case oConnectTimeout:
421 		intptr = &options->connection_timeout;
422 parse_time:
423 		arg = strdelim(&s);
424 		if (!arg || *arg == '\0')
425 			fatal("%s line %d: missing time value.",
426 			    filename, linenum);
427 		if ((value = convtime(arg)) == -1)
428 			fatal("%s line %d: invalid time value.",
429 			    filename, linenum);
430 		if (*activep && *intptr == -1)
431 			*intptr = value;
432 		break;
433 
434 	case oForwardAgent:
435 		intptr = &options->forward_agent;
436 parse_flag:
437 		arg = strdelim(&s);
438 		if (!arg || *arg == '\0')
439 			fatal("%.200s line %d: Missing yes/no argument.", filename, linenum);
440 		value = 0;	/* To avoid compiler warning... */
441 		if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0)
442 			value = 1;
443 		else if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0)
444 			value = 0;
445 		else
446 			fatal("%.200s line %d: Bad yes/no argument.", filename, linenum);
447 		if (*activep && *intptr == -1)
448 			*intptr = value;
449 		break;
450 
451 	case oForwardX11:
452 		intptr = &options->forward_x11;
453 		goto parse_flag;
454 
455 	case oForwardX11Trusted:
456 		intptr = &options->forward_x11_trusted;
457 		goto parse_flag;
458 
459 	case oForwardX11Timeout:
460 		intptr = &options->forward_x11_timeout;
461 		goto parse_time;
462 
463 	case oGatewayPorts:
464 		intptr = &options->gateway_ports;
465 		goto parse_flag;
466 
467 	case oExitOnForwardFailure:
468 		intptr = &options->exit_on_forward_failure;
469 		goto parse_flag;
470 
471 	case oUsePrivilegedPort:
472 		intptr = &options->use_privileged_port;
473 		goto parse_flag;
474 
475 	case oPasswordAuthentication:
476 		intptr = &options->password_authentication;
477 		goto parse_flag;
478 
479 	case oZeroKnowledgePasswordAuthentication:
480 		intptr = &options->zero_knowledge_password_authentication;
481 		goto parse_flag;
482 
483 	case oKbdInteractiveAuthentication:
484 		intptr = &options->kbd_interactive_authentication;
485 		goto parse_flag;
486 
487 	case oKbdInteractiveDevices:
488 		charptr = &options->kbd_interactive_devices;
489 		goto parse_string;
490 
491 	case oPubkeyAuthentication:
492 		intptr = &options->pubkey_authentication;
493 		goto parse_flag;
494 
495 	case oRSAAuthentication:
496 		intptr = &options->rsa_authentication;
497 		goto parse_flag;
498 
499 	case oRhostsRSAAuthentication:
500 		intptr = &options->rhosts_rsa_authentication;
501 		goto parse_flag;
502 
503 	case oHostbasedAuthentication:
504 		intptr = &options->hostbased_authentication;
505 		goto parse_flag;
506 
507 	case oChallengeResponseAuthentication:
508 		intptr = &options->challenge_response_authentication;
509 		goto parse_flag;
510 
511 	case oGssAuthentication:
512 		intptr = &options->gss_authentication;
513 		goto parse_flag;
514 
515 	case oGssDelegateCreds:
516 		intptr = &options->gss_deleg_creds;
517 		goto parse_flag;
518 
519 	case oBatchMode:
520 		intptr = &options->batch_mode;
521 		goto parse_flag;
522 
523 	case oCheckHostIP:
524 		intptr = &options->check_host_ip;
525 		goto parse_flag;
526 
527 	case oVerifyHostKeyDNS:
528 		intptr = &options->verify_host_key_dns;
529 		goto parse_yesnoask;
530 
531 	case oStrictHostKeyChecking:
532 		intptr = &options->strict_host_key_checking;
533 parse_yesnoask:
534 		arg = strdelim(&s);
535 		if (!arg || *arg == '\0')
536 			fatal("%.200s line %d: Missing yes/no/ask argument.",
537 			    filename, linenum);
538 		value = 0;	/* To avoid compiler warning... */
539 		if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0)
540 			value = 1;
541 		else if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0)
542 			value = 0;
543 		else if (strcmp(arg, "ask") == 0)
544 			value = 2;
545 		else
546 			fatal("%.200s line %d: Bad yes/no/ask argument.", filename, linenum);
547 		if (*activep && *intptr == -1)
548 			*intptr = value;
549 		break;
550 
551 	case oCompression:
552 		intptr = &options->compression;
553 		goto parse_flag;
554 
555 	case oTCPKeepAlive:
556 		intptr = &options->tcp_keep_alive;
557 		goto parse_flag;
558 
559 	case oNoHostAuthenticationForLocalhost:
560 		intptr = &options->no_host_authentication_for_localhost;
561 		goto parse_flag;
562 
563 	case oNumberOfPasswordPrompts:
564 		intptr = &options->number_of_password_prompts;
565 		goto parse_int;
566 
567 	case oCompressionLevel:
568 		intptr = &options->compression_level;
569 		goto parse_int;
570 
571 	case oRekeyLimit:
572 		arg = strdelim(&s);
573 		if (!arg || *arg == '\0')
574 			fatal("%.200s line %d: Missing argument.", filename, linenum);
575 		if (arg[0] < '0' || arg[0] > '9')
576 			fatal("%.200s line %d: Bad number.", filename, linenum);
577 		orig = val64 = strtoll(arg, &endofnumber, 10);
578 		if (arg == endofnumber)
579 			fatal("%.200s line %d: Bad number.", filename, linenum);
580 		switch (toupper(*endofnumber)) {
581 		case '\0':
582 			scale = 1;
583 			break;
584 		case 'K':
585 			scale = 1<<10;
586 			break;
587 		case 'M':
588 			scale = 1<<20;
589 			break;
590 		case 'G':
591 			scale = 1<<30;
592 			break;
593 		default:
594 			fatal("%.200s line %d: Invalid RekeyLimit suffix",
595 			    filename, linenum);
596 		}
597 		val64 *= scale;
598 		/* detect integer wrap and too-large limits */
599 		if ((val64 / scale) != orig || val64 > UINT_MAX)
600 			fatal("%.200s line %d: RekeyLimit too large",
601 			    filename, linenum);
602 		if (val64 < 16)
603 			fatal("%.200s line %d: RekeyLimit too small",
604 			    filename, linenum);
605 		if (*activep && options->rekey_limit == -1)
606 			options->rekey_limit = (u_int32_t)val64;
607 		break;
608 
609 	case oIdentityFile:
610 		arg = strdelim(&s);
611 		if (!arg || *arg == '\0')
612 			fatal("%.200s line %d: Missing argument.", filename, linenum);
613 		if (*activep) {
614 			intptr = &options->num_identity_files;
615 			if (*intptr >= SSH_MAX_IDENTITY_FILES)
616 				fatal("%.200s line %d: Too many identity files specified (max %d).",
617 				    filename, linenum, SSH_MAX_IDENTITY_FILES);
618 			charptr = &options->identity_files[*intptr];
619 			*charptr = xstrdup(arg);
620 			*intptr = *intptr + 1;
621 		}
622 		break;
623 
624 	case oXAuthLocation:
625 		charptr=&options->xauth_location;
626 		goto parse_string;
627 
628 	case oUser:
629 		charptr = &options->user;
630 parse_string:
631 		arg = strdelim(&s);
632 		if (!arg || *arg == '\0')
633 			fatal("%.200s line %d: Missing argument.",
634 			    filename, linenum);
635 		if (*activep && *charptr == NULL)
636 			*charptr = xstrdup(arg);
637 		break;
638 
639 	case oGlobalKnownHostsFile:
640 		cpptr = (char **)&options->system_hostfiles;
641 		uintptr = &options->num_system_hostfiles;
642 		max_entries = SSH_MAX_HOSTS_FILES;
643 parse_char_array:
644 		if (*activep && *uintptr == 0) {
645 			while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
646 				if ((*uintptr) >= max_entries)
647 					fatal("%s line %d: "
648 					    "too many authorized keys files.",
649 					    filename, linenum);
650 				cpptr[(*uintptr)++] = xstrdup(arg);
651 			}
652 		}
653 		return 0;
654 
655 	case oUserKnownHostsFile:
656 		cpptr = (char **)&options->user_hostfiles;
657 		uintptr = &options->num_user_hostfiles;
658 		max_entries = SSH_MAX_HOSTS_FILES;
659 		goto parse_char_array;
660 
661 	case oHostName:
662 		charptr = &options->hostname;
663 		goto parse_string;
664 
665 	case oHostKeyAlias:
666 		charptr = &options->host_key_alias;
667 		goto parse_string;
668 
669 	case oPreferredAuthentications:
670 		charptr = &options->preferred_authentications;
671 		goto parse_string;
672 
673 	case oBindAddress:
674 		charptr = &options->bind_address;
675 		goto parse_string;
676 
677 	case oPKCS11Provider:
678 		charptr = &options->pkcs11_provider;
679 		goto parse_string;
680 
681 	case oProxyCommand:
682 		charptr = &options->proxy_command;
683 parse_command:
684 		if (s == NULL)
685 			fatal("%.200s line %d: Missing argument.", filename, linenum);
686 		len = strspn(s, WHITESPACE "=");
687 		if (*activep && *charptr == NULL)
688 			*charptr = xstrdup(s + len);
689 		return 0;
690 
691 	case oPort:
692 		intptr = &options->port;
693 parse_int:
694 		arg = strdelim(&s);
695 		if (!arg || *arg == '\0')
696 			fatal("%.200s line %d: Missing argument.", filename, linenum);
697 		if (arg[0] < '0' || arg[0] > '9')
698 			fatal("%.200s line %d: Bad number.", filename, linenum);
699 
700 		/* Octal, decimal, or hex format? */
701 		value = strtol(arg, &endofnumber, 0);
702 		if (arg == endofnumber)
703 			fatal("%.200s line %d: Bad number.", filename, linenum);
704 		if (*activep && *intptr == -1)
705 			*intptr = value;
706 		break;
707 
708 	case oConnectionAttempts:
709 		intptr = &options->connection_attempts;
710 		goto parse_int;
711 
712 	case oCipher:
713 		intptr = &options->cipher;
714 		arg = strdelim(&s);
715 		if (!arg || *arg == '\0')
716 			fatal("%.200s line %d: Missing argument.", filename, linenum);
717 		value = cipher_number(arg);
718 		if (value == -1)
719 			fatal("%.200s line %d: Bad cipher '%s'.",
720 			    filename, linenum, arg ? arg : "<NONE>");
721 		if (*activep && *intptr == -1)
722 			*intptr = value;
723 		break;
724 
725 	case oCiphers:
726 		arg = strdelim(&s);
727 		if (!arg || *arg == '\0')
728 			fatal("%.200s line %d: Missing argument.", filename, linenum);
729 		if (!ciphers_valid(arg))
730 			fatal("%.200s line %d: Bad SSH2 cipher spec '%s'.",
731 			    filename, linenum, arg ? arg : "<NONE>");
732 		if (*activep && options->ciphers == NULL)
733 			options->ciphers = xstrdup(arg);
734 		break;
735 
736 	case oMacs:
737 		arg = strdelim(&s);
738 		if (!arg || *arg == '\0')
739 			fatal("%.200s line %d: Missing argument.", filename, linenum);
740 		if (!mac_valid(arg))
741 			fatal("%.200s line %d: Bad SSH2 Mac spec '%s'.",
742 			    filename, linenum, arg ? arg : "<NONE>");
743 		if (*activep && options->macs == NULL)
744 			options->macs = xstrdup(arg);
745 		break;
746 
747 	case oKexAlgorithms:
748 		arg = strdelim(&s);
749 		if (!arg || *arg == '\0')
750 			fatal("%.200s line %d: Missing argument.",
751 			    filename, linenum);
752 		if (!kex_names_valid(arg))
753 			fatal("%.200s line %d: Bad SSH2 KexAlgorithms '%s'.",
754 			    filename, linenum, arg ? arg : "<NONE>");
755 		if (*activep && options->kex_algorithms == NULL)
756 			options->kex_algorithms = xstrdup(arg);
757 		break;
758 
759 	case oHostKeyAlgorithms:
760 		arg = strdelim(&s);
761 		if (!arg || *arg == '\0')
762 			fatal("%.200s line %d: Missing argument.", filename, linenum);
763 		if (!key_names_valid2(arg))
764 			fatal("%.200s line %d: Bad protocol 2 host key algorithms '%s'.",
765 			    filename, linenum, arg ? arg : "<NONE>");
766 		if (*activep && options->hostkeyalgorithms == NULL)
767 			options->hostkeyalgorithms = xstrdup(arg);
768 		break;
769 
770 	case oProtocol:
771 		intptr = &options->protocol;
772 		arg = strdelim(&s);
773 		if (!arg || *arg == '\0')
774 			fatal("%.200s line %d: Missing argument.", filename, linenum);
775 		value = proto_spec(arg);
776 		if (value == SSH_PROTO_UNKNOWN)
777 			fatal("%.200s line %d: Bad protocol spec '%s'.",
778 			    filename, linenum, arg ? arg : "<NONE>");
779 		if (*activep && *intptr == SSH_PROTO_UNKNOWN)
780 			*intptr = value;
781 		break;
782 
783 	case oLogLevel:
784 		log_level_ptr = &options->log_level;
785 		arg = strdelim(&s);
786 		value = log_level_number(arg);
787 		if (value == SYSLOG_LEVEL_NOT_SET)
788 			fatal("%.200s line %d: unsupported log level '%s'",
789 			    filename, linenum, arg ? arg : "<NONE>");
790 		if (*activep && *log_level_ptr == SYSLOG_LEVEL_NOT_SET)
791 			*log_level_ptr = (LogLevel) value;
792 		break;
793 
794 	case oLocalForward:
795 	case oRemoteForward:
796 	case oDynamicForward:
797 		arg = strdelim(&s);
798 		if (arg == NULL || *arg == '\0')
799 			fatal("%.200s line %d: Missing port argument.",
800 			    filename, linenum);
801 
802 		if (opcode == oLocalForward ||
803 		    opcode == oRemoteForward) {
804 			arg2 = strdelim(&s);
805 			if (arg2 == NULL || *arg2 == '\0')
806 				fatal("%.200s line %d: Missing target argument.",
807 				    filename, linenum);
808 
809 			/* construct a string for parse_forward */
810 			snprintf(fwdarg, sizeof(fwdarg), "%s:%s", arg, arg2);
811 		} else if (opcode == oDynamicForward) {
812 			strlcpy(fwdarg, arg, sizeof(fwdarg));
813 		}
814 
815 		if (parse_forward(&fwd, fwdarg,
816 		    opcode == oDynamicForward ? 1 : 0,
817 		    opcode == oRemoteForward ? 1 : 0) == 0)
818 			fatal("%.200s line %d: Bad forwarding specification.",
819 			    filename, linenum);
820 
821 		if (*activep) {
822 			if (opcode == oLocalForward ||
823 			    opcode == oDynamicForward)
824 				add_local_forward(options, &fwd);
825 			else if (opcode == oRemoteForward)
826 				add_remote_forward(options, &fwd);
827 		}
828 		break;
829 
830 	case oClearAllForwardings:
831 		intptr = &options->clear_forwardings;
832 		goto parse_flag;
833 
834 	case oHost:
835 		*activep = 0;
836 		arg2 = NULL;
837 		while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
838 			negated = *arg == '!';
839 			if (negated)
840 				arg++;
841 			if (match_pattern(host, arg)) {
842 				if (negated) {
843 					debug("%.200s line %d: Skipping Host "
844 					    "block because of negated match "
845 					    "for %.100s", filename, linenum,
846 					    arg);
847 					*activep = 0;
848 					break;
849 				}
850 				if (!*activep)
851 					arg2 = arg; /* logged below */
852 				*activep = 1;
853 			}
854 		}
855 		if (*activep)
856 			debug("%.200s line %d: Applying options for %.100s",
857 			    filename, linenum, arg2);
858 		/* Avoid garbage check below, as strdelim is done. */
859 		return 0;
860 
861 	case oEscapeChar:
862 		intptr = &options->escape_char;
863 		arg = strdelim(&s);
864 		if (!arg || *arg == '\0')
865 			fatal("%.200s line %d: Missing argument.", filename, linenum);
866 		if (arg[0] == '^' && arg[2] == 0 &&
867 		    (u_char) arg[1] >= 64 && (u_char) arg[1] < 128)
868 			value = (u_char) arg[1] & 31;
869 		else if (strlen(arg) == 1)
870 			value = (u_char) arg[0];
871 		else if (strcmp(arg, "none") == 0)
872 			value = SSH_ESCAPECHAR_NONE;
873 		else {
874 			fatal("%.200s line %d: Bad escape character.",
875 			    filename, linenum);
876 			/* NOTREACHED */
877 			value = 0;	/* Avoid compiler warning. */
878 		}
879 		if (*activep && *intptr == -1)
880 			*intptr = value;
881 		break;
882 
883 	case oAddressFamily:
884 		arg = strdelim(&s);
885 		if (!arg || *arg == '\0')
886 			fatal("%s line %d: missing address family.",
887 			    filename, linenum);
888 		intptr = &options->address_family;
889 		if (strcasecmp(arg, "inet") == 0)
890 			value = AF_INET;
891 		else if (strcasecmp(arg, "inet6") == 0)
892 			value = AF_INET6;
893 		else if (strcasecmp(arg, "any") == 0)
894 			value = AF_UNSPEC;
895 		else
896 			fatal("Unsupported AddressFamily \"%s\"", arg);
897 		if (*activep && *intptr == -1)
898 			*intptr = value;
899 		break;
900 
901 	case oEnableSSHKeysign:
902 		intptr = &options->enable_ssh_keysign;
903 		goto parse_flag;
904 
905 	case oIdentitiesOnly:
906 		intptr = &options->identities_only;
907 		goto parse_flag;
908 
909 	case oServerAliveInterval:
910 		intptr = &options->server_alive_interval;
911 		goto parse_time;
912 
913 	case oServerAliveCountMax:
914 		intptr = &options->server_alive_count_max;
915 		goto parse_int;
916 
917 	case oSendEnv:
918 		while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
919 			if (strchr(arg, '=') != NULL)
920 				fatal("%s line %d: Invalid environment name.",
921 				    filename, linenum);
922 			if (!*activep)
923 				continue;
924 			if (options->num_send_env >= MAX_SEND_ENV)
925 				fatal("%s line %d: too many send env.",
926 				    filename, linenum);
927 			options->send_env[options->num_send_env++] =
928 			    xstrdup(arg);
929 		}
930 		break;
931 
932 	case oControlPath:
933 		charptr = &options->control_path;
934 		goto parse_string;
935 
936 	case oControlMaster:
937 		intptr = &options->control_master;
938 		arg = strdelim(&s);
939 		if (!arg || *arg == '\0')
940 			fatal("%.200s line %d: Missing ControlMaster argument.",
941 			    filename, linenum);
942 		value = 0;	/* To avoid compiler warning... */
943 		if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0)
944 			value = SSHCTL_MASTER_YES;
945 		else if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0)
946 			value = SSHCTL_MASTER_NO;
947 		else if (strcmp(arg, "auto") == 0)
948 			value = SSHCTL_MASTER_AUTO;
949 		else if (strcmp(arg, "ask") == 0)
950 			value = SSHCTL_MASTER_ASK;
951 		else if (strcmp(arg, "autoask") == 0)
952 			value = SSHCTL_MASTER_AUTO_ASK;
953 		else
954 			fatal("%.200s line %d: Bad ControlMaster argument.",
955 			    filename, linenum);
956 		if (*activep && *intptr == -1)
957 			*intptr = value;
958 		break;
959 
960 	case oControlPersist:
961 		/* no/false/yes/true, or a time spec */
962 		intptr = &options->control_persist;
963 		arg = strdelim(&s);
964 		if (!arg || *arg == '\0')
965 			fatal("%.200s line %d: Missing ControlPersist"
966 			    " argument.", filename, linenum);
967 		value = 0;
968 		value2 = 0;	/* timeout */
969 		if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0)
970 			value = 0;
971 		else if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0)
972 			value = 1;
973 		else if ((value2 = convtime(arg)) >= 0)
974 			value = 1;
975 		else
976 			fatal("%.200s line %d: Bad ControlPersist argument.",
977 			    filename, linenum);
978 		if (*activep && *intptr == -1) {
979 			*intptr = value;
980 			options->control_persist_timeout = value2;
981 		}
982 		break;
983 
984 	case oHashKnownHosts:
985 		intptr = &options->hash_known_hosts;
986 		goto parse_flag;
987 
988 	case oTunnel:
989 		intptr = &options->tun_open;
990 		arg = strdelim(&s);
991 		if (!arg || *arg == '\0')
992 			fatal("%s line %d: Missing yes/point-to-point/"
993 			    "ethernet/no argument.", filename, linenum);
994 		value = 0;	/* silence compiler */
995 		if (strcasecmp(arg, "ethernet") == 0)
996 			value = SSH_TUNMODE_ETHERNET;
997 		else if (strcasecmp(arg, "point-to-point") == 0)
998 			value = SSH_TUNMODE_POINTOPOINT;
999 		else if (strcasecmp(arg, "yes") == 0)
1000 			value = SSH_TUNMODE_DEFAULT;
1001 		else if (strcasecmp(arg, "no") == 0)
1002 			value = SSH_TUNMODE_NO;
1003 		else
1004 			fatal("%s line %d: Bad yes/point-to-point/ethernet/"
1005 			    "no argument: %s", filename, linenum, arg);
1006 		if (*activep)
1007 			*intptr = value;
1008 		break;
1009 
1010 	case oTunnelDevice:
1011 		arg = strdelim(&s);
1012 		if (!arg || *arg == '\0')
1013 			fatal("%.200s line %d: Missing argument.", filename, linenum);
1014 		value = a2tun(arg, &value2);
1015 		if (value == SSH_TUNID_ERR)
1016 			fatal("%.200s line %d: Bad tun device.", filename, linenum);
1017 		if (*activep) {
1018 			options->tun_local = value;
1019 			options->tun_remote = value2;
1020 		}
1021 		break;
1022 
1023 	case oLocalCommand:
1024 		charptr = &options->local_command;
1025 		goto parse_command;
1026 
1027 	case oPermitLocalCommand:
1028 		intptr = &options->permit_local_command;
1029 		goto parse_flag;
1030 
1031 	case oVisualHostKey:
1032 		intptr = &options->visual_host_key;
1033 		goto parse_flag;
1034 
1035 	case oIPQoS:
1036 		arg = strdelim(&s);
1037 		if ((value = parse_ipqos(arg)) == -1)
1038 			fatal("%s line %d: Bad IPQoS value: %s",
1039 			    filename, linenum, arg);
1040 		arg = strdelim(&s);
1041 		if (arg == NULL)
1042 			value2 = value;
1043 		else if ((value2 = parse_ipqos(arg)) == -1)
1044 			fatal("%s line %d: Bad IPQoS value: %s",
1045 			    filename, linenum, arg);
1046 		if (*activep) {
1047 			options->ip_qos_interactive = value;
1048 			options->ip_qos_bulk = value2;
1049 		}
1050 		break;
1051 
1052 	case oUseRoaming:
1053 		intptr = &options->use_roaming;
1054 		goto parse_flag;
1055 
1056 	case oRequestTTY:
1057 		arg = strdelim(&s);
1058 		if (!arg || *arg == '\0')
1059 			fatal("%s line %d: missing argument.",
1060 			    filename, linenum);
1061 		intptr = &options->request_tty;
1062 		if (strcasecmp(arg, "yes") == 0)
1063 			value = REQUEST_TTY_YES;
1064 		else if (strcasecmp(arg, "no") == 0)
1065 			value = REQUEST_TTY_NO;
1066 		else if (strcasecmp(arg, "force") == 0)
1067 			value = REQUEST_TTY_FORCE;
1068 		else if (strcasecmp(arg, "auto") == 0)
1069 			value = REQUEST_TTY_AUTO;
1070 		else
1071 			fatal("Unsupported RequestTTY \"%s\"", arg);
1072 		if (*activep && *intptr == -1)
1073 			*intptr = value;
1074 		break;
1075 
1076 	case oHPNDisabled:
1077 		intptr = &options->hpn_disabled;
1078 		goto parse_flag;
1079 
1080 	case oHPNBufferSize:
1081 		intptr = &options->hpn_buffer_size;
1082 		goto parse_int;
1083 
1084 	case oTcpRcvBufPoll:
1085 		intptr = &options->tcp_rcv_buf_poll;
1086 		goto parse_flag;
1087 
1088 	case oTcpRcvBuf:
1089 		intptr = &options->tcp_rcv_buf;
1090 		goto parse_int;
1091 
1092 #ifdef	NONE_CIPHER_ENABLED
1093 	case oNoneEnabled:
1094 		intptr = &options->none_enabled;
1095 		goto parse_flag;
1096 
1097 	/*
1098 	 * We check to see if the command comes from the command line or not.
1099 	 * If it does then enable it otherwise fail.  NONE must never be a
1100 	 * default configuration.
1101 	 */
1102 	case oNoneSwitch:
1103 		if (strcmp(filename,"command-line") == 0) {
1104 			intptr = &options->none_switch;
1105 			goto parse_flag;
1106 		} else {
1107 			debug("NoneSwitch directive found in %.200s.",
1108 			    filename);
1109 			error("NoneSwitch is found in %.200s.\n"
1110 			    "You may only use this configuration option "
1111 			    "from the command line", filename);
1112 			error("Continuing...");
1113 			return 0;
1114 		}
1115 #endif
1116 
1117 	case oVersionAddendum:
1118 		ssh_version_set_addendum(strtok(s, "\n"));
1119 		do {
1120 			arg = strdelim(&s);
1121 		} while (arg != NULL && *arg != '\0');
1122 		break;
1123 
1124 	case oDeprecated:
1125 		debug("%s line %d: Deprecated option \"%s\"",
1126 		    filename, linenum, keyword);
1127 		return 0;
1128 
1129 	case oUnsupported:
1130 		error("%s line %d: Unsupported option \"%s\"",
1131 		    filename, linenum, keyword);
1132 		return 0;
1133 
1134 	default:
1135 		fatal("process_config_line: Unimplemented opcode %d", opcode);
1136 	}
1137 
1138 	/* Check that there is no garbage at end of line. */
1139 	if ((arg = strdelim(&s)) != NULL && *arg != '\0') {
1140 		fatal("%.200s line %d: garbage at end of line; \"%.200s\".",
1141 		    filename, linenum, arg);
1142 	}
1143 	return 0;
1144 }
1145 
1146 
1147 /*
1148  * Reads the config file and modifies the options accordingly.  Options
1149  * should already be initialized before this call.  This never returns if
1150  * there is an error.  If the file does not exist, this returns 0.
1151  */
1152 
1153 int
1154 read_config_file(const char *filename, const char *host, Options *options,
1155     int checkperm)
1156 {
1157 	FILE *f;
1158 	char line[1024];
1159 	int active, linenum;
1160 	int bad_options = 0;
1161 
1162 	if ((f = fopen(filename, "r")) == NULL)
1163 		return 0;
1164 
1165 	if (checkperm) {
1166 		struct stat sb;
1167 
1168 		if (fstat(fileno(f), &sb) == -1)
1169 			fatal("fstat %s: %s", filename, strerror(errno));
1170 		if (((sb.st_uid != 0 && sb.st_uid != getuid()) ||
1171 		    (sb.st_mode & 022) != 0))
1172 			fatal("Bad owner or permissions on %s", filename);
1173 	}
1174 
1175 	debug("Reading configuration data %.200s", filename);
1176 
1177 	/*
1178 	 * Mark that we are now processing the options.  This flag is turned
1179 	 * on/off by Host specifications.
1180 	 */
1181 	active = 1;
1182 	linenum = 0;
1183 	while (fgets(line, sizeof(line), f)) {
1184 		/* Update line number counter. */
1185 		linenum++;
1186 		if (process_config_line(options, host, line, filename, linenum, &active) != 0)
1187 			bad_options++;
1188 	}
1189 	fclose(f);
1190 	if (bad_options > 0)
1191 		fatal("%s: terminating, %d bad configuration options",
1192 		    filename, bad_options);
1193 	return 1;
1194 }
1195 
1196 /*
1197  * Initializes options to special values that indicate that they have not yet
1198  * been set.  Read_config_file will only set options with this value. Options
1199  * are processed in the following order: command line, user config file,
1200  * system config file.  Last, fill_default_options is called.
1201  */
1202 
1203 void
1204 initialize_options(Options * options)
1205 {
1206 	memset(options, 'X', sizeof(*options));
1207 	options->forward_agent = -1;
1208 	options->forward_x11 = -1;
1209 	options->forward_x11_trusted = -1;
1210 	options->forward_x11_timeout = -1;
1211 	options->exit_on_forward_failure = -1;
1212 	options->xauth_location = NULL;
1213 	options->gateway_ports = -1;
1214 	options->use_privileged_port = -1;
1215 	options->rsa_authentication = -1;
1216 	options->pubkey_authentication = -1;
1217 	options->challenge_response_authentication = -1;
1218 	options->gss_authentication = -1;
1219 	options->gss_deleg_creds = -1;
1220 	options->password_authentication = -1;
1221 	options->kbd_interactive_authentication = -1;
1222 	options->kbd_interactive_devices = NULL;
1223 	options->rhosts_rsa_authentication = -1;
1224 	options->hostbased_authentication = -1;
1225 	options->batch_mode = -1;
1226 	options->check_host_ip = -1;
1227 	options->strict_host_key_checking = -1;
1228 	options->compression = -1;
1229 	options->tcp_keep_alive = -1;
1230 	options->compression_level = -1;
1231 	options->port = -1;
1232 	options->address_family = -1;
1233 	options->connection_attempts = -1;
1234 	options->connection_timeout = -1;
1235 	options->number_of_password_prompts = -1;
1236 	options->cipher = -1;
1237 	options->ciphers = NULL;
1238 	options->macs = NULL;
1239 	options->kex_algorithms = NULL;
1240 	options->hostkeyalgorithms = NULL;
1241 	options->protocol = SSH_PROTO_UNKNOWN;
1242 	options->num_identity_files = 0;
1243 	options->hostname = NULL;
1244 	options->host_key_alias = NULL;
1245 	options->proxy_command = NULL;
1246 	options->user = NULL;
1247 	options->escape_char = -1;
1248 	options->num_system_hostfiles = 0;
1249 	options->num_user_hostfiles = 0;
1250 	options->local_forwards = NULL;
1251 	options->num_local_forwards = 0;
1252 	options->remote_forwards = NULL;
1253 	options->num_remote_forwards = 0;
1254 	options->clear_forwardings = -1;
1255 	options->log_level = SYSLOG_LEVEL_NOT_SET;
1256 	options->preferred_authentications = NULL;
1257 	options->bind_address = NULL;
1258 	options->pkcs11_provider = NULL;
1259 	options->enable_ssh_keysign = - 1;
1260 	options->no_host_authentication_for_localhost = - 1;
1261 	options->identities_only = - 1;
1262 	options->rekey_limit = - 1;
1263 	options->verify_host_key_dns = -1;
1264 	options->server_alive_interval = -1;
1265 	options->server_alive_count_max = -1;
1266 	options->num_send_env = 0;
1267 	options->control_path = NULL;
1268 	options->control_master = -1;
1269 	options->control_persist = -1;
1270 	options->control_persist_timeout = 0;
1271 	options->hash_known_hosts = -1;
1272 	options->tun_open = -1;
1273 	options->tun_local = -1;
1274 	options->tun_remote = -1;
1275 	options->local_command = NULL;
1276 	options->permit_local_command = -1;
1277 	options->use_roaming = -1;
1278 	options->visual_host_key = -1;
1279 	options->zero_knowledge_password_authentication = -1;
1280 	options->ip_qos_interactive = -1;
1281 	options->ip_qos_bulk = -1;
1282 	options->request_tty = -1;
1283 	options->hpn_disabled = -1;
1284 	options->hpn_buffer_size = -1;
1285 	options->tcp_rcv_buf_poll = -1;
1286 	options->tcp_rcv_buf = -1;
1287 #ifdef NONE_CIPHER_ENABLED
1288 	options->none_enabled = -1;
1289 	options->none_switch = -1;
1290 #endif
1291 }
1292 
1293 /*
1294  * Called after processing other sources of option data, this fills those
1295  * options for which no value has been specified with their default values.
1296  */
1297 
1298 void
1299 fill_default_options(Options * options)
1300 {
1301 	int len;
1302 
1303 	if (options->forward_agent == -1)
1304 		options->forward_agent = 0;
1305 	if (options->forward_x11 == -1)
1306 		options->forward_x11 = 0;
1307 	if (options->forward_x11_trusted == -1)
1308 		options->forward_x11_trusted = 0;
1309 	if (options->forward_x11_timeout == -1)
1310 		options->forward_x11_timeout = 1200;
1311 	if (options->exit_on_forward_failure == -1)
1312 		options->exit_on_forward_failure = 0;
1313 	if (options->xauth_location == NULL)
1314 		options->xauth_location = _PATH_XAUTH;
1315 	if (options->gateway_ports == -1)
1316 		options->gateway_ports = 0;
1317 	if (options->use_privileged_port == -1)
1318 		options->use_privileged_port = 0;
1319 	if (options->rsa_authentication == -1)
1320 		options->rsa_authentication = 1;
1321 	if (options->pubkey_authentication == -1)
1322 		options->pubkey_authentication = 1;
1323 	if (options->challenge_response_authentication == -1)
1324 		options->challenge_response_authentication = 1;
1325 	if (options->gss_authentication == -1)
1326 		options->gss_authentication = 0;
1327 	if (options->gss_deleg_creds == -1)
1328 		options->gss_deleg_creds = 0;
1329 	if (options->password_authentication == -1)
1330 		options->password_authentication = 1;
1331 	if (options->kbd_interactive_authentication == -1)
1332 		options->kbd_interactive_authentication = 1;
1333 	if (options->rhosts_rsa_authentication == -1)
1334 		options->rhosts_rsa_authentication = 0;
1335 	if (options->hostbased_authentication == -1)
1336 		options->hostbased_authentication = 0;
1337 	if (options->batch_mode == -1)
1338 		options->batch_mode = 0;
1339 	if (options->check_host_ip == -1)
1340 		options->check_host_ip = 0;
1341 	if (options->strict_host_key_checking == -1)
1342 		options->strict_host_key_checking = 2;	/* 2 is default */
1343 	if (options->compression == -1)
1344 		options->compression = 0;
1345 	if (options->tcp_keep_alive == -1)
1346 		options->tcp_keep_alive = 1;
1347 	if (options->compression_level == -1)
1348 		options->compression_level = 6;
1349 	if (options->port == -1)
1350 		options->port = 0;	/* Filled in ssh_connect. */
1351 	if (options->address_family == -1)
1352 		options->address_family = AF_UNSPEC;
1353 	if (options->connection_attempts == -1)
1354 		options->connection_attempts = 1;
1355 	if (options->number_of_password_prompts == -1)
1356 		options->number_of_password_prompts = 3;
1357 	/* Selected in ssh_login(). */
1358 	if (options->cipher == -1)
1359 		options->cipher = SSH_CIPHER_NOT_SET;
1360 	/* options->ciphers, default set in myproposals.h */
1361 	/* options->macs, default set in myproposals.h */
1362 	/* options->kex_algorithms, default set in myproposals.h */
1363 	/* options->hostkeyalgorithms, default set in myproposals.h */
1364 	if (options->protocol == SSH_PROTO_UNKNOWN)
1365 		options->protocol = SSH_PROTO_2;
1366 	if (options->num_identity_files == 0) {
1367 		if (options->protocol & SSH_PROTO_1) {
1368 			len = 2 + strlen(_PATH_SSH_CLIENT_IDENTITY) + 1;
1369 			options->identity_files[options->num_identity_files] =
1370 			    xmalloc(len);
1371 			snprintf(options->identity_files[options->num_identity_files++],
1372 			    len, "~/%.100s", _PATH_SSH_CLIENT_IDENTITY);
1373 		}
1374 		if (options->protocol & SSH_PROTO_2) {
1375 			len = 2 + strlen(_PATH_SSH_CLIENT_ID_RSA) + 1;
1376 			options->identity_files[options->num_identity_files] =
1377 			    xmalloc(len);
1378 			snprintf(options->identity_files[options->num_identity_files++],
1379 			    len, "~/%.100s", _PATH_SSH_CLIENT_ID_RSA);
1380 
1381 			len = 2 + strlen(_PATH_SSH_CLIENT_ID_DSA) + 1;
1382 			options->identity_files[options->num_identity_files] =
1383 			    xmalloc(len);
1384 			snprintf(options->identity_files[options->num_identity_files++],
1385 			    len, "~/%.100s", _PATH_SSH_CLIENT_ID_DSA);
1386 #ifdef OPENSSL_HAS_ECC
1387 			len = 2 + strlen(_PATH_SSH_CLIENT_ID_ECDSA) + 1;
1388 			options->identity_files[options->num_identity_files] =
1389 			    xmalloc(len);
1390 			snprintf(options->identity_files[options->num_identity_files++],
1391 			    len, "~/%.100s", _PATH_SSH_CLIENT_ID_ECDSA);
1392 #endif
1393 		}
1394 	}
1395 	if (options->escape_char == -1)
1396 		options->escape_char = '~';
1397 	if (options->num_system_hostfiles == 0) {
1398 		options->system_hostfiles[options->num_system_hostfiles++] =
1399 		    xstrdup(_PATH_SSH_SYSTEM_HOSTFILE);
1400 		options->system_hostfiles[options->num_system_hostfiles++] =
1401 		    xstrdup(_PATH_SSH_SYSTEM_HOSTFILE2);
1402 	}
1403 	if (options->num_user_hostfiles == 0) {
1404 		options->user_hostfiles[options->num_user_hostfiles++] =
1405 		    xstrdup(_PATH_SSH_USER_HOSTFILE);
1406 		options->user_hostfiles[options->num_user_hostfiles++] =
1407 		    xstrdup(_PATH_SSH_USER_HOSTFILE2);
1408 	}
1409 	if (options->log_level == SYSLOG_LEVEL_NOT_SET)
1410 		options->log_level = SYSLOG_LEVEL_INFO;
1411 	if (options->clear_forwardings == 1)
1412 		clear_forwardings(options);
1413 	if (options->no_host_authentication_for_localhost == - 1)
1414 		options->no_host_authentication_for_localhost = 0;
1415 	if (options->identities_only == -1)
1416 		options->identities_only = 0;
1417 	if (options->enable_ssh_keysign == -1)
1418 		options->enable_ssh_keysign = 0;
1419 	if (options->rekey_limit == -1)
1420 		options->rekey_limit = 0;
1421 	if (options->verify_host_key_dns == -1)
1422 		options->verify_host_key_dns = 0;
1423 	if (options->server_alive_interval == -1)
1424 		options->server_alive_interval = 0;
1425 	if (options->server_alive_count_max == -1)
1426 		options->server_alive_count_max = 3;
1427 	if (options->control_master == -1)
1428 		options->control_master = 0;
1429 	if (options->control_persist == -1) {
1430 		options->control_persist = 0;
1431 		options->control_persist_timeout = 0;
1432 	}
1433 	if (options->hash_known_hosts == -1)
1434 		options->hash_known_hosts = 0;
1435 	if (options->tun_open == -1)
1436 		options->tun_open = SSH_TUNMODE_NO;
1437 	if (options->tun_local == -1)
1438 		options->tun_local = SSH_TUNID_ANY;
1439 	if (options->tun_remote == -1)
1440 		options->tun_remote = SSH_TUNID_ANY;
1441 	if (options->permit_local_command == -1)
1442 		options->permit_local_command = 0;
1443 	if (options->use_roaming == -1)
1444 		options->use_roaming = 1;
1445 	if (options->visual_host_key == -1)
1446 		options->visual_host_key = 0;
1447 	if (options->zero_knowledge_password_authentication == -1)
1448 		options->zero_knowledge_password_authentication = 0;
1449 	if (options->ip_qos_interactive == -1)
1450 		options->ip_qos_interactive = IPTOS_LOWDELAY;
1451 	if (options->ip_qos_bulk == -1)
1452 		options->ip_qos_bulk = IPTOS_THROUGHPUT;
1453 	if (options->request_tty == -1)
1454 		options->request_tty = REQUEST_TTY_AUTO;
1455 	/* options->local_command should not be set by default */
1456 	/* options->proxy_command should not be set by default */
1457 	/* options->user will be set in the main program if appropriate */
1458 	/* options->hostname will be set in the main program if appropriate */
1459 	/* options->host_key_alias should not be set by default */
1460 	/* options->preferred_authentications will be set in ssh */
1461 	if (options->hpn_disabled == -1)
1462 		options->hpn_disabled = 0;
1463 	if (options->hpn_buffer_size > -1)
1464 	{
1465 		u_int maxlen;
1466 
1467 		/* If a user tries to set the size to 0 set it to 1KB. */
1468 		if (options->hpn_buffer_size == 0)
1469 			options->hpn_buffer_size = 1024;
1470 		/* Limit the buffer to BUFFER_MAX_LEN. */
1471 		maxlen = buffer_get_max_len();
1472 		if (options->hpn_buffer_size > (maxlen / 1024)) {
1473 			debug("User requested buffer larger than %ub: %ub. "
1474 			    "Request reverted to %ub", maxlen,
1475 			    options->hpn_buffer_size * 1024, maxlen);
1476 			options->hpn_buffer_size = maxlen;
1477 		}
1478 		debug("hpn_buffer_size set to %d", options->hpn_buffer_size);
1479 	}
1480 	if (options->tcp_rcv_buf == 0)
1481 		options->tcp_rcv_buf = 1;
1482 	if (options->tcp_rcv_buf > -1)
1483 		options->tcp_rcv_buf *= 1024;
1484 	if (options->tcp_rcv_buf_poll == -1)
1485 		options->tcp_rcv_buf_poll = 1;
1486 #ifdef	NONE_CIPHER_ENABLED
1487 	/* options->none_enabled must not be set by default */
1488 	if (options->none_switch == -1)
1489 		options->none_switch = 0;
1490 #endif
1491 }
1492 
1493 /*
1494  * parse_forward
1495  * parses a string containing a port forwarding specification of the form:
1496  *   dynamicfwd == 0
1497  *	[listenhost:]listenport:connecthost:connectport
1498  *   dynamicfwd == 1
1499  *	[listenhost:]listenport
1500  * returns number of arguments parsed or zero on error
1501  */
1502 int
1503 parse_forward(Forward *fwd, const char *fwdspec, int dynamicfwd, int remotefwd)
1504 {
1505 	int i;
1506 	char *p, *cp, *fwdarg[4];
1507 
1508 	memset(fwd, '\0', sizeof(*fwd));
1509 
1510 	cp = p = xstrdup(fwdspec);
1511 
1512 	/* skip leading spaces */
1513 	while (isspace(*cp))
1514 		cp++;
1515 
1516 	for (i = 0; i < 4; ++i)
1517 		if ((fwdarg[i] = hpdelim(&cp)) == NULL)
1518 			break;
1519 
1520 	/* Check for trailing garbage */
1521 	if (cp != NULL)
1522 		i = 0;	/* failure */
1523 
1524 	switch (i) {
1525 	case 1:
1526 		fwd->listen_host = NULL;
1527 		fwd->listen_port = a2port(fwdarg[0]);
1528 		fwd->connect_host = xstrdup("socks");
1529 		break;
1530 
1531 	case 2:
1532 		fwd->listen_host = xstrdup(cleanhostname(fwdarg[0]));
1533 		fwd->listen_port = a2port(fwdarg[1]);
1534 		fwd->connect_host = xstrdup("socks");
1535 		break;
1536 
1537 	case 3:
1538 		fwd->listen_host = NULL;
1539 		fwd->listen_port = a2port(fwdarg[0]);
1540 		fwd->connect_host = xstrdup(cleanhostname(fwdarg[1]));
1541 		fwd->connect_port = a2port(fwdarg[2]);
1542 		break;
1543 
1544 	case 4:
1545 		fwd->listen_host = xstrdup(cleanhostname(fwdarg[0]));
1546 		fwd->listen_port = a2port(fwdarg[1]);
1547 		fwd->connect_host = xstrdup(cleanhostname(fwdarg[2]));
1548 		fwd->connect_port = a2port(fwdarg[3]);
1549 		break;
1550 	default:
1551 		i = 0; /* failure */
1552 	}
1553 
1554 	xfree(p);
1555 
1556 	if (dynamicfwd) {
1557 		if (!(i == 1 || i == 2))
1558 			goto fail_free;
1559 	} else {
1560 		if (!(i == 3 || i == 4))
1561 			goto fail_free;
1562 		if (fwd->connect_port <= 0)
1563 			goto fail_free;
1564 	}
1565 
1566 	if (fwd->listen_port < 0 || (!remotefwd && fwd->listen_port == 0))
1567 		goto fail_free;
1568 
1569 	if (fwd->connect_host != NULL &&
1570 	    strlen(fwd->connect_host) >= NI_MAXHOST)
1571 		goto fail_free;
1572 	if (fwd->listen_host != NULL &&
1573 	    strlen(fwd->listen_host) >= NI_MAXHOST)
1574 		goto fail_free;
1575 
1576 
1577 	return (i);
1578 
1579  fail_free:
1580 	if (fwd->connect_host != NULL) {
1581 		xfree(fwd->connect_host);
1582 		fwd->connect_host = NULL;
1583 	}
1584 	if (fwd->listen_host != NULL) {
1585 		xfree(fwd->listen_host);
1586 		fwd->listen_host = NULL;
1587 	}
1588 	return (0);
1589 }
1590