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