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