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