]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - crypto/openssh/readconf.c
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / crypto / openssh / readconf.c
1 /* $OpenBSD: readconf.c,v 1.190 2010/11/13 23:27:50 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,
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", oGlobalKnownHostsFile2 },    /* obsolete */
206         { "userknownhostsfile", oUserKnownHostsFile },
207         { "userknownhostsfile2", oUserKnownHostsFile2 },        /* obsolete */
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         { "hpndisabled", oHPNDisabled },
258         { "hpnbuffersize", oHPNBufferSize },
259         { "tcprcvbufpoll", oTcpRcvBufPoll },
260         { "tcprcvbuf", oTcpRcvBuf },
261 #ifdef  NONE_CIPHER_ENABLED
262         { "noneenabled", oNoneEnabled },
263         { "noneswitch", oNoneSwitch },
264 #endif
265
266         { "versionaddendum", oVersionAddendum },
267         { NULL, oBadOption }
268 };
269
270 /*
271  * Adds a local TCP/IP port forward to options.  Never returns if there is an
272  * error.
273  */
274
275 void
276 add_local_forward(Options *options, const Forward *newfwd)
277 {
278         Forward *fwd;
279 #ifndef NO_IPPORT_RESERVED_CONCEPT
280         extern uid_t original_real_uid;
281         int ipport_reserved;
282 #ifdef __FreeBSD__
283         size_t len_ipport_reserved = sizeof(ipport_reserved);
284
285         if (sysctlbyname("net.inet.ip.portrange.reservedhigh",
286             &ipport_reserved, &len_ipport_reserved, NULL, 0) != 0)
287                 ipport_reserved = IPPORT_RESERVED;
288         else
289                 ipport_reserved++;
290 #else
291         ipport_reserved = IPPORT_RESERVED;
292 #endif
293         if (newfwd->listen_port < ipport_reserved && original_real_uid != 0)
294                 fatal("Privileged ports can only be forwarded by root.");
295 #endif
296         options->local_forwards = xrealloc(options->local_forwards,
297             options->num_local_forwards + 1,
298             sizeof(*options->local_forwards));
299         fwd = &options->local_forwards[options->num_local_forwards++];
300
301         fwd->listen_host = newfwd->listen_host;
302         fwd->listen_port = newfwd->listen_port;
303         fwd->connect_host = newfwd->connect_host;
304         fwd->connect_port = newfwd->connect_port;
305 }
306
307 /*
308  * Adds a remote TCP/IP port forward to options.  Never returns if there is
309  * an error.
310  */
311
312 void
313 add_remote_forward(Options *options, const Forward *newfwd)
314 {
315         Forward *fwd;
316
317         options->remote_forwards = xrealloc(options->remote_forwards,
318             options->num_remote_forwards + 1,
319             sizeof(*options->remote_forwards));
320         fwd = &options->remote_forwards[options->num_remote_forwards++];
321
322         fwd->listen_host = newfwd->listen_host;
323         fwd->listen_port = newfwd->listen_port;
324         fwd->connect_host = newfwd->connect_host;
325         fwd->connect_port = newfwd->connect_port;
326         fwd->allocated_port = 0;
327 }
328
329 static void
330 clear_forwardings(Options *options)
331 {
332         int i;
333
334         for (i = 0; i < options->num_local_forwards; i++) {
335                 if (options->local_forwards[i].listen_host != NULL)
336                         xfree(options->local_forwards[i].listen_host);
337                 xfree(options->local_forwards[i].connect_host);
338         }
339         if (options->num_local_forwards > 0) {
340                 xfree(options->local_forwards);
341                 options->local_forwards = NULL;
342         }
343         options->num_local_forwards = 0;
344         for (i = 0; i < options->num_remote_forwards; i++) {
345                 if (options->remote_forwards[i].listen_host != NULL)
346                         xfree(options->remote_forwards[i].listen_host);
347                 xfree(options->remote_forwards[i].connect_host);
348         }
349         if (options->num_remote_forwards > 0) {
350                 xfree(options->remote_forwards);
351                 options->remote_forwards = NULL;
352         }
353         options->num_remote_forwards = 0;
354         options->tun_open = SSH_TUNMODE_NO;
355 }
356
357 /*
358  * Returns the number of the token pointed to by cp or oBadOption.
359  */
360
361 static OpCodes
362 parse_token(const char *cp, const char *filename, int linenum)
363 {
364         u_int i;
365
366         for (i = 0; keywords[i].name; i++)
367                 if (strcasecmp(cp, keywords[i].name) == 0)
368                         return keywords[i].opcode;
369
370         error("%s: line %d: Bad configuration option: %s",
371             filename, linenum, cp);
372         return oBadOption;
373 }
374
375 /*
376  * Processes a single option line as used in the configuration files. This
377  * only sets those values that have not already been set.
378  */
379 #define WHITESPACE " \t\r\n"
380
381 int
382 process_config_line(Options *options, const char *host,
383                     char *line, const char *filename, int linenum,
384                     int *activep)
385 {
386         char *s, **charptr, *endofnumber, *keyword, *arg, *arg2, fwdarg[256];
387         int opcode, *intptr, value, value2, scale;
388         LogLevel *log_level_ptr;
389         long long orig, val64;
390         size_t len;
391         Forward fwd;
392
393         /* Strip trailing whitespace */
394         for (len = strlen(line) - 1; len > 0; len--) {
395                 if (strchr(WHITESPACE, line[len]) == NULL)
396                         break;
397                 line[len] = '\0';
398         }
399
400         s = line;
401         /* Get the keyword. (Each line is supposed to begin with a keyword). */
402         if ((keyword = strdelim(&s)) == NULL)
403                 return 0;
404         /* Ignore leading whitespace. */
405         if (*keyword == '\0')
406                 keyword = strdelim(&s);
407         if (keyword == NULL || !*keyword || *keyword == '\n' || *keyword == '#')
408                 return 0;
409
410         opcode = parse_token(keyword, filename, linenum);
411
412         switch (opcode) {
413         case oBadOption:
414                 /* don't panic, but count bad options */
415                 return -1;
416                 /* NOTREACHED */
417         case oConnectTimeout:
418                 intptr = &options->connection_timeout;
419 parse_time:
420                 arg = strdelim(&s);
421                 if (!arg || *arg == '\0')
422                         fatal("%s line %d: missing time value.",
423                             filename, linenum);
424                 if ((value = convtime(arg)) == -1)
425                         fatal("%s line %d: invalid time value.",
426                             filename, linenum);
427                 if (*activep && *intptr == -1)
428                         *intptr = value;
429                 break;
430
431         case oForwardAgent:
432                 intptr = &options->forward_agent;
433 parse_flag:
434                 arg = strdelim(&s);
435                 if (!arg || *arg == '\0')
436                         fatal("%.200s line %d: Missing yes/no argument.", filename, linenum);
437                 value = 0;      /* To avoid compiler warning... */
438                 if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0)
439                         value = 1;
440                 else if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0)
441                         value = 0;
442                 else
443                         fatal("%.200s line %d: Bad yes/no argument.", filename, linenum);
444                 if (*activep && *intptr == -1)
445                         *intptr = value;
446                 break;
447
448         case oForwardX11:
449                 intptr = &options->forward_x11;
450                 goto parse_flag;
451
452         case oForwardX11Trusted:
453                 intptr = &options->forward_x11_trusted;
454                 goto parse_flag;
455         
456         case oForwardX11Timeout:
457                 intptr = &options->forward_x11_timeout;
458                 goto parse_time;
459
460         case oGatewayPorts:
461                 intptr = &options->gateway_ports;
462                 goto parse_flag;
463
464         case oExitOnForwardFailure:
465                 intptr = &options->exit_on_forward_failure;
466                 goto parse_flag;
467
468         case oUsePrivilegedPort:
469                 intptr = &options->use_privileged_port;
470                 goto parse_flag;
471
472         case oPasswordAuthentication:
473                 intptr = &options->password_authentication;
474                 goto parse_flag;
475
476         case oZeroKnowledgePasswordAuthentication:
477                 intptr = &options->zero_knowledge_password_authentication;
478                 goto parse_flag;
479
480         case oKbdInteractiveAuthentication:
481                 intptr = &options->kbd_interactive_authentication;
482                 goto parse_flag;
483
484         case oKbdInteractiveDevices:
485                 charptr = &options->kbd_interactive_devices;
486                 goto parse_string;
487
488         case oPubkeyAuthentication:
489                 intptr = &options->pubkey_authentication;
490                 goto parse_flag;
491
492         case oRSAAuthentication:
493                 intptr = &options->rsa_authentication;
494                 goto parse_flag;
495
496         case oRhostsRSAAuthentication:
497                 intptr = &options->rhosts_rsa_authentication;
498                 goto parse_flag;
499
500         case oHostbasedAuthentication:
501                 intptr = &options->hostbased_authentication;
502                 goto parse_flag;
503
504         case oChallengeResponseAuthentication:
505                 intptr = &options->challenge_response_authentication;
506                 goto parse_flag;
507
508         case oGssAuthentication:
509                 intptr = &options->gss_authentication;
510                 goto parse_flag;
511
512         case oGssDelegateCreds:
513                 intptr = &options->gss_deleg_creds;
514                 goto parse_flag;
515
516         case oBatchMode:
517                 intptr = &options->batch_mode;
518                 goto parse_flag;
519
520         case oCheckHostIP:
521                 intptr = &options->check_host_ip;
522                 goto parse_flag;
523
524         case oVerifyHostKeyDNS:
525                 intptr = &options->verify_host_key_dns;
526                 goto parse_yesnoask;
527
528         case oStrictHostKeyChecking:
529                 intptr = &options->strict_host_key_checking;
530 parse_yesnoask:
531                 arg = strdelim(&s);
532                 if (!arg || *arg == '\0')
533                         fatal("%.200s line %d: Missing yes/no/ask argument.",
534                             filename, linenum);
535                 value = 0;      /* To avoid compiler warning... */
536                 if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0)
537                         value = 1;
538                 else if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0)
539                         value = 0;
540                 else if (strcmp(arg, "ask") == 0)
541                         value = 2;
542                 else
543                         fatal("%.200s line %d: Bad yes/no/ask argument.", filename, linenum);
544                 if (*activep && *intptr == -1)
545                         *intptr = value;
546                 break;
547
548         case oCompression:
549                 intptr = &options->compression;
550                 goto parse_flag;
551
552         case oTCPKeepAlive:
553                 intptr = &options->tcp_keep_alive;
554                 goto parse_flag;
555
556         case oNoHostAuthenticationForLocalhost:
557                 intptr = &options->no_host_authentication_for_localhost;
558                 goto parse_flag;
559
560         case oNumberOfPasswordPrompts:
561                 intptr = &options->number_of_password_prompts;
562                 goto parse_int;
563
564         case oCompressionLevel:
565                 intptr = &options->compression_level;
566                 goto parse_int;
567
568         case oRekeyLimit:
569                 arg = strdelim(&s);
570                 if (!arg || *arg == '\0')
571                         fatal("%.200s line %d: Missing argument.", filename, linenum);
572                 if (arg[0] < '0' || arg[0] > '9')
573                         fatal("%.200s line %d: Bad number.", filename, linenum);
574                 orig = val64 = strtoll(arg, &endofnumber, 10);
575                 if (arg == endofnumber)
576                         fatal("%.200s line %d: Bad number.", filename, linenum);
577                 switch (toupper(*endofnumber)) {
578                 case '\0':
579                         scale = 1;
580                         break;
581                 case 'K':
582                         scale = 1<<10;
583                         break;
584                 case 'M':
585                         scale = 1<<20;
586                         break;
587                 case 'G':
588                         scale = 1<<30;
589                         break;
590                 default:
591                         fatal("%.200s line %d: Invalid RekeyLimit suffix",
592                             filename, linenum);
593                 }
594                 val64 *= scale;
595                 /* detect integer wrap and too-large limits */
596                 if ((val64 / scale) != orig || val64 > UINT_MAX)
597                         fatal("%.200s line %d: RekeyLimit too large",
598                             filename, linenum);
599                 if (val64 < 16)
600                         fatal("%.200s line %d: RekeyLimit too small",
601                             filename, linenum);
602                 if (*activep && options->rekey_limit == -1)
603                         options->rekey_limit = (u_int32_t)val64;
604                 break;
605
606         case oIdentityFile:
607                 arg = strdelim(&s);
608                 if (!arg || *arg == '\0')
609                         fatal("%.200s line %d: Missing argument.", filename, linenum);
610                 if (*activep) {
611                         intptr = &options->num_identity_files;
612                         if (*intptr >= SSH_MAX_IDENTITY_FILES)
613                                 fatal("%.200s line %d: Too many identity files specified (max %d).",
614                                     filename, linenum, SSH_MAX_IDENTITY_FILES);
615                         charptr = &options->identity_files[*intptr];
616                         *charptr = xstrdup(arg);
617                         *intptr = *intptr + 1;
618                 }
619                 break;
620
621         case oXAuthLocation:
622                 charptr=&options->xauth_location;
623                 goto parse_string;
624
625         case oUser:
626                 charptr = &options->user;
627 parse_string:
628                 arg = strdelim(&s);
629                 if (!arg || *arg == '\0')
630                         fatal("%.200s line %d: Missing argument.", filename, linenum);
631                 if (*activep && *charptr == NULL)
632                         *charptr = xstrdup(arg);
633                 break;
634
635         case oGlobalKnownHostsFile:
636                 charptr = &options->system_hostfile;
637                 goto parse_string;
638
639         case oUserKnownHostsFile:
640                 charptr = &options->user_hostfile;
641                 goto parse_string;
642
643         case oGlobalKnownHostsFile2:
644                 charptr = &options->system_hostfile2;
645                 goto parse_string;
646
647         case oUserKnownHostsFile2:
648                 charptr = &options->user_hostfile2;
649                 goto parse_string;
650
651         case oHostName:
652                 charptr = &options->hostname;
653                 goto parse_string;
654
655         case oHostKeyAlias:
656                 charptr = &options->host_key_alias;
657                 goto parse_string;
658
659         case oPreferredAuthentications:
660                 charptr = &options->preferred_authentications;
661                 goto parse_string;
662
663         case oBindAddress:
664                 charptr = &options->bind_address;
665                 goto parse_string;
666
667         case oPKCS11Provider:
668                 charptr = &options->pkcs11_provider;
669                 goto parse_string;
670
671         case oProxyCommand:
672                 charptr = &options->proxy_command;
673 parse_command:
674                 if (s == NULL)
675                         fatal("%.200s line %d: Missing argument.", filename, linenum);
676                 len = strspn(s, WHITESPACE "=");
677                 if (*activep && *charptr == NULL)
678                         *charptr = xstrdup(s + len);
679                 return 0;
680
681         case oPort:
682                 intptr = &options->port;
683 parse_int:
684                 arg = strdelim(&s);
685                 if (!arg || *arg == '\0')
686                         fatal("%.200s line %d: Missing argument.", filename, linenum);
687                 if (arg[0] < '0' || arg[0] > '9')
688                         fatal("%.200s line %d: Bad number.", filename, linenum);
689
690                 /* Octal, decimal, or hex format? */
691                 value = strtol(arg, &endofnumber, 0);
692                 if (arg == endofnumber)
693                         fatal("%.200s line %d: Bad number.", filename, linenum);
694                 if (*activep && *intptr == -1)
695                         *intptr = value;
696                 break;
697
698         case oConnectionAttempts:
699                 intptr = &options->connection_attempts;
700                 goto parse_int;
701
702         case oCipher:
703                 intptr = &options->cipher;
704                 arg = strdelim(&s);
705                 if (!arg || *arg == '\0')
706                         fatal("%.200s line %d: Missing argument.", filename, linenum);
707                 value = cipher_number(arg);
708                 if (value == -1)
709                         fatal("%.200s line %d: Bad cipher '%s'.",
710                             filename, linenum, arg ? arg : "<NONE>");
711                 if (*activep && *intptr == -1)
712                         *intptr = value;
713                 break;
714
715         case oCiphers:
716                 arg = strdelim(&s);
717                 if (!arg || *arg == '\0')
718                         fatal("%.200s line %d: Missing argument.", filename, linenum);
719                 if (!ciphers_valid(arg))
720                         fatal("%.200s line %d: Bad SSH2 cipher spec '%s'.",
721                             filename, linenum, arg ? arg : "<NONE>");
722                 if (*activep && options->ciphers == NULL)
723                         options->ciphers = xstrdup(arg);
724                 break;
725
726         case oMacs:
727                 arg = strdelim(&s);
728                 if (!arg || *arg == '\0')
729                         fatal("%.200s line %d: Missing argument.", filename, linenum);
730                 if (!mac_valid(arg))
731                         fatal("%.200s line %d: Bad SSH2 Mac spec '%s'.",
732                             filename, linenum, arg ? arg : "<NONE>");
733                 if (*activep && options->macs == NULL)
734                         options->macs = xstrdup(arg);
735                 break;
736
737         case oKexAlgorithms:
738                 arg = strdelim(&s);
739                 if (!arg || *arg == '\0')
740                         fatal("%.200s line %d: Missing argument.",
741                             filename, linenum);
742                 if (!kex_names_valid(arg))
743                         fatal("%.200s line %d: Bad SSH2 KexAlgorithms '%s'.",
744                             filename, linenum, arg ? arg : "<NONE>");
745                 if (*activep && options->kex_algorithms == NULL)
746                         options->kex_algorithms = xstrdup(arg);
747                 break;
748
749         case oHostKeyAlgorithms:
750                 arg = strdelim(&s);
751                 if (!arg || *arg == '\0')
752                         fatal("%.200s line %d: Missing argument.", filename, linenum);
753                 if (!key_names_valid2(arg))
754                         fatal("%.200s line %d: Bad protocol 2 host key algorithms '%s'.",
755                             filename, linenum, arg ? arg : "<NONE>");
756                 if (*activep && options->hostkeyalgorithms == NULL)
757                         options->hostkeyalgorithms = xstrdup(arg);
758                 break;
759
760         case oProtocol:
761                 intptr = &options->protocol;
762                 arg = strdelim(&s);
763                 if (!arg || *arg == '\0')
764                         fatal("%.200s line %d: Missing argument.", filename, linenum);
765                 value = proto_spec(arg);
766                 if (value == SSH_PROTO_UNKNOWN)
767                         fatal("%.200s line %d: Bad protocol spec '%s'.",
768                             filename, linenum, arg ? arg : "<NONE>");
769                 if (*activep && *intptr == SSH_PROTO_UNKNOWN)
770                         *intptr = value;
771                 break;
772
773         case oLogLevel:
774                 log_level_ptr = &options->log_level;
775                 arg = strdelim(&s);
776                 value = log_level_number(arg);
777                 if (value == SYSLOG_LEVEL_NOT_SET)
778                         fatal("%.200s line %d: unsupported log level '%s'",
779                             filename, linenum, arg ? arg : "<NONE>");
780                 if (*activep && *log_level_ptr == SYSLOG_LEVEL_NOT_SET)
781                         *log_level_ptr = (LogLevel) value;
782                 break;
783
784         case oLocalForward:
785         case oRemoteForward:
786         case oDynamicForward:
787                 arg = strdelim(&s);
788                 if (arg == NULL || *arg == '\0')
789                         fatal("%.200s line %d: Missing port argument.",
790                             filename, linenum);
791
792                 if (opcode == oLocalForward ||
793                     opcode == oRemoteForward) {
794                         arg2 = strdelim(&s);
795                         if (arg2 == NULL || *arg2 == '\0')
796                                 fatal("%.200s line %d: Missing target argument.",
797                                     filename, linenum);
798
799                         /* construct a string for parse_forward */
800                         snprintf(fwdarg, sizeof(fwdarg), "%s:%s", arg, arg2);
801                 } else if (opcode == oDynamicForward) {
802                         strlcpy(fwdarg, arg, sizeof(fwdarg));
803                 }
804
805                 if (parse_forward(&fwd, fwdarg,
806                     opcode == oDynamicForward ? 1 : 0,
807                     opcode == oRemoteForward ? 1 : 0) == 0)
808                         fatal("%.200s line %d: Bad forwarding specification.",
809                             filename, linenum);
810
811                 if (*activep) {
812                         if (opcode == oLocalForward ||
813                             opcode == oDynamicForward)
814                                 add_local_forward(options, &fwd);
815                         else if (opcode == oRemoteForward)
816                                 add_remote_forward(options, &fwd);
817                 }
818                 break;
819
820         case oClearAllForwardings:
821                 intptr = &options->clear_forwardings;
822                 goto parse_flag;
823
824         case oHost:
825                 *activep = 0;
826                 while ((arg = strdelim(&s)) != NULL && *arg != '\0')
827                         if (match_pattern(host, arg)) {
828                                 debug("Applying options for %.100s", arg);
829                                 *activep = 1;
830                                 break;
831                         }
832                 /* Avoid garbage check below, as strdelim is done. */
833                 return 0;
834
835         case oEscapeChar:
836                 intptr = &options->escape_char;
837                 arg = strdelim(&s);
838                 if (!arg || *arg == '\0')
839                         fatal("%.200s line %d: Missing argument.", filename, linenum);
840                 if (arg[0] == '^' && arg[2] == 0 &&
841                     (u_char) arg[1] >= 64 && (u_char) arg[1] < 128)
842                         value = (u_char) arg[1] & 31;
843                 else if (strlen(arg) == 1)
844                         value = (u_char) arg[0];
845                 else if (strcmp(arg, "none") == 0)
846                         value = SSH_ESCAPECHAR_NONE;
847                 else {
848                         fatal("%.200s line %d: Bad escape character.",
849                             filename, linenum);
850                         /* NOTREACHED */
851                         value = 0;      /* Avoid compiler warning. */
852                 }
853                 if (*activep && *intptr == -1)
854                         *intptr = value;
855                 break;
856
857         case oAddressFamily:
858                 arg = strdelim(&s);
859                 if (!arg || *arg == '\0')
860                         fatal("%s line %d: missing address family.",
861                             filename, linenum);
862                 intptr = &options->address_family;
863                 if (strcasecmp(arg, "inet") == 0)
864                         value = AF_INET;
865                 else if (strcasecmp(arg, "inet6") == 0)
866                         value = AF_INET6;
867                 else if (strcasecmp(arg, "any") == 0)
868                         value = AF_UNSPEC;
869                 else
870                         fatal("Unsupported AddressFamily \"%s\"", arg);
871                 if (*activep && *intptr == -1)
872                         *intptr = value;
873                 break;
874
875         case oEnableSSHKeysign:
876                 intptr = &options->enable_ssh_keysign;
877                 goto parse_flag;
878
879         case oIdentitiesOnly:
880                 intptr = &options->identities_only;
881                 goto parse_flag;
882
883         case oServerAliveInterval:
884                 intptr = &options->server_alive_interval;
885                 goto parse_time;
886
887         case oServerAliveCountMax:
888                 intptr = &options->server_alive_count_max;
889                 goto parse_int;
890
891         case oSendEnv:
892                 while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
893                         if (strchr(arg, '=') != NULL)
894                                 fatal("%s line %d: Invalid environment name.",
895                                     filename, linenum);
896                         if (!*activep)
897                                 continue;
898                         if (options->num_send_env >= MAX_SEND_ENV)
899                                 fatal("%s line %d: too many send env.",
900                                     filename, linenum);
901                         options->send_env[options->num_send_env++] =
902                             xstrdup(arg);
903                 }
904                 break;
905
906         case oControlPath:
907                 charptr = &options->control_path;
908                 goto parse_string;
909
910         case oControlMaster:
911                 intptr = &options->control_master;
912                 arg = strdelim(&s);
913                 if (!arg || *arg == '\0')
914                         fatal("%.200s line %d: Missing ControlMaster argument.",
915                             filename, linenum);
916                 value = 0;      /* To avoid compiler warning... */
917                 if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0)
918                         value = SSHCTL_MASTER_YES;
919                 else if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0)
920                         value = SSHCTL_MASTER_NO;
921                 else if (strcmp(arg, "auto") == 0)
922                         value = SSHCTL_MASTER_AUTO;
923                 else if (strcmp(arg, "ask") == 0)
924                         value = SSHCTL_MASTER_ASK;
925                 else if (strcmp(arg, "autoask") == 0)
926                         value = SSHCTL_MASTER_AUTO_ASK;
927                 else
928                         fatal("%.200s line %d: Bad ControlMaster argument.",
929                             filename, linenum);
930                 if (*activep && *intptr == -1)
931                         *intptr = value;
932                 break;
933
934         case oControlPersist:
935                 /* no/false/yes/true, or a time spec */
936                 intptr = &options->control_persist;
937                 arg = strdelim(&s);
938                 if (!arg || *arg == '\0')
939                         fatal("%.200s line %d: Missing ControlPersist"
940                             " argument.", filename, linenum);
941                 value = 0;
942                 value2 = 0;     /* timeout */
943                 if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0)
944                         value = 0;
945                 else if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0)
946                         value = 1;
947                 else if ((value2 = convtime(arg)) >= 0)
948                         value = 1;
949                 else
950                         fatal("%.200s line %d: Bad ControlPersist argument.",
951                             filename, linenum);
952                 if (*activep && *intptr == -1) {
953                         *intptr = value;
954                         options->control_persist_timeout = value2;
955                 }
956                 break;
957
958         case oHashKnownHosts:
959                 intptr = &options->hash_known_hosts;
960                 goto parse_flag;
961
962         case oTunnel:
963                 intptr = &options->tun_open;
964                 arg = strdelim(&s);
965                 if (!arg || *arg == '\0')
966                         fatal("%s line %d: Missing yes/point-to-point/"
967                             "ethernet/no argument.", filename, linenum);
968                 value = 0;      /* silence compiler */
969                 if (strcasecmp(arg, "ethernet") == 0)
970                         value = SSH_TUNMODE_ETHERNET;
971                 else if (strcasecmp(arg, "point-to-point") == 0)
972                         value = SSH_TUNMODE_POINTOPOINT;
973                 else if (strcasecmp(arg, "yes") == 0)
974                         value = SSH_TUNMODE_DEFAULT;
975                 else if (strcasecmp(arg, "no") == 0)
976                         value = SSH_TUNMODE_NO;
977                 else
978                         fatal("%s line %d: Bad yes/point-to-point/ethernet/"
979                             "no argument: %s", filename, linenum, arg);
980                 if (*activep)
981                         *intptr = value;
982                 break;
983
984         case oTunnelDevice:
985                 arg = strdelim(&s);
986                 if (!arg || *arg == '\0')
987                         fatal("%.200s line %d: Missing argument.", filename, linenum);
988                 value = a2tun(arg, &value2);
989                 if (value == SSH_TUNID_ERR)
990                         fatal("%.200s line %d: Bad tun device.", filename, linenum);
991                 if (*activep) {
992                         options->tun_local = value;
993                         options->tun_remote = value2;
994                 }
995                 break;
996
997         case oLocalCommand:
998                 charptr = &options->local_command;
999                 goto parse_command;
1000
1001         case oPermitLocalCommand:
1002                 intptr = &options->permit_local_command;
1003                 goto parse_flag;
1004
1005         case oVisualHostKey:
1006                 intptr = &options->visual_host_key;
1007                 goto parse_flag;
1008
1009         case oIPQoS:
1010                 arg = strdelim(&s);
1011                 if ((value = parse_ipqos(arg)) == -1)
1012                         fatal("%s line %d: Bad IPQoS value: %s",
1013                             filename, linenum, arg);
1014                 arg = strdelim(&s);
1015                 if (arg == NULL)
1016                         value2 = value;
1017                 else if ((value2 = parse_ipqos(arg)) == -1)
1018                         fatal("%s line %d: Bad IPQoS value: %s",
1019                             filename, linenum, arg);
1020                 if (*activep) {
1021                         options->ip_qos_interactive = value;
1022                         options->ip_qos_bulk = value2;
1023                 }
1024                 break;
1025
1026         case oUseRoaming:
1027                 intptr = &options->use_roaming;
1028                 goto parse_flag;
1029
1030         case oVersionAddendum:
1031                 ssh_version_set_addendum(strtok(s, "\n"));
1032                 do {
1033                         arg = strdelim(&s);
1034                 } while (arg != NULL && *arg != '\0');
1035                 break;
1036
1037         case oHPNDisabled:
1038                 intptr = &options->hpn_disabled;
1039                 goto parse_flag;
1040
1041         case oHPNBufferSize:
1042                 intptr = &options->hpn_buffer_size;
1043                 goto parse_int;
1044
1045         case oTcpRcvBufPoll:
1046                 intptr = &options->tcp_rcv_buf_poll;
1047                 goto parse_flag;
1048
1049         case oTcpRcvBuf:
1050                 intptr = &options->tcp_rcv_buf;
1051                 goto parse_int;
1052
1053 #ifdef  NONE_CIPHER_ENABLED
1054         case oNoneEnabled:
1055                 intptr = &options->none_enabled;
1056                 goto parse_flag;
1057  
1058         /*
1059          * We check to see if the command comes from the command line or not.
1060          * If it does then enable it otherwise fail.  NONE must never be a
1061          * default configuration.
1062          */
1063         case oNoneSwitch:
1064                 if (strcmp(filename,"command-line") == 0) {
1065                         intptr = &options->none_switch;
1066                         goto parse_flag;
1067                 } else {
1068                         debug("NoneSwitch directive found in %.200s.",
1069                             filename);
1070                         error("NoneSwitch is found in %.200s.\n"
1071                             "You may only use this configuration option "
1072                             "from the command line", filename);
1073                         error("Continuing...");
1074                         return 0;
1075                 }
1076 #endif
1077
1078         case oDeprecated:
1079                 debug("%s line %d: Deprecated option \"%s\"",
1080                     filename, linenum, keyword);
1081                 return 0;
1082
1083         case oUnsupported:
1084                 error("%s line %d: Unsupported option \"%s\"",
1085                     filename, linenum, keyword);
1086                 return 0;
1087
1088         default:
1089                 fatal("process_config_line: Unimplemented opcode %d", opcode);
1090         }
1091
1092         /* Check that there is no garbage at end of line. */
1093         if ((arg = strdelim(&s)) != NULL && *arg != '\0') {
1094                 fatal("%.200s line %d: garbage at end of line; \"%.200s\".",
1095                     filename, linenum, arg);
1096         }
1097         return 0;
1098 }
1099
1100
1101 /*
1102  * Reads the config file and modifies the options accordingly.  Options
1103  * should already be initialized before this call.  This never returns if
1104  * there is an error.  If the file does not exist, this returns 0.
1105  */
1106
1107 int
1108 read_config_file(const char *filename, const char *host, Options *options,
1109     int checkperm)
1110 {
1111         FILE *f;
1112         char line[1024];
1113         int active, linenum;
1114         int bad_options = 0;
1115
1116         if ((f = fopen(filename, "r")) == NULL)
1117                 return 0;
1118
1119         if (checkperm) {
1120                 struct stat sb;
1121
1122                 if (fstat(fileno(f), &sb) == -1)
1123                         fatal("fstat %s: %s", filename, strerror(errno));
1124                 if (((sb.st_uid != 0 && sb.st_uid != getuid()) ||
1125                     (sb.st_mode & 022) != 0))
1126                         fatal("Bad owner or permissions on %s", filename);
1127         }
1128
1129         debug("Reading configuration data %.200s", filename);
1130
1131         /*
1132          * Mark that we are now processing the options.  This flag is turned
1133          * on/off by Host specifications.
1134          */
1135         active = 1;
1136         linenum = 0;
1137         while (fgets(line, sizeof(line), f)) {
1138                 /* Update line number counter. */
1139                 linenum++;
1140                 if (process_config_line(options, host, line, filename, linenum, &active) != 0)
1141                         bad_options++;
1142         }
1143         fclose(f);
1144         if (bad_options > 0)
1145                 fatal("%s: terminating, %d bad configuration options",
1146                     filename, bad_options);
1147         return 1;
1148 }
1149
1150 /*
1151  * Initializes options to special values that indicate that they have not yet
1152  * been set.  Read_config_file will only set options with this value. Options
1153  * are processed in the following order: command line, user config file,
1154  * system config file.  Last, fill_default_options is called.
1155  */
1156
1157 void
1158 initialize_options(Options * options)
1159 {
1160         memset(options, 'X', sizeof(*options));
1161         options->forward_agent = -1;
1162         options->forward_x11 = -1;
1163         options->forward_x11_trusted = -1;
1164         options->forward_x11_timeout = -1;
1165         options->exit_on_forward_failure = -1;
1166         options->xauth_location = NULL;
1167         options->gateway_ports = -1;
1168         options->use_privileged_port = -1;
1169         options->rsa_authentication = -1;
1170         options->pubkey_authentication = -1;
1171         options->challenge_response_authentication = -1;
1172         options->gss_authentication = -1;
1173         options->gss_deleg_creds = -1;
1174         options->password_authentication = -1;
1175         options->kbd_interactive_authentication = -1;
1176         options->kbd_interactive_devices = NULL;
1177         options->rhosts_rsa_authentication = -1;
1178         options->hostbased_authentication = -1;
1179         options->batch_mode = -1;
1180         options->check_host_ip = -1;
1181         options->strict_host_key_checking = -1;
1182         options->compression = -1;
1183         options->tcp_keep_alive = -1;
1184         options->compression_level = -1;
1185         options->port = -1;
1186         options->address_family = -1;
1187         options->connection_attempts = -1;
1188         options->connection_timeout = -1;
1189         options->number_of_password_prompts = -1;
1190         options->cipher = -1;
1191         options->ciphers = NULL;
1192         options->macs = NULL;
1193         options->kex_algorithms = NULL;
1194         options->hostkeyalgorithms = NULL;
1195         options->protocol = SSH_PROTO_UNKNOWN;
1196         options->num_identity_files = 0;
1197         options->hostname = NULL;
1198         options->host_key_alias = NULL;
1199         options->proxy_command = NULL;
1200         options->user = NULL;
1201         options->escape_char = -1;
1202         options->system_hostfile = NULL;
1203         options->user_hostfile = NULL;
1204         options->system_hostfile2 = NULL;
1205         options->user_hostfile2 = NULL;
1206         options->local_forwards = NULL;
1207         options->num_local_forwards = 0;
1208         options->remote_forwards = NULL;
1209         options->num_remote_forwards = 0;
1210         options->clear_forwardings = -1;
1211         options->log_level = SYSLOG_LEVEL_NOT_SET;
1212         options->preferred_authentications = NULL;
1213         options->bind_address = NULL;
1214         options->pkcs11_provider = NULL;
1215         options->enable_ssh_keysign = - 1;
1216         options->no_host_authentication_for_localhost = - 1;
1217         options->identities_only = - 1;
1218         options->rekey_limit = - 1;
1219         options->verify_host_key_dns = -1;
1220         options->server_alive_interval = -1;
1221         options->server_alive_count_max = -1;
1222         options->num_send_env = 0;
1223         options->control_path = NULL;
1224         options->control_master = -1;
1225         options->control_persist = -1;
1226         options->control_persist_timeout = 0;
1227         options->hash_known_hosts = -1;
1228         options->tun_open = -1;
1229         options->tun_local = -1;
1230         options->tun_remote = -1;
1231         options->local_command = NULL;
1232         options->permit_local_command = -1;
1233         options->use_roaming = -1;
1234         options->visual_host_key = -1;
1235         options->zero_knowledge_password_authentication = -1;
1236         options->ip_qos_interactive = -1;
1237         options->ip_qos_bulk = -1;
1238         options->hpn_disabled = -1;
1239         options->hpn_buffer_size = -1;
1240         options->tcp_rcv_buf_poll = -1;
1241         options->tcp_rcv_buf = -1;
1242 #ifdef NONE_CIPHER_ENABLED
1243         options->none_enabled = -1;
1244         options->none_switch = -1;
1245 #endif
1246 }
1247
1248 /*
1249  * Called after processing other sources of option data, this fills those
1250  * options for which no value has been specified with their default values.
1251  */
1252
1253 void
1254 fill_default_options(Options * options)
1255 {
1256         int len;
1257
1258         if (options->forward_agent == -1)
1259                 options->forward_agent = 0;
1260         if (options->forward_x11 == -1)
1261                 options->forward_x11 = 0;
1262         if (options->forward_x11_trusted == -1)
1263                 options->forward_x11_trusted = 0;
1264         if (options->forward_x11_timeout == -1)
1265                 options->forward_x11_timeout = 1200;
1266         if (options->exit_on_forward_failure == -1)
1267                 options->exit_on_forward_failure = 0;
1268         if (options->xauth_location == NULL)
1269                 options->xauth_location = _PATH_XAUTH;
1270         if (options->gateway_ports == -1)
1271                 options->gateway_ports = 0;
1272         if (options->use_privileged_port == -1)
1273                 options->use_privileged_port = 0;
1274         if (options->rsa_authentication == -1)
1275                 options->rsa_authentication = 1;
1276         if (options->pubkey_authentication == -1)
1277                 options->pubkey_authentication = 1;
1278         if (options->challenge_response_authentication == -1)
1279                 options->challenge_response_authentication = 1;
1280         if (options->gss_authentication == -1)
1281                 options->gss_authentication = 0;
1282         if (options->gss_deleg_creds == -1)
1283                 options->gss_deleg_creds = 0;
1284         if (options->password_authentication == -1)
1285                 options->password_authentication = 1;
1286         if (options->kbd_interactive_authentication == -1)
1287                 options->kbd_interactive_authentication = 1;
1288         if (options->rhosts_rsa_authentication == -1)
1289                 options->rhosts_rsa_authentication = 0;
1290         if (options->hostbased_authentication == -1)
1291                 options->hostbased_authentication = 0;
1292         if (options->batch_mode == -1)
1293                 options->batch_mode = 0;
1294         if (options->check_host_ip == -1)
1295                 options->check_host_ip = 0;
1296         if (options->strict_host_key_checking == -1)
1297                 options->strict_host_key_checking = 2;  /* 2 is default */
1298         if (options->compression == -1)
1299                 options->compression = 0;
1300         if (options->tcp_keep_alive == -1)
1301                 options->tcp_keep_alive = 1;
1302         if (options->compression_level == -1)
1303                 options->compression_level = 6;
1304         if (options->port == -1)
1305                 options->port = 0;      /* Filled in ssh_connect. */
1306         if (options->address_family == -1)
1307                 options->address_family = AF_UNSPEC;
1308         if (options->connection_attempts == -1)
1309                 options->connection_attempts = 1;
1310         if (options->number_of_password_prompts == -1)
1311                 options->number_of_password_prompts = 3;
1312         /* Selected in ssh_login(). */
1313         if (options->cipher == -1)
1314                 options->cipher = SSH_CIPHER_NOT_SET;
1315         /* options->ciphers, default set in myproposals.h */
1316         /* options->macs, default set in myproposals.h */
1317         /* options->kex_algorithms, default set in myproposals.h */
1318         /* options->hostkeyalgorithms, default set in myproposals.h */
1319         if (options->protocol == SSH_PROTO_UNKNOWN)
1320                 options->protocol = SSH_PROTO_2;
1321         if (options->num_identity_files == 0) {
1322                 if (options->protocol & SSH_PROTO_1) {
1323                         len = 2 + strlen(_PATH_SSH_CLIENT_IDENTITY) + 1;
1324                         options->identity_files[options->num_identity_files] =
1325                             xmalloc(len);
1326                         snprintf(options->identity_files[options->num_identity_files++],
1327                             len, "~/%.100s", _PATH_SSH_CLIENT_IDENTITY);
1328                 }
1329                 if (options->protocol & SSH_PROTO_2) {
1330                         len = 2 + strlen(_PATH_SSH_CLIENT_ID_RSA) + 1;
1331                         options->identity_files[options->num_identity_files] =
1332                             xmalloc(len);
1333                         snprintf(options->identity_files[options->num_identity_files++],
1334                             len, "~/%.100s", _PATH_SSH_CLIENT_ID_RSA);
1335
1336                         len = 2 + strlen(_PATH_SSH_CLIENT_ID_DSA) + 1;
1337                         options->identity_files[options->num_identity_files] =
1338                             xmalloc(len);
1339                         snprintf(options->identity_files[options->num_identity_files++],
1340                             len, "~/%.100s", _PATH_SSH_CLIENT_ID_DSA);
1341 #ifdef OPENSSL_HAS_ECC
1342                         len = 2 + strlen(_PATH_SSH_CLIENT_ID_ECDSA) + 1;
1343                         options->identity_files[options->num_identity_files] =
1344                             xmalloc(len);
1345                         snprintf(options->identity_files[options->num_identity_files++],
1346                             len, "~/%.100s", _PATH_SSH_CLIENT_ID_ECDSA);
1347 #endif
1348                 }
1349         }
1350         if (options->escape_char == -1)
1351                 options->escape_char = '~';
1352         if (options->system_hostfile == NULL)
1353                 options->system_hostfile = _PATH_SSH_SYSTEM_HOSTFILE;
1354         if (options->user_hostfile == NULL)
1355                 options->user_hostfile = _PATH_SSH_USER_HOSTFILE;
1356         if (options->system_hostfile2 == NULL)
1357                 options->system_hostfile2 = _PATH_SSH_SYSTEM_HOSTFILE2;
1358         if (options->user_hostfile2 == NULL)
1359                 options->user_hostfile2 = _PATH_SSH_USER_HOSTFILE2;
1360         if (options->log_level == SYSLOG_LEVEL_NOT_SET)
1361                 options->log_level = SYSLOG_LEVEL_INFO;
1362         if (options->clear_forwardings == 1)
1363                 clear_forwardings(options);
1364         if (options->no_host_authentication_for_localhost == - 1)
1365                 options->no_host_authentication_for_localhost = 0;
1366         if (options->identities_only == -1)
1367                 options->identities_only = 0;
1368         if (options->enable_ssh_keysign == -1)
1369                 options->enable_ssh_keysign = 0;
1370         if (options->rekey_limit == -1)
1371                 options->rekey_limit = 0;
1372         if (options->verify_host_key_dns == -1)
1373                 options->verify_host_key_dns = 0;
1374         if (options->server_alive_interval == -1)
1375                 options->server_alive_interval = 0;
1376         if (options->server_alive_count_max == -1)
1377                 options->server_alive_count_max = 3;
1378         if (options->control_master == -1)
1379                 options->control_master = 0;
1380         if (options->control_persist == -1) {
1381                 options->control_persist = 0;
1382                 options->control_persist_timeout = 0;
1383         }
1384         if (options->hash_known_hosts == -1)
1385                 options->hash_known_hosts = 0;
1386         if (options->tun_open == -1)
1387                 options->tun_open = SSH_TUNMODE_NO;
1388         if (options->tun_local == -1)
1389                 options->tun_local = SSH_TUNID_ANY;
1390         if (options->tun_remote == -1)
1391                 options->tun_remote = SSH_TUNID_ANY;
1392         if (options->permit_local_command == -1)
1393                 options->permit_local_command = 0;
1394         if (options->use_roaming == -1)
1395                 options->use_roaming = 1;
1396         if (options->visual_host_key == -1)
1397                 options->visual_host_key = 0;
1398         if (options->zero_knowledge_password_authentication == -1)
1399                 options->zero_knowledge_password_authentication = 0;
1400         if (options->ip_qos_interactive == -1)
1401                 options->ip_qos_interactive = IPTOS_LOWDELAY;
1402         if (options->ip_qos_bulk == -1)
1403                 options->ip_qos_bulk = IPTOS_THROUGHPUT;
1404         /* options->local_command should not be set by default */
1405         /* options->proxy_command should not be set by default */
1406         /* options->user will be set in the main program if appropriate */
1407         /* options->hostname will be set in the main program if appropriate */
1408         /* options->host_key_alias should not be set by default */
1409         /* options->preferred_authentications will be set in ssh */
1410         if (options->hpn_disabled == -1)
1411                 options->hpn_disabled = 0;
1412         if (options->hpn_buffer_size > -1)
1413         {
1414                 u_int maxlen;
1415
1416                 /* If a user tries to set the size to 0 set it to 1KB. */
1417                 if (options->hpn_buffer_size == 0)
1418                         options->hpn_buffer_size = 1024;
1419                 /* Limit the buffer to BUFFER_MAX_LEN. */
1420                 maxlen = buffer_get_max_len();
1421                 if (options->hpn_buffer_size > (maxlen / 1024)) {
1422                         debug("User requested buffer larger than %ub: %ub. "
1423                             "Request reverted to %ub", maxlen,
1424                             options->hpn_buffer_size * 1024, maxlen);
1425                         options->hpn_buffer_size = maxlen;
1426                 }
1427                 debug("hpn_buffer_size set to %d", options->hpn_buffer_size);
1428         }
1429         if (options->tcp_rcv_buf == 0)
1430                 options->tcp_rcv_buf = 1;
1431         if (options->tcp_rcv_buf > -1) 
1432                 options->tcp_rcv_buf *= 1024;
1433         if (options->tcp_rcv_buf_poll == -1)
1434                 options->tcp_rcv_buf_poll = 1;
1435 #ifdef  NONE_CIPHER_ENABLED
1436         /* options->none_enabled must not be set by default */
1437         if (options->none_switch == -1)
1438                 options->none_switch = 0;
1439 #endif
1440 }
1441
1442 /*
1443  * parse_forward
1444  * parses a string containing a port forwarding specification of the form:
1445  *   dynamicfwd == 0
1446  *      [listenhost:]listenport:connecthost:connectport
1447  *   dynamicfwd == 1
1448  *      [listenhost:]listenport
1449  * returns number of arguments parsed or zero on error
1450  */
1451 int
1452 parse_forward(Forward *fwd, const char *fwdspec, int dynamicfwd, int remotefwd)
1453 {
1454         int i;
1455         char *p, *cp, *fwdarg[4];
1456
1457         memset(fwd, '\0', sizeof(*fwd));
1458
1459         cp = p = xstrdup(fwdspec);
1460
1461         /* skip leading spaces */
1462         while (isspace(*cp))
1463                 cp++;
1464
1465         for (i = 0; i < 4; ++i)
1466                 if ((fwdarg[i] = hpdelim(&cp)) == NULL)
1467                         break;
1468
1469         /* Check for trailing garbage */
1470         if (cp != NULL)
1471                 i = 0;  /* failure */
1472
1473         switch (i) {
1474         case 1:
1475                 fwd->listen_host = NULL;
1476                 fwd->listen_port = a2port(fwdarg[0]);
1477                 fwd->connect_host = xstrdup("socks");
1478                 break;
1479
1480         case 2:
1481                 fwd->listen_host = xstrdup(cleanhostname(fwdarg[0]));
1482                 fwd->listen_port = a2port(fwdarg[1]);
1483                 fwd->connect_host = xstrdup("socks");
1484                 break;
1485
1486         case 3:
1487                 fwd->listen_host = NULL;
1488                 fwd->listen_port = a2port(fwdarg[0]);
1489                 fwd->connect_host = xstrdup(cleanhostname(fwdarg[1]));
1490                 fwd->connect_port = a2port(fwdarg[2]);
1491                 break;
1492
1493         case 4:
1494                 fwd->listen_host = xstrdup(cleanhostname(fwdarg[0]));
1495                 fwd->listen_port = a2port(fwdarg[1]);
1496                 fwd->connect_host = xstrdup(cleanhostname(fwdarg[2]));
1497                 fwd->connect_port = a2port(fwdarg[3]);
1498                 break;
1499         default:
1500                 i = 0; /* failure */
1501         }
1502
1503         xfree(p);
1504
1505         if (dynamicfwd) {
1506                 if (!(i == 1 || i == 2))
1507                         goto fail_free;
1508         } else {
1509                 if (!(i == 3 || i == 4))
1510                         goto fail_free;
1511                 if (fwd->connect_port <= 0)
1512                         goto fail_free;
1513         }
1514
1515         if (fwd->listen_port < 0 || (!remotefwd && fwd->listen_port == 0))
1516                 goto fail_free;
1517
1518         if (fwd->connect_host != NULL &&
1519             strlen(fwd->connect_host) >= NI_MAXHOST)
1520                 goto fail_free;
1521         if (fwd->listen_host != NULL &&
1522             strlen(fwd->listen_host) >= NI_MAXHOST)
1523                 goto fail_free;
1524
1525
1526         return (i);
1527
1528  fail_free:
1529         if (fwd->connect_host != NULL) {
1530                 xfree(fwd->connect_host);
1531                 fwd->connect_host = NULL;
1532         }
1533         if (fwd->listen_host != NULL) {
1534                 xfree(fwd->listen_host);
1535                 fwd->listen_host = NULL;
1536         }
1537         return (0);
1538 }