[BACK]Return to readconf.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/readconf.c, Revision 1.221

1.221   ! djm         1: /* $OpenBSD: readconf.c,v 1.220 2014/07/15 15:54:14 millert Exp $ */
1.1       deraadt     2: /*
1.18      deraadt     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.
1.26      markus      7:  *
1.46      deraadt     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".
1.18      deraadt    13:  */
1.1       deraadt    14:
1.147     stevesk    15: #include <sys/types.h>
                     16: #include <sys/stat.h>
1.152     stevesk    17: #include <sys/socket.h>
1.206     djm        18: #include <sys/wait.h>
1.220     millert    19: #include <sys/un.h>
1.152     stevesk    20:
                     21: #include <netinet/in.h>
1.190     djm        22: #include <netinet/in_systm.h>
                     23: #include <netinet/ip.h>
1.148     stevesk    24:
                     25: #include <ctype.h>
1.154     stevesk    26: #include <errno.h>
1.206     djm        27: #include <fcntl.h>
1.155     stevesk    28: #include <netdb.h>
1.206     djm        29: #include <paths.h>
                     30: #include <pwd.h>
1.159     deraadt    31: #include <signal.h>
1.158     stevesk    32: #include <stdio.h>
1.157     stevesk    33: #include <string.h>
1.156     stevesk    34: #include <unistd.h>
1.200     dtucker    35: #include <util.h>
1.221   ! djm        36: #include <vis.h>
1.1       deraadt    37:
1.159     deraadt    38: #include "xmalloc.h"
1.1       deraadt    39: #include "ssh.h"
1.25      markus     40: #include "compat.h"
1.58      markus     41: #include "cipher.h"
1.55      markus     42: #include "pathnames.h"
1.58      markus     43: #include "log.h"
1.159     deraadt    44: #include "key.h"
1.220     millert    45: #include "misc.h"
1.58      markus     46: #include "readconf.h"
                     47: #include "match.h"
1.159     deraadt    48: #include "buffer.h"
1.62      markus     49: #include "kex.h"
                     50: #include "mac.h"
1.206     djm        51: #include "uidswap.h"
1.221   ! djm        52: #include "myproposal.h"
1.1       deraadt    53:
                     54: /* Format of the configuration file:
                     55:
                     56:    # Configuration data is parsed as follows:
                     57:    #  1. command line options
                     58:    #  2. user-specific file
                     59:    #  3. system-wide file
                     60:    # Any configuration value is only changed the first time it is set.
                     61:    # Thus, host-specific definitions should be at the beginning of the
                     62:    # configuration file, and defaults at the end.
                     63:
                     64:    # Host-specific declarations.  These may override anything above.  A single
                     65:    # host may match multiple declarations; these are processed in the order
                     66:    # that they are given in.
                     67:
                     68:    Host *.ngs.fi ngs.fi
1.96      markus     69:      User foo
1.1       deraadt    70:
                     71:    Host fake.com
                     72:      HostName another.host.name.real.org
                     73:      User blaah
                     74:      Port 34289
                     75:      ForwardX11 no
                     76:      ForwardAgent no
                     77:
                     78:    Host books.com
                     79:      RemoteForward 9999 shadows.cs.hut.fi:9999
                     80:      Cipher 3des
                     81:
                     82:    Host fascist.blob.com
                     83:      Port 23123
                     84:      User tylonen
                     85:      PasswordAuthentication no
                     86:
                     87:    Host puukko.hut.fi
                     88:      User t35124p
                     89:      ProxyCommand ssh-proxy %h %p
                     90:
                     91:    Host *.fr
1.96      markus     92:      PublicKeyAuthentication no
1.1       deraadt    93:
                     94:    Host *.su
                     95:      Cipher none
                     96:      PasswordAuthentication no
                     97:
1.144     reyk       98:    Host vpn.fake.com
                     99:      Tunnel yes
                    100:      TunnelDevice 3
                    101:
1.1       deraadt   102:    # Defaults for various options
                    103:    Host *
                    104:      ForwardAgent no
1.50      markus    105:      ForwardX11 no
1.1       deraadt   106:      PasswordAuthentication yes
                    107:      RSAAuthentication yes
                    108:      RhostsRSAAuthentication yes
                    109:      StrictHostKeyChecking yes
1.126     markus    110:      TcpKeepAlive no
1.1       deraadt   111:      IdentityFile ~/.ssh/identity
                    112:      Port 22
                    113:      EscapeChar ~
                    114:
                    115: */
                    116:
                    117: /* Keyword tokens. */
                    118:
1.17      markus    119: typedef enum {
                    120:        oBadOption,
1.206     djm       121:        oHost, oMatch,
1.186     djm       122:        oForwardAgent, oForwardX11, oForwardX11Trusted, oForwardX11Timeout,
                    123:        oGatewayPorts, oExitOnForwardFailure,
1.100     deraadt   124:        oPasswordAuthentication, oRSAAuthentication,
1.59      markus    125:        oChallengeResponseAuthentication, oXAuthLocation,
1.17      markus    126:        oIdentityFile, oHostName, oPort, oCipher, oRemoteForward, oLocalForward,
1.206     djm       127:        oUser, oEscapeChar, oRhostsRSAAuthentication, oProxyCommand,
1.17      markus    128:        oGlobalKnownHostsFile, oUserKnownHostsFile, oConnectionAttempts,
                    129:        oBatchMode, oCheckHostIP, oStrictHostKeyChecking, oCompression,
1.126     markus    130:        oCompressionLevel, oTCPKeepAlive, oNumberOfPasswordPrompts,
1.62      markus    131:        oUsePrivilegedPort, oLogLevel, oCiphers, oProtocol, oMacs,
1.221   ! djm       132:        oPubkeyAuthentication,
1.67      markus    133:        oKbdInteractiveAuthentication, oKbdInteractiveDevices, oHostKeyAlias,
1.76      markus    134:        oDynamicForward, oPreferredAuthentications, oHostbasedAuthentication,
1.183     markus    135:        oHostKeyAlgorithms, oBindAddress, oPKCS11Provider,
1.96      markus    136:        oClearAllForwardings, oNoHostAuthenticationForLocalhost,
1.111     djm       137:        oEnableSSHKeysign, oRekeyLimit, oVerifyHostKeyDNS, oConnectTimeout,
1.118     markus    138:        oAddressFamily, oGssAuthentication, oGssDelegateCreds,
1.128     markus    139:        oServerAliveInterval, oServerAliveCountMax, oIdentitiesOnly,
1.187     djm       140:        oSendEnv, oControlPath, oControlMaster, oControlPersist,
                    141:        oHashKnownHosts,
1.144     reyk      142:        oTunnel, oTunnelDevice, oLocalCommand, oPermitLocalCommand,
1.216     djm       143:        oVisualHostKey, oUseRoaming,
1.205     djm       144:        oKexAlgorithms, oIPQoS, oRequestTTY, oIgnoreUnknown, oProxyUseFdpass,
1.209     djm       145:        oCanonicalDomains, oCanonicalizeHostname, oCanonicalizeMaxDots,
                    146:        oCanonicalizeFallbackLocal, oCanonicalizePermittedCNAMEs,
1.220     millert   147:        oStreamLocalBindMask, oStreamLocalBindUnlink,
1.199     djm       148:        oIgnoredUnknownOption, oDeprecated, oUnsupported
1.1       deraadt   149: } OpCodes;
                    150:
                    151: /* Textual representations of the tokens. */
                    152:
1.17      markus    153: static struct {
                    154:        const char *name;
                    155:        OpCodes opcode;
                    156: } keywords[] = {
                    157:        { "forwardagent", oForwardAgent },
                    158:        { "forwardx11", oForwardX11 },
1.123     markus    159:        { "forwardx11trusted", oForwardX11Trusted },
1.186     djm       160:        { "forwardx11timeout", oForwardX11Timeout },
1.153     markus    161:        { "exitonforwardfailure", oExitOnForwardFailure },
1.34      markus    162:        { "xauthlocation", oXAuthLocation },
1.17      markus    163:        { "gatewayports", oGatewayPorts },
                    164:        { "useprivilegedport", oUsePrivilegedPort },
1.116     markus    165:        { "rhostsauthentication", oDeprecated },
1.17      markus    166:        { "passwordauthentication", oPasswordAuthentication },
1.48      markus    167:        { "kbdinteractiveauthentication", oKbdInteractiveAuthentication },
                    168:        { "kbdinteractivedevices", oKbdInteractiveDevices },
1.17      markus    169:        { "rsaauthentication", oRSAAuthentication },
1.50      markus    170:        { "pubkeyauthentication", oPubkeyAuthentication },
1.59      markus    171:        { "dsaauthentication", oPubkeyAuthentication },             /* alias */
1.72      markus    172:        { "rhostsrsaauthentication", oRhostsRSAAuthentication },
1.73      markus    173:        { "hostbasedauthentication", oHostbasedAuthentication },
1.59      markus    174:        { "challengeresponseauthentication", oChallengeResponseAuthentication },
                    175:        { "skeyauthentication", oChallengeResponseAuthentication }, /* alias */
                    176:        { "tisauthentication", oChallengeResponseAuthentication },  /* alias */
1.110     jakob     177:        { "kerberosauthentication", oUnsupported },
                    178:        { "kerberostgtpassing", oUnsupported },
                    179:        { "afstokenpassing", oUnsupported },
1.118     markus    180: #if defined(GSSAPI)
                    181:        { "gssapiauthentication", oGssAuthentication },
                    182:        { "gssapidelegatecredentials", oGssDelegateCreds },
                    183: #else
                    184:        { "gssapiauthentication", oUnsupported },
                    185:        { "gssapidelegatecredentials", oUnsupported },
                    186: #endif
1.96      markus    187:        { "fallbacktorsh", oDeprecated },
                    188:        { "usersh", oDeprecated },
1.17      markus    189:        { "identityfile", oIdentityFile },
1.174     stevesk   190:        { "identityfile2", oIdentityFile },                     /* obsolete */
1.128     markus    191:        { "identitiesonly", oIdentitiesOnly },
1.17      markus    192:        { "hostname", oHostName },
1.52      markus    193:        { "hostkeyalias", oHostKeyAlias },
1.17      markus    194:        { "proxycommand", oProxyCommand },
                    195:        { "port", oPort },
                    196:        { "cipher", oCipher },
1.25      markus    197:        { "ciphers", oCiphers },
1.62      markus    198:        { "macs", oMacs },
1.25      markus    199:        { "protocol", oProtocol },
1.17      markus    200:        { "remoteforward", oRemoteForward },
                    201:        { "localforward", oLocalForward },
                    202:        { "user", oUser },
                    203:        { "host", oHost },
1.206     djm       204:        { "match", oMatch },
1.17      markus    205:        { "escapechar", oEscapeChar },
                    206:        { "globalknownhostsfile", oGlobalKnownHostsFile },
1.193     djm       207:        { "globalknownhostsfile2", oDeprecated },
1.174     stevesk   208:        { "userknownhostsfile", oUserKnownHostsFile },
1.221   ! djm       209:        { "userknownhostsfile2", oDeprecated },
1.17      markus    210:        { "connectionattempts", oConnectionAttempts },
                    211:        { "batchmode", oBatchMode },
                    212:        { "checkhostip", oCheckHostIP },
                    213:        { "stricthostkeychecking", oStrictHostKeyChecking },
                    214:        { "compression", oCompression },
                    215:        { "compressionlevel", oCompressionLevel },
1.126     markus    216:        { "tcpkeepalive", oTCPKeepAlive },
                    217:        { "keepalive", oTCPKeepAlive },                         /* obsolete */
1.17      markus    218:        { "numberofpasswordprompts", oNumberOfPasswordPrompts },
                    219:        { "loglevel", oLogLevel },
1.71      markus    220:        { "dynamicforward", oDynamicForward },
1.67      markus    221:        { "preferredauthentications", oPreferredAuthentications },
1.76      markus    222:        { "hostkeyalgorithms", oHostKeyAlgorithms },
1.77      markus    223:        { "bindaddress", oBindAddress },
1.183     markus    224: #ifdef ENABLE_PKCS11
                    225:        { "smartcarddevice", oPKCS11Provider },
                    226:        { "pkcs11provider", oPKCS11Provider },
1.110     jakob     227: #else
                    228:        { "smartcarddevice", oUnsupported },
1.183     markus    229:        { "pkcs11provider", oUnsupported },
1.110     jakob     230: #endif
1.93      deraadt   231:        { "clearallforwardings", oClearAllForwardings },
1.101     markus    232:        { "enablesshkeysign", oEnableSSHKeysign },
1.107     jakob     233:        { "verifyhostkeydns", oVerifyHostKeyDNS },
1.93      deraadt   234:        { "nohostauthenticationforlocalhost", oNoHostAuthenticationForLocalhost },
1.105     markus    235:        { "rekeylimit", oRekeyLimit },
1.111     djm       236:        { "connecttimeout", oConnectTimeout },
1.112     djm       237:        { "addressfamily", oAddressFamily },
1.127     markus    238:        { "serveraliveinterval", oServerAliveInterval },
                    239:        { "serveralivecountmax", oServerAliveCountMax },
1.130     djm       240:        { "sendenv", oSendEnv },
1.132     djm       241:        { "controlpath", oControlPath },
                    242:        { "controlmaster", oControlMaster },
1.187     djm       243:        { "controlpersist", oControlPersist },
1.136     djm       244:        { "hashknownhosts", oHashKnownHosts },
1.144     reyk      245:        { "tunnel", oTunnel },
                    246:        { "tunneldevice", oTunnelDevice },
                    247:        { "localcommand", oLocalCommand },
                    248:        { "permitlocalcommand", oPermitLocalCommand },
1.167     grunk     249:        { "visualhostkey", oVisualHostKey },
1.177     andreas   250:        { "useroaming", oUseRoaming },
1.189     djm       251:        { "kexalgorithms", oKexAlgorithms },
1.190     djm       252:        { "ipqos", oIPQoS },
1.192     djm       253:        { "requesttty", oRequestTTY },
1.205     djm       254:        { "proxyusefdpass", oProxyUseFdpass },
1.208     djm       255:        { "canonicaldomains", oCanonicalDomains },
1.209     djm       256:        { "canonicalizefallbacklocal", oCanonicalizeFallbackLocal },
                    257:        { "canonicalizehostname", oCanonicalizeHostname },
                    258:        { "canonicalizemaxdots", oCanonicalizeMaxDots },
                    259:        { "canonicalizepermittedcnames", oCanonicalizePermittedCNAMEs },
1.220     millert   260:        { "streamlocalbindmask", oStreamLocalBindMask },
                    261:        { "streamlocalbindunlink", oStreamLocalBindUnlink },
1.199     djm       262:        { "ignoreunknown", oIgnoreUnknown },
1.171     djm       263:
1.92      stevesk   264:        { NULL, oBadOption }
1.13      markus    265: };
                    266:
1.19      markus    267: /*
                    268:  * Adds a local TCP/IP port forward to options.  Never returns if there is an
                    269:  * error.
                    270:  */
1.1       deraadt   271:
1.26      markus    272: void
1.220     millert   273: add_local_forward(Options *options, const struct Forward *newfwd)
1.1       deraadt   274: {
1.220     millert   275:        struct Forward *fwd;
1.17      markus    276:        extern uid_t original_real_uid;
1.185     djm       277:
1.220     millert   278:        if (newfwd->listen_port < IPPORT_RESERVED && original_real_uid != 0 &&
                    279:            newfwd->listen_path == NULL)
1.64      millert   280:                fatal("Privileged ports can only be forwarded by root.");
1.185     djm       281:        options->local_forwards = xrealloc(options->local_forwards,
                    282:            options->num_local_forwards + 1,
                    283:            sizeof(*options->local_forwards));
1.17      markus    284:        fwd = &options->local_forwards[options->num_local_forwards++];
1.135     djm       285:
1.172     stevesk   286:        fwd->listen_host = newfwd->listen_host;
1.135     djm       287:        fwd->listen_port = newfwd->listen_port;
1.220     millert   288:        fwd->listen_path = newfwd->listen_path;
1.172     stevesk   289:        fwd->connect_host = newfwd->connect_host;
1.135     djm       290:        fwd->connect_port = newfwd->connect_port;
1.220     millert   291:        fwd->connect_path = newfwd->connect_path;
1.1       deraadt   292: }
                    293:
1.19      markus    294: /*
                    295:  * Adds a remote TCP/IP port forward to options.  Never returns if there is
                    296:  * an error.
                    297:  */
1.1       deraadt   298:
1.26      markus    299: void
1.220     millert   300: add_remote_forward(Options *options, const struct Forward *newfwd)
1.1       deraadt   301: {
1.220     millert   302:        struct Forward *fwd;
1.185     djm       303:
                    304:        options->remote_forwards = xrealloc(options->remote_forwards,
                    305:            options->num_remote_forwards + 1,
                    306:            sizeof(*options->remote_forwards));
1.17      markus    307:        fwd = &options->remote_forwards[options->num_remote_forwards++];
1.135     djm       308:
1.172     stevesk   309:        fwd->listen_host = newfwd->listen_host;
1.135     djm       310:        fwd->listen_port = newfwd->listen_port;
1.220     millert   311:        fwd->listen_path = newfwd->listen_path;
1.172     stevesk   312:        fwd->connect_host = newfwd->connect_host;
1.135     djm       313:        fwd->connect_port = newfwd->connect_port;
1.220     millert   314:        fwd->connect_path = newfwd->connect_path;
1.194     markus    315:        fwd->handle = newfwd->handle;
1.184     markus    316:        fwd->allocated_port = 0;
1.1       deraadt   317: }
                    318:
1.90      stevesk   319: static void
                    320: clear_forwardings(Options *options)
                    321: {
                    322:        int i;
                    323:
1.135     djm       324:        for (i = 0; i < options->num_local_forwards; i++) {
1.202     djm       325:                free(options->local_forwards[i].listen_host);
1.220     millert   326:                free(options->local_forwards[i].listen_path);
1.202     djm       327:                free(options->local_forwards[i].connect_host);
1.220     millert   328:                free(options->local_forwards[i].connect_path);
1.135     djm       329:        }
1.185     djm       330:        if (options->num_local_forwards > 0) {
1.202     djm       331:                free(options->local_forwards);
1.185     djm       332:                options->local_forwards = NULL;
                    333:        }
1.90      stevesk   334:        options->num_local_forwards = 0;
1.135     djm       335:        for (i = 0; i < options->num_remote_forwards; i++) {
1.202     djm       336:                free(options->remote_forwards[i].listen_host);
1.220     millert   337:                free(options->remote_forwards[i].listen_path);
1.202     djm       338:                free(options->remote_forwards[i].connect_host);
1.220     millert   339:                free(options->remote_forwards[i].connect_path);
1.135     djm       340:        }
1.185     djm       341:        if (options->num_remote_forwards > 0) {
1.202     djm       342:                free(options->remote_forwards);
1.185     djm       343:                options->remote_forwards = NULL;
                    344:        }
1.90      stevesk   345:        options->num_remote_forwards = 0;
1.145     reyk      346:        options->tun_open = SSH_TUNMODE_NO;
1.90      stevesk   347: }
                    348:
1.195     dtucker   349: void
                    350: add_identity_file(Options *options, const char *dir, const char *filename,
                    351:     int userprovided)
                    352: {
                    353:        char *path;
1.219     djm       354:        int i;
1.195     dtucker   355:
                    356:        if (options->num_identity_files >= SSH_MAX_IDENTITY_FILES)
                    357:                fatal("Too many identity files specified (max %d)",
                    358:                    SSH_MAX_IDENTITY_FILES);
                    359:
                    360:        if (dir == NULL) /* no dir, filename is absolute */
                    361:                path = xstrdup(filename);
                    362:        else
                    363:                (void)xasprintf(&path, "%.100s%.100s", dir, filename);
1.219     djm       364:
                    365:        /* Avoid registering duplicates */
                    366:        for (i = 0; i < options->num_identity_files; i++) {
                    367:                if (options->identity_file_userprovided[i] == userprovided &&
                    368:                    strcmp(options->identity_files[i], path) == 0) {
                    369:                        debug2("%s: ignoring duplicate key %s", __func__, path);
                    370:                        free(path);
                    371:                        return;
                    372:                }
                    373:        }
1.195     dtucker   374:
                    375:        options->identity_file_userprovided[options->num_identity_files] =
                    376:            userprovided;
                    377:        options->identity_files[options->num_identity_files++] = path;
                    378: }
                    379:
1.206     djm       380: int
                    381: default_ssh_port(void)
                    382: {
                    383:        static int port;
                    384:        struct servent *sp;
                    385:
                    386:        if (port == 0) {
                    387:                sp = getservbyname(SSH_SERVICE_NAME, "tcp");
                    388:                port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
                    389:        }
                    390:        return port;
                    391: }
                    392:
                    393: /*
                    394:  * Execute a command in a shell.
                    395:  * Return its exit status or -1 on abnormal exit.
                    396:  */
                    397: static int
                    398: execute_in_shell(const char *cmd)
                    399: {
                    400:        char *shell, *command_string;
                    401:        pid_t pid;
                    402:        int devnull, status;
                    403:        extern uid_t original_real_uid;
                    404:
                    405:        if ((shell = getenv("SHELL")) == NULL)
                    406:                shell = _PATH_BSHELL;
                    407:
                    408:        /*
                    409:         * Use "exec" to avoid "sh -c" processes on some platforms
                    410:         * (e.g. Solaris)
                    411:         */
                    412:        xasprintf(&command_string, "exec %s", cmd);
                    413:
                    414:        /* Need this to redirect subprocess stdin/out */
                    415:        if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1)
                    416:                fatal("open(/dev/null): %s", strerror(errno));
                    417:
                    418:        debug("Executing command: '%.500s'", cmd);
                    419:
                    420:        /* Fork and execute the command. */
                    421:        if ((pid = fork()) == 0) {
                    422:                char *argv[4];
                    423:
                    424:                /* Child.  Permanently give up superuser privileges. */
                    425:                permanently_drop_suid(original_real_uid);
                    426:
                    427:                /* Redirect child stdin and stdout. Leave stderr */
                    428:                if (dup2(devnull, STDIN_FILENO) == -1)
                    429:                        fatal("dup2: %s", strerror(errno));
                    430:                if (dup2(devnull, STDOUT_FILENO) == -1)
                    431:                        fatal("dup2: %s", strerror(errno));
                    432:                if (devnull > STDERR_FILENO)
                    433:                        close(devnull);
                    434:                closefrom(STDERR_FILENO + 1);
                    435:
                    436:                argv[0] = shell;
                    437:                argv[1] = "-c";
                    438:                argv[2] = command_string;
                    439:                argv[3] = NULL;
                    440:
                    441:                execv(argv[0], argv);
                    442:                error("Unable to execute '%.100s': %s", cmd, strerror(errno));
                    443:                /* Die with signal to make this error apparent to parent. */
                    444:                signal(SIGTERM, SIG_DFL);
                    445:                kill(getpid(), SIGTERM);
                    446:                _exit(1);
                    447:        }
                    448:        /* Parent. */
                    449:        if (pid < 0)
                    450:                fatal("%s: fork: %.100s", __func__, strerror(errno));
                    451:
                    452:        close(devnull);
                    453:        free(command_string);
                    454:
                    455:        while (waitpid(pid, &status, 0) == -1) {
                    456:                if (errno != EINTR && errno != EAGAIN)
                    457:                        fatal("%s: waitpid: %s", __func__, strerror(errno));
                    458:        }
                    459:        if (!WIFEXITED(status)) {
                    460:                error("command '%.100s' exited abnormally", cmd);
                    461:                return -1;
1.221   ! djm       462:        }
1.206     djm       463:        debug3("command returned status %d", WEXITSTATUS(status));
                    464:        return WEXITSTATUS(status);
                    465: }
                    466:
                    467: /*
                    468:  * Parse and execute a Match directive.
                    469:  */
                    470: static int
                    471: match_cfg_line(Options *options, char **condition, struct passwd *pw,
1.221   ! djm       472:     const char *host_arg, const char *original_host, int post_canon,
        !           473:     const char *filename, int linenum)
1.206     djm       474: {
1.221   ! djm       475:        char *arg, *oattrib, *attrib, *cmd, *cp = *condition, *host, *criteria;
1.211     djm       476:        const char *ruser;
1.221   ! djm       477:        int r, port, this_result, result = 1, attributes = 0, negate;
1.206     djm       478:        size_t len;
                    479:        char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
                    480:
                    481:        /*
                    482:         * Configuration is likely to be incomplete at this point so we
                    483:         * must be prepared to use default values.
                    484:         */
                    485:        port = options->port <= 0 ? default_ssh_port() : options->port;
                    486:        ruser = options->user == NULL ? pw->pw_name : options->user;
1.211     djm       487:        if (options->hostname != NULL) {
1.212     djm       488:                /* NB. Please keep in sync with ssh.c:main() */
1.211     djm       489:                host = percent_expand(options->hostname,
                    490:                    "h", host_arg, (char *)NULL);
                    491:        } else
                    492:                host = xstrdup(host_arg);
1.206     djm       493:
1.221   ! djm       494:        debug2("checking match for '%s' host %s originally %s",
        !           495:            cp, host, original_host);
        !           496:        while ((oattrib = attrib = strdelim(&cp)) && *attrib != '\0') {
        !           497:                criteria = NULL;
        !           498:                this_result = 1;
        !           499:                if ((negate = attrib[0] == '!'))
        !           500:                        attrib++;
        !           501:                /* criteria "all" and "canonical" have no argument */
1.213     dtucker   502:                if (strcasecmp(attrib, "all") == 0) {
1.221   ! djm       503:                        if (attributes > 1 ||
1.213     dtucker   504:                            ((arg = strdelim(&cp)) != NULL && *arg != '\0')) {
1.221   ! djm       505:                                error("%.200s line %d: '%s' cannot be combined "
        !           506:                                    "with other Match attributes",
        !           507:                                    filename, linenum, oattrib);
1.213     dtucker   508:                                result = -1;
                    509:                                goto out;
                    510:                        }
1.221   ! djm       511:                        if (result)
        !           512:                                result = negate ? 0 : 1;
1.213     dtucker   513:                        goto out;
                    514:                }
1.221   ! djm       515:                attributes++;
        !           516:                if (strcasecmp(attrib, "canonical") == 0) {
        !           517:                        r = !!post_canon;  /* force bitmask member to boolean */
        !           518:                        if (r == (negate ? 1 : 0))
        !           519:                                this_result = result = 0;
        !           520:                        debug3("%.200s line %d: %smatched '%s'",
        !           521:                            filename, linenum,
        !           522:                            this_result ? "" : "not ", oattrib);
        !           523:                        continue;
        !           524:                }
        !           525:                /* All other criteria require an argument */
1.206     djm       526:                if ((arg = strdelim(&cp)) == NULL || *arg == '\0') {
                    527:                        error("Missing Match criteria for %s", attrib);
1.211     djm       528:                        result = -1;
                    529:                        goto out;
1.206     djm       530:                }
                    531:                len = strlen(arg);
                    532:                if (strcasecmp(attrib, "host") == 0) {
1.221   ! djm       533:                        criteria = xstrdup(host);
        !           534:                        r = match_hostname(host, arg, len) == 1;
        !           535:                        if (r == (negate ? 1 : 0))
        !           536:                                this_result = result = 0;
1.206     djm       537:                } else if (strcasecmp(attrib, "originalhost") == 0) {
1.221   ! djm       538:                        criteria = xstrdup(original_host);
        !           539:                        r = match_hostname(original_host, arg, len) == 1;
        !           540:                        if (r == (negate ? 1 : 0))
        !           541:                                this_result = result = 0;
1.206     djm       542:                } else if (strcasecmp(attrib, "user") == 0) {
1.221   ! djm       543:                        criteria = xstrdup(ruser);
        !           544:                        r = match_pattern_list(ruser, arg, len, 0) == 1;
        !           545:                        if (r == (negate ? 1 : 0))
        !           546:                                this_result = result = 0;
1.206     djm       547:                } else if (strcasecmp(attrib, "localuser") == 0) {
1.221   ! djm       548:                        criteria = xstrdup(pw->pw_name);
        !           549:                        r = match_pattern_list(pw->pw_name, arg, len, 0) == 1;
        !           550:                        if (r == (negate ? 1 : 0))
        !           551:                                this_result = result = 0;
1.210     djm       552:                } else if (strcasecmp(attrib, "exec") == 0) {
1.206     djm       553:                        if (gethostname(thishost, sizeof(thishost)) == -1)
                    554:                                fatal("gethostname: %s", strerror(errno));
                    555:                        strlcpy(shorthost, thishost, sizeof(shorthost));
                    556:                        shorthost[strcspn(thishost, ".")] = '\0';
                    557:                        snprintf(portstr, sizeof(portstr), "%d", port);
                    558:
                    559:                        cmd = percent_expand(arg,
                    560:                            "L", shorthost,
                    561:                            "d", pw->pw_dir,
                    562:                            "h", host,
                    563:                            "l", thishost,
1.221   ! djm       564:                            "n", original_host,
1.206     djm       565:                            "p", portstr,
                    566:                            "r", ruser,
                    567:                            "u", pw->pw_name,
                    568:                            (char *)NULL);
1.217     djm       569:                        if (result != 1) {
                    570:                                /* skip execution if prior predicate failed */
1.221   ! djm       571:                                debug3("%.200s line %d: skipped exec "
        !           572:                                    "\"%.100s\"", filename, linenum, cmd);
        !           573:                                free(cmd);
        !           574:                                continue;
        !           575:                        }
        !           576:                        r = execute_in_shell(cmd);
        !           577:                        if (r == -1) {
        !           578:                                fatal("%.200s line %d: match exec "
        !           579:                                    "'%.100s' error", filename,
        !           580:                                    linenum, cmd);
1.217     djm       581:                        }
1.221   ! djm       582:                        criteria = xstrdup(cmd);
1.206     djm       583:                        free(cmd);
1.221   ! djm       584:                        /* Force exit status to boolean */
        !           585:                        r = r == 0;
        !           586:                        if (r == (negate ? 1 : 0))
        !           587:                                this_result = result = 0;
1.206     djm       588:                } else {
                    589:                        error("Unsupported Match attribute %s", attrib);
1.211     djm       590:                        result = -1;
                    591:                        goto out;
1.206     djm       592:                }
1.221   ! djm       593:                debug3("%.200s line %d: %smatched '%s \"%.100s\"' ",
        !           594:                    filename, linenum, this_result ? "": "not ",
        !           595:                    oattrib, criteria);
        !           596:                free(criteria);
1.213     dtucker   597:        }
                    598:        if (attributes == 0) {
                    599:                error("One or more attributes required for Match");
                    600:                result = -1;
                    601:                goto out;
1.206     djm       602:        }
1.221   ! djm       603:  out:
        !           604:        if (result != -1)
        !           605:                debug2("match %sfound", result ? "" : "not ");
1.206     djm       606:        *condition = cp;
1.211     djm       607:        free(host);
1.206     djm       608:        return result;
                    609: }
                    610:
1.208     djm       611: /* Check and prepare a domain name: removes trailing '.' and lowercases */
                    612: static void
                    613: valid_domain(char *name, const char *filename, int linenum)
                    614: {
                    615:        size_t i, l = strlen(name);
                    616:        u_char c, last = '\0';
                    617:
                    618:        if (l == 0)
                    619:                fatal("%s line %d: empty hostname suffix", filename, linenum);
                    620:        if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0]))
                    621:                fatal("%s line %d: hostname suffix \"%.100s\" "
                    622:                    "starts with invalid character", filename, linenum, name);
                    623:        for (i = 0; i < l; i++) {
                    624:                c = tolower((u_char)name[i]);
                    625:                name[i] = (char)c;
                    626:                if (last == '.' && c == '.')
                    627:                        fatal("%s line %d: hostname suffix \"%.100s\" contains "
                    628:                            "consecutive separators", filename, linenum, name);
                    629:                if (c != '.' && c != '-' && !isalnum(c) &&
                    630:                    c != '_') /* technically invalid, but common */
                    631:                        fatal("%s line %d: hostname suffix \"%.100s\" contains "
                    632:                            "invalid characters", filename, linenum, name);
                    633:                last = c;
                    634:        }
                    635:        if (name[l - 1] == '.')
                    636:                name[l - 1] = '\0';
                    637: }
                    638:
1.19      markus    639: /*
1.70      stevesk   640:  * Returns the number of the token pointed to by cp or oBadOption.
1.19      markus    641:  */
1.26      markus    642: static OpCodes
1.199     djm       643: parse_token(const char *cp, const char *filename, int linenum,
                    644:     const char *ignored_unknown)
1.1       deraadt   645: {
1.199     djm       646:        int i;
1.1       deraadt   647:
1.17      markus    648:        for (i = 0; keywords[i].name; i++)
1.199     djm       649:                if (strcmp(cp, keywords[i].name) == 0)
1.17      markus    650:                        return keywords[i].opcode;
1.199     djm       651:        if (ignored_unknown != NULL && match_pattern_list(cp, ignored_unknown,
                    652:            strlen(ignored_unknown), 1) == 1)
                    653:                return oIgnoredUnknownOption;
1.75      stevesk   654:        error("%s: line %d: Bad configuration option: %s",
                    655:            filename, linenum, cp);
1.17      markus    656:        return oBadOption;
1.1       deraadt   657: }
                    658:
1.207     djm       659: /* Multistate option parsing */
                    660: struct multistate {
                    661:        char *key;
                    662:        int value;
                    663: };
                    664: static const struct multistate multistate_flag[] = {
                    665:        { "true",                       1 },
                    666:        { "false",                      0 },
                    667:        { "yes",                        1 },
                    668:        { "no",                         0 },
                    669:        { NULL, -1 }
                    670: };
                    671: static const struct multistate multistate_yesnoask[] = {
                    672:        { "true",                       1 },
                    673:        { "false",                      0 },
                    674:        { "yes",                        1 },
                    675:        { "no",                         0 },
                    676:        { "ask",                        2 },
                    677:        { NULL, -1 }
                    678: };
                    679: static const struct multistate multistate_addressfamily[] = {
                    680:        { "inet",                       AF_INET },
                    681:        { "inet6",                      AF_INET6 },
                    682:        { "any",                        AF_UNSPEC },
                    683:        { NULL, -1 }
                    684: };
                    685: static const struct multistate multistate_controlmaster[] = {
                    686:        { "true",                       SSHCTL_MASTER_YES },
                    687:        { "yes",                        SSHCTL_MASTER_YES },
                    688:        { "false",                      SSHCTL_MASTER_NO },
                    689:        { "no",                         SSHCTL_MASTER_NO },
                    690:        { "auto",                       SSHCTL_MASTER_AUTO },
                    691:        { "ask",                        SSHCTL_MASTER_ASK },
                    692:        { "autoask",                    SSHCTL_MASTER_AUTO_ASK },
                    693:        { NULL, -1 }
                    694: };
                    695: static const struct multistate multistate_tunnel[] = {
                    696:        { "ethernet",                   SSH_TUNMODE_ETHERNET },
                    697:        { "point-to-point",             SSH_TUNMODE_POINTOPOINT },
                    698:        { "true",                       SSH_TUNMODE_DEFAULT },
                    699:        { "yes",                        SSH_TUNMODE_DEFAULT },
                    700:        { "false",                      SSH_TUNMODE_NO },
                    701:        { "no",                         SSH_TUNMODE_NO },
                    702:        { NULL, -1 }
                    703: };
                    704: static const struct multistate multistate_requesttty[] = {
                    705:        { "true",                       REQUEST_TTY_YES },
                    706:        { "yes",                        REQUEST_TTY_YES },
                    707:        { "false",                      REQUEST_TTY_NO },
                    708:        { "no",                         REQUEST_TTY_NO },
                    709:        { "force",                      REQUEST_TTY_FORCE },
                    710:        { "auto",                       REQUEST_TTY_AUTO },
                    711:        { NULL, -1 }
                    712: };
1.209     djm       713: static const struct multistate multistate_canonicalizehostname[] = {
1.208     djm       714:        { "true",                       SSH_CANONICALISE_YES },
                    715:        { "false",                      SSH_CANONICALISE_NO },
                    716:        { "yes",                        SSH_CANONICALISE_YES },
                    717:        { "no",                         SSH_CANONICALISE_NO },
                    718:        { "always",                     SSH_CANONICALISE_ALWAYS },
                    719:        { NULL, -1 }
                    720: };
1.207     djm       721:
1.19      markus    722: /*
                    723:  * Processes a single option line as used in the configuration files. This
                    724:  * only sets those values that have not already been set.
                    725:  */
1.102     markus    726: #define WHITESPACE " \t\r\n"
1.14      markus    727: int
1.206     djm       728: process_config_line(Options *options, struct passwd *pw, const char *host,
1.221   ! djm       729:     const char *original_host, char *line, const char *filename,
        !           730:     int linenum, int *activep, int flags)
1.1       deraadt   731: {
1.193     djm       732:        char *s, **charptr, *endofnumber, *keyword, *arg, *arg2;
                    733:        char **cpptr, fwdarg[256];
1.199     djm       734:        u_int i, *uintptr, max_entries = 0;
1.206     djm       735:        int negated, opcode, *intptr, value, value2, cmdline = 0;
1.164     dtucker   736:        LogLevel *log_level_ptr;
1.201     dtucker   737:        long long val64;
1.102     markus    738:        size_t len;
1.220     millert   739:        struct Forward fwd;
1.207     djm       740:        const struct multistate *multistate_ptr;
1.208     djm       741:        struct allowed_cname *cname;
1.106     djm       742:
1.206     djm       743:        if (activep == NULL) { /* We are processing a command line directive */
                    744:                cmdline = 1;
                    745:                activep = &cmdline;
                    746:        }
                    747:
1.106     djm       748:        /* Strip trailing whitespace */
1.139     deraadt   749:        for (len = strlen(line) - 1; len > 0; len--) {
1.106     djm       750:                if (strchr(WHITESPACE, line[len]) == NULL)
                    751:                        break;
                    752:                line[len] = '\0';
                    753:        }
1.1       deraadt   754:
1.42      provos    755:        s = line;
                    756:        /* Get the keyword. (Each line is supposed to begin with a keyword). */
1.149     djm       757:        if ((keyword = strdelim(&s)) == NULL)
                    758:                return 0;
1.42      provos    759:        /* Ignore leading whitespace. */
                    760:        if (*keyword == '\0')
1.43      markus    761:                keyword = strdelim(&s);
1.56      deraadt   762:        if (keyword == NULL || !*keyword || *keyword == '\n' || *keyword == '#')
1.17      markus    763:                return 0;
1.199     djm       764:        /* Match lowercase keyword */
1.207     djm       765:        lowercase(keyword);
1.17      markus    766:
1.199     djm       767:        opcode = parse_token(keyword, filename, linenum,
                    768:            options->ignored_unknown);
1.17      markus    769:
                    770:        switch (opcode) {
                    771:        case oBadOption:
1.19      markus    772:                /* don't panic, but count bad options */
                    773:                return -1;
1.17      markus    774:                /* NOTREACHED */
1.199     djm       775:        case oIgnoredUnknownOption:
                    776:                debug("%s line %d: Ignored unknown option \"%s\"",
                    777:                    filename, linenum, keyword);
                    778:                return 0;
1.111     djm       779:        case oConnectTimeout:
                    780:                intptr = &options->connection_timeout;
1.127     markus    781: parse_time:
1.111     djm       782:                arg = strdelim(&s);
                    783:                if (!arg || *arg == '\0')
                    784:                        fatal("%s line %d: missing time value.",
                    785:                            filename, linenum);
1.221   ! djm       786:                if (strcmp(arg, "none") == 0)
        !           787:                        value = -1;
        !           788:                else if ((value = convtime(arg)) == -1)
1.111     djm       789:                        fatal("%s line %d: invalid time value.",
                    790:                            filename, linenum);
1.160     dtucker   791:                if (*activep && *intptr == -1)
1.111     djm       792:                        *intptr = value;
                    793:                break;
                    794:
1.17      markus    795:        case oForwardAgent:
                    796:                intptr = &options->forward_agent;
1.207     djm       797:  parse_flag:
                    798:                multistate_ptr = multistate_flag;
                    799:  parse_multistate:
1.42      provos    800:                arg = strdelim(&s);
1.40      ho        801:                if (!arg || *arg == '\0')
1.207     djm       802:                        fatal("%s line %d: missing argument.",
                    803:                            filename, linenum);
                    804:                value = -1;
                    805:                for (i = 0; multistate_ptr[i].key != NULL; i++) {
                    806:                        if (strcasecmp(arg, multistate_ptr[i].key) == 0) {
                    807:                                value = multistate_ptr[i].value;
                    808:                                break;
                    809:                        }
                    810:                }
                    811:                if (value == -1)
                    812:                        fatal("%s line %d: unsupported option \"%s\".",
                    813:                            filename, linenum, arg);
1.17      markus    814:                if (*activep && *intptr == -1)
                    815:                        *intptr = value;
                    816:                break;
                    817:
                    818:        case oForwardX11:
                    819:                intptr = &options->forward_x11;
                    820:                goto parse_flag;
                    821:
1.123     markus    822:        case oForwardX11Trusted:
                    823:                intptr = &options->forward_x11_trusted;
                    824:                goto parse_flag;
1.221   ! djm       825:
1.186     djm       826:        case oForwardX11Timeout:
                    827:                intptr = &options->forward_x11_timeout;
                    828:                goto parse_time;
1.123     markus    829:
1.17      markus    830:        case oGatewayPorts:
1.220     millert   831:                intptr = &options->fwd_opts.gateway_ports;
1.17      markus    832:                goto parse_flag;
                    833:
1.153     markus    834:        case oExitOnForwardFailure:
                    835:                intptr = &options->exit_on_forward_failure;
                    836:                goto parse_flag;
                    837:
1.17      markus    838:        case oUsePrivilegedPort:
                    839:                intptr = &options->use_privileged_port;
                    840:                goto parse_flag;
                    841:
                    842:        case oPasswordAuthentication:
                    843:                intptr = &options->password_authentication;
                    844:                goto parse_flag;
                    845:
1.48      markus    846:        case oKbdInteractiveAuthentication:
                    847:                intptr = &options->kbd_interactive_authentication;
                    848:                goto parse_flag;
                    849:
                    850:        case oKbdInteractiveDevices:
                    851:                charptr = &options->kbd_interactive_devices;
                    852:                goto parse_string;
                    853:
1.50      markus    854:        case oPubkeyAuthentication:
                    855:                intptr = &options->pubkey_authentication;
1.30      markus    856:                goto parse_flag;
                    857:
1.17      markus    858:        case oRSAAuthentication:
                    859:                intptr = &options->rsa_authentication;
                    860:                goto parse_flag;
                    861:
                    862:        case oRhostsRSAAuthentication:
                    863:                intptr = &options->rhosts_rsa_authentication;
                    864:                goto parse_flag;
                    865:
1.72      markus    866:        case oHostbasedAuthentication:
                    867:                intptr = &options->hostbased_authentication;
                    868:                goto parse_flag;
                    869:
1.59      markus    870:        case oChallengeResponseAuthentication:
1.78      markus    871:                intptr = &options->challenge_response_authentication;
1.17      markus    872:                goto parse_flag;
1.108     jakob     873:
1.118     markus    874:        case oGssAuthentication:
                    875:                intptr = &options->gss_authentication;
                    876:                goto parse_flag;
                    877:
                    878:        case oGssDelegateCreds:
                    879:                intptr = &options->gss_deleg_creds;
                    880:                goto parse_flag;
                    881:
1.17      markus    882:        case oBatchMode:
                    883:                intptr = &options->batch_mode;
                    884:                goto parse_flag;
                    885:
                    886:        case oCheckHostIP:
                    887:                intptr = &options->check_host_ip;
1.167     grunk     888:                goto parse_flag;
1.17      markus    889:
1.107     jakob     890:        case oVerifyHostKeyDNS:
                    891:                intptr = &options->verify_host_key_dns;
1.207     djm       892:                multistate_ptr = multistate_yesnoask;
                    893:                goto parse_multistate;
1.107     jakob     894:
1.17      markus    895:        case oStrictHostKeyChecking:
                    896:                intptr = &options->strict_host_key_checking;
1.207     djm       897:                multistate_ptr = multistate_yesnoask;
                    898:                goto parse_multistate;
1.17      markus    899:
                    900:        case oCompression:
                    901:                intptr = &options->compression;
                    902:                goto parse_flag;
                    903:
1.126     markus    904:        case oTCPKeepAlive:
                    905:                intptr = &options->tcp_keep_alive;
1.17      markus    906:                goto parse_flag;
                    907:
1.91      markus    908:        case oNoHostAuthenticationForLocalhost:
                    909:                intptr = &options->no_host_authentication_for_localhost;
                    910:                goto parse_flag;
                    911:
1.17      markus    912:        case oNumberOfPasswordPrompts:
                    913:                intptr = &options->number_of_password_prompts;
                    914:                goto parse_int;
                    915:
                    916:        case oCompressionLevel:
                    917:                intptr = &options->compression_level;
                    918:                goto parse_int;
                    919:
1.105     markus    920:        case oRekeyLimit:
                    921:                arg = strdelim(&s);
                    922:                if (!arg || *arg == '\0')
1.198     dtucker   923:                        fatal("%.200s line %d: Missing argument.", filename,
                    924:                            linenum);
                    925:                if (strcmp(arg, "default") == 0) {
                    926:                        val64 = 0;
                    927:                } else {
1.200     dtucker   928:                        if (scan_scaled(arg, &val64) == -1)
                    929:                                fatal("%.200s line %d: Bad number '%s': %s",
                    930:                                    filename, linenum, arg, strerror(errno));
                    931:                        /* check for too-large or too-small limits */
                    932:                        if (val64 > UINT_MAX)
1.198     dtucker   933:                                fatal("%.200s line %d: RekeyLimit too large",
                    934:                                    filename, linenum);
                    935:                        if (val64 != 0 && val64 < 16)
                    936:                                fatal("%.200s line %d: RekeyLimit too small",
                    937:                                    filename, linenum);
1.105     markus    938:                }
1.165     djm       939:                if (*activep && options->rekey_limit == -1)
                    940:                        options->rekey_limit = (u_int32_t)val64;
1.198     dtucker   941:                if (s != NULL) { /* optional rekey interval present */
                    942:                        if (strcmp(s, "none") == 0) {
                    943:                                (void)strdelim(&s);     /* discard */
                    944:                                break;
                    945:                        }
                    946:                        intptr = &options->rekey_interval;
                    947:                        goto parse_time;
                    948:                }
1.105     markus    949:                break;
                    950:
1.17      markus    951:        case oIdentityFile:
1.42      provos    952:                arg = strdelim(&s);
1.40      ho        953:                if (!arg || *arg == '\0')
1.17      markus    954:                        fatal("%.200s line %d: Missing argument.", filename, linenum);
                    955:                if (*activep) {
1.50      markus    956:                        intptr = &options->num_identity_files;
1.27      markus    957:                        if (*intptr >= SSH_MAX_IDENTITY_FILES)
1.17      markus    958:                                fatal("%.200s line %d: Too many identity files specified (max %d).",
1.93      deraadt   959:                                    filename, linenum, SSH_MAX_IDENTITY_FILES);
1.221   ! djm       960:                        add_identity_file(options, NULL,
        !           961:                            arg, flags & SSHCONF_USERCONF);
1.17      markus    962:                }
                    963:                break;
                    964:
1.34      markus    965:        case oXAuthLocation:
                    966:                charptr=&options->xauth_location;
                    967:                goto parse_string;
                    968:
1.17      markus    969:        case oUser:
                    970:                charptr = &options->user;
                    971: parse_string:
1.42      provos    972:                arg = strdelim(&s);
1.40      ho        973:                if (!arg || *arg == '\0')
1.193     djm       974:                        fatal("%.200s line %d: Missing argument.",
                    975:                            filename, linenum);
1.17      markus    976:                if (*activep && *charptr == NULL)
1.38      provos    977:                        *charptr = xstrdup(arg);
1.17      markus    978:                break;
                    979:
                    980:        case oGlobalKnownHostsFile:
1.193     djm       981:                cpptr = (char **)&options->system_hostfiles;
                    982:                uintptr = &options->num_system_hostfiles;
                    983:                max_entries = SSH_MAX_HOSTS_FILES;
                    984: parse_char_array:
                    985:                if (*activep && *uintptr == 0) {
                    986:                        while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
                    987:                                if ((*uintptr) >= max_entries)
                    988:                                        fatal("%s line %d: "
                    989:                                            "too many authorized keys files.",
                    990:                                            filename, linenum);
                    991:                                cpptr[(*uintptr)++] = xstrdup(arg);
                    992:                        }
                    993:                }
                    994:                return 0;
1.17      markus    995:
                    996:        case oUserKnownHostsFile:
1.193     djm       997:                cpptr = (char **)&options->user_hostfiles;
                    998:                uintptr = &options->num_user_hostfiles;
                    999:                max_entries = SSH_MAX_HOSTS_FILES;
                   1000:                goto parse_char_array;
1.27      markus   1001:
1.17      markus   1002:        case oHostName:
                   1003:                charptr = &options->hostname;
                   1004:                goto parse_string;
                   1005:
1.52      markus   1006:        case oHostKeyAlias:
                   1007:                charptr = &options->host_key_alias;
                   1008:                goto parse_string;
                   1009:
1.67      markus   1010:        case oPreferredAuthentications:
                   1011:                charptr = &options->preferred_authentications;
                   1012:                goto parse_string;
                   1013:
1.77      markus   1014:        case oBindAddress:
                   1015:                charptr = &options->bind_address;
                   1016:                goto parse_string;
                   1017:
1.183     markus   1018:        case oPKCS11Provider:
                   1019:                charptr = &options->pkcs11_provider;
1.86      markus   1020:                goto parse_string;
1.85      jakob    1021:
1.17      markus   1022:        case oProxyCommand:
1.144     reyk     1023:                charptr = &options->proxy_command;
                   1024: parse_command:
1.113     markus   1025:                if (s == NULL)
                   1026:                        fatal("%.200s line %d: Missing argument.", filename, linenum);
1.102     markus   1027:                len = strspn(s, WHITESPACE "=");
1.17      markus   1028:                if (*activep && *charptr == NULL)
1.102     markus   1029:                        *charptr = xstrdup(s + len);
1.17      markus   1030:                return 0;
                   1031:
                   1032:        case oPort:
                   1033:                intptr = &options->port;
                   1034: parse_int:
1.42      provos   1035:                arg = strdelim(&s);
1.40      ho       1036:                if (!arg || *arg == '\0')
1.17      markus   1037:                        fatal("%.200s line %d: Missing argument.", filename, linenum);
1.38      provos   1038:                if (arg[0] < '0' || arg[0] > '9')
1.17      markus   1039:                        fatal("%.200s line %d: Bad number.", filename, linenum);
1.21      markus   1040:
                   1041:                /* Octal, decimal, or hex format? */
1.38      provos   1042:                value = strtol(arg, &endofnumber, 0);
                   1043:                if (arg == endofnumber)
1.21      markus   1044:                        fatal("%.200s line %d: Bad number.", filename, linenum);
1.17      markus   1045:                if (*activep && *intptr == -1)
                   1046:                        *intptr = value;
                   1047:                break;
                   1048:
                   1049:        case oConnectionAttempts:
                   1050:                intptr = &options->connection_attempts;
                   1051:                goto parse_int;
                   1052:
                   1053:        case oCipher:
                   1054:                intptr = &options->cipher;
1.42      provos   1055:                arg = strdelim(&s);
1.40      ho       1056:                if (!arg || *arg == '\0')
1.32      markus   1057:                        fatal("%.200s line %d: Missing argument.", filename, linenum);
1.38      provos   1058:                value = cipher_number(arg);
1.17      markus   1059:                if (value == -1)
                   1060:                        fatal("%.200s line %d: Bad cipher '%s'.",
1.93      deraadt  1061:                            filename, linenum, arg ? arg : "<NONE>");
1.17      markus   1062:                if (*activep && *intptr == -1)
                   1063:                        *intptr = value;
                   1064:                break;
                   1065:
1.25      markus   1066:        case oCiphers:
1.42      provos   1067:                arg = strdelim(&s);
1.40      ho       1068:                if (!arg || *arg == '\0')
1.32      markus   1069:                        fatal("%.200s line %d: Missing argument.", filename, linenum);
1.38      provos   1070:                if (!ciphers_valid(arg))
1.31      markus   1071:                        fatal("%.200s line %d: Bad SSH2 cipher spec '%s'.",
1.93      deraadt  1072:                            filename, linenum, arg ? arg : "<NONE>");
1.25      markus   1073:                if (*activep && options->ciphers == NULL)
1.38      provos   1074:                        options->ciphers = xstrdup(arg);
1.25      markus   1075:                break;
                   1076:
1.62      markus   1077:        case oMacs:
                   1078:                arg = strdelim(&s);
                   1079:                if (!arg || *arg == '\0')
                   1080:                        fatal("%.200s line %d: Missing argument.", filename, linenum);
                   1081:                if (!mac_valid(arg))
                   1082:                        fatal("%.200s line %d: Bad SSH2 Mac spec '%s'.",
1.93      deraadt  1083:                            filename, linenum, arg ? arg : "<NONE>");
1.62      markus   1084:                if (*activep && options->macs == NULL)
                   1085:                        options->macs = xstrdup(arg);
                   1086:                break;
                   1087:
1.189     djm      1088:        case oKexAlgorithms:
                   1089:                arg = strdelim(&s);
                   1090:                if (!arg || *arg == '\0')
                   1091:                        fatal("%.200s line %d: Missing argument.",
                   1092:                            filename, linenum);
                   1093:                if (!kex_names_valid(arg))
                   1094:                        fatal("%.200s line %d: Bad SSH2 KexAlgorithms '%s'.",
                   1095:                            filename, linenum, arg ? arg : "<NONE>");
                   1096:                if (*activep && options->kex_algorithms == NULL)
                   1097:                        options->kex_algorithms = xstrdup(arg);
                   1098:                break;
                   1099:
1.76      markus   1100:        case oHostKeyAlgorithms:
                   1101:                arg = strdelim(&s);
                   1102:                if (!arg || *arg == '\0')
                   1103:                        fatal("%.200s line %d: Missing argument.", filename, linenum);
                   1104:                if (!key_names_valid2(arg))
                   1105:                        fatal("%.200s line %d: Bad protocol 2 host key algorithms '%s'.",
1.93      deraadt  1106:                            filename, linenum, arg ? arg : "<NONE>");
1.76      markus   1107:                if (*activep && options->hostkeyalgorithms == NULL)
                   1108:                        options->hostkeyalgorithms = xstrdup(arg);
                   1109:                break;
                   1110:
1.25      markus   1111:        case oProtocol:
                   1112:                intptr = &options->protocol;
1.42      provos   1113:                arg = strdelim(&s);
1.40      ho       1114:                if (!arg || *arg == '\0')
1.32      markus   1115:                        fatal("%.200s line %d: Missing argument.", filename, linenum);
1.38      provos   1116:                value = proto_spec(arg);
1.25      markus   1117:                if (value == SSH_PROTO_UNKNOWN)
                   1118:                        fatal("%.200s line %d: Bad protocol spec '%s'.",
1.93      deraadt  1119:                            filename, linenum, arg ? arg : "<NONE>");
1.25      markus   1120:                if (*activep && *intptr == SSH_PROTO_UNKNOWN)
                   1121:                        *intptr = value;
                   1122:                break;
                   1123:
1.17      markus   1124:        case oLogLevel:
1.164     dtucker  1125:                log_level_ptr = &options->log_level;
1.42      provos   1126:                arg = strdelim(&s);
1.38      provos   1127:                value = log_level_number(arg);
1.95      markus   1128:                if (value == SYSLOG_LEVEL_NOT_SET)
1.64      millert  1129:                        fatal("%.200s line %d: unsupported log level '%s'",
1.93      deraadt  1130:                            filename, linenum, arg ? arg : "<NONE>");
1.164     dtucker  1131:                if (*activep && *log_level_ptr == SYSLOG_LEVEL_NOT_SET)
                   1132:                        *log_level_ptr = (LogLevel) value;
1.17      markus   1133:                break;
                   1134:
1.88      stevesk  1135:        case oLocalForward:
1.17      markus   1136:        case oRemoteForward:
1.168     stevesk  1137:        case oDynamicForward:
1.42      provos   1138:                arg = strdelim(&s);
1.135     djm      1139:                if (arg == NULL || *arg == '\0')
1.88      stevesk  1140:                        fatal("%.200s line %d: Missing port argument.",
                   1141:                            filename, linenum);
1.135     djm      1142:
1.168     stevesk  1143:                if (opcode == oLocalForward ||
                   1144:                    opcode == oRemoteForward) {
                   1145:                        arg2 = strdelim(&s);
                   1146:                        if (arg2 == NULL || *arg2 == '\0')
                   1147:                                fatal("%.200s line %d: Missing target argument.",
                   1148:                                    filename, linenum);
1.135     djm      1149:
1.168     stevesk  1150:                        /* construct a string for parse_forward */
                   1151:                        snprintf(fwdarg, sizeof(fwdarg), "%s:%s", arg, arg2);
                   1152:                } else if (opcode == oDynamicForward) {
                   1153:                        strlcpy(fwdarg, arg, sizeof(fwdarg));
                   1154:                }
                   1155:
                   1156:                if (parse_forward(&fwd, fwdarg,
1.176     djm      1157:                    opcode == oDynamicForward ? 1 : 0,
                   1158:                    opcode == oRemoteForward ? 1 : 0) == 0)
1.88      stevesk  1159:                        fatal("%.200s line %d: Bad forwarding specification.",
                   1160:                            filename, linenum);
1.135     djm      1161:
1.88      stevesk  1162:                if (*activep) {
1.168     stevesk  1163:                        if (opcode == oLocalForward ||
                   1164:                            opcode == oDynamicForward)
1.135     djm      1165:                                add_local_forward(options, &fwd);
1.88      stevesk  1166:                        else if (opcode == oRemoteForward)
1.135     djm      1167:                                add_remote_forward(options, &fwd);
1.88      stevesk  1168:                }
1.17      markus   1169:                break;
1.71      markus   1170:
1.90      stevesk  1171:        case oClearAllForwardings:
                   1172:                intptr = &options->clear_forwardings;
                   1173:                goto parse_flag;
                   1174:
1.17      markus   1175:        case oHost:
1.206     djm      1176:                if (cmdline)
                   1177:                        fatal("Host directive not supported as a command-line "
                   1178:                            "option");
1.17      markus   1179:                *activep = 0;
1.191     djm      1180:                arg2 = NULL;
                   1181:                while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
                   1182:                        negated = *arg == '!';
                   1183:                        if (negated)
                   1184:                                arg++;
1.38      provos   1185:                        if (match_pattern(host, arg)) {
1.191     djm      1186:                                if (negated) {
                   1187:                                        debug("%.200s line %d: Skipping Host "
                   1188:                                            "block because of negated match "
                   1189:                                            "for %.100s", filename, linenum,
                   1190:                                            arg);
                   1191:                                        *activep = 0;
                   1192:                                        break;
                   1193:                                }
                   1194:                                if (!*activep)
                   1195:                                        arg2 = arg; /* logged below */
1.17      markus   1196:                                *activep = 1;
                   1197:                        }
1.191     djm      1198:                }
                   1199:                if (*activep)
                   1200:                        debug("%.200s line %d: Applying options for %.100s",
                   1201:                            filename, linenum, arg2);
1.42      provos   1202:                /* Avoid garbage check below, as strdelim is done. */
1.17      markus   1203:                return 0;
                   1204:
1.206     djm      1205:        case oMatch:
                   1206:                if (cmdline)
                   1207:                        fatal("Host directive not supported as a command-line "
                   1208:                            "option");
1.221   ! djm      1209:                value = match_cfg_line(options, &s, pw, host, original_host,
        !          1210:                    flags & SSHCONF_POSTCANON, filename, linenum);
1.206     djm      1211:                if (value < 0)
                   1212:                        fatal("%.200s line %d: Bad Match condition", filename,
                   1213:                            linenum);
                   1214:                *activep = value;
                   1215:                break;
                   1216:
1.17      markus   1217:        case oEscapeChar:
                   1218:                intptr = &options->escape_char;
1.42      provos   1219:                arg = strdelim(&s);
1.40      ho       1220:                if (!arg || *arg == '\0')
1.17      markus   1221:                        fatal("%.200s line %d: Missing argument.", filename, linenum);
1.38      provos   1222:                if (arg[0] == '^' && arg[2] == 0 &&
1.51      markus   1223:                    (u_char) arg[1] >= 64 && (u_char) arg[1] < 128)
                   1224:                        value = (u_char) arg[1] & 31;
1.38      provos   1225:                else if (strlen(arg) == 1)
1.51      markus   1226:                        value = (u_char) arg[0];
1.38      provos   1227:                else if (strcmp(arg, "none") == 0)
1.79      stevesk  1228:                        value = SSH_ESCAPECHAR_NONE;
1.17      markus   1229:                else {
                   1230:                        fatal("%.200s line %d: Bad escape character.",
1.93      deraadt  1231:                            filename, linenum);
1.17      markus   1232:                        /* NOTREACHED */
                   1233:                        value = 0;      /* Avoid compiler warning. */
                   1234:                }
                   1235:                if (*activep && *intptr == -1)
                   1236:                        *intptr = value;
1.112     djm      1237:                break;
                   1238:
                   1239:        case oAddressFamily:
1.114     djm      1240:                intptr = &options->address_family;
1.207     djm      1241:                multistate_ptr = multistate_addressfamily;
                   1242:                goto parse_multistate;
1.17      markus   1243:
1.101     markus   1244:        case oEnableSSHKeysign:
                   1245:                intptr = &options->enable_ssh_keysign;
                   1246:                goto parse_flag;
                   1247:
1.128     markus   1248:        case oIdentitiesOnly:
                   1249:                intptr = &options->identities_only;
                   1250:                goto parse_flag;
                   1251:
1.127     markus   1252:        case oServerAliveInterval:
                   1253:                intptr = &options->server_alive_interval;
                   1254:                goto parse_time;
                   1255:
                   1256:        case oServerAliveCountMax:
                   1257:                intptr = &options->server_alive_count_max;
                   1258:                goto parse_int;
                   1259:
1.130     djm      1260:        case oSendEnv:
                   1261:                while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
                   1262:                        if (strchr(arg, '=') != NULL)
                   1263:                                fatal("%s line %d: Invalid environment name.",
                   1264:                                    filename, linenum);
1.137     djm      1265:                        if (!*activep)
                   1266:                                continue;
1.130     djm      1267:                        if (options->num_send_env >= MAX_SEND_ENV)
                   1268:                                fatal("%s line %d: too many send env.",
                   1269:                                    filename, linenum);
                   1270:                        options->send_env[options->num_send_env++] =
                   1271:                            xstrdup(arg);
                   1272:                }
                   1273:                break;
                   1274:
1.132     djm      1275:        case oControlPath:
                   1276:                charptr = &options->control_path;
                   1277:                goto parse_string;
                   1278:
                   1279:        case oControlMaster:
                   1280:                intptr = &options->control_master;
1.207     djm      1281:                multistate_ptr = multistate_controlmaster;
                   1282:                goto parse_multistate;
1.132     djm      1283:
1.187     djm      1284:        case oControlPersist:
                   1285:                /* no/false/yes/true, or a time spec */
                   1286:                intptr = &options->control_persist;
                   1287:                arg = strdelim(&s);
                   1288:                if (!arg || *arg == '\0')
                   1289:                        fatal("%.200s line %d: Missing ControlPersist"
                   1290:                            " argument.", filename, linenum);
                   1291:                value = 0;
                   1292:                value2 = 0;     /* timeout */
                   1293:                if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0)
                   1294:                        value = 0;
                   1295:                else if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0)
                   1296:                        value = 1;
                   1297:                else if ((value2 = convtime(arg)) >= 0)
                   1298:                        value = 1;
                   1299:                else
                   1300:                        fatal("%.200s line %d: Bad ControlPersist argument.",
                   1301:                            filename, linenum);
                   1302:                if (*activep && *intptr == -1) {
                   1303:                        *intptr = value;
                   1304:                        options->control_persist_timeout = value2;
                   1305:                }
                   1306:                break;
                   1307:
1.136     djm      1308:        case oHashKnownHosts:
                   1309:                intptr = &options->hash_known_hosts;
                   1310:                goto parse_flag;
                   1311:
1.144     reyk     1312:        case oTunnel:
                   1313:                intptr = &options->tun_open;
1.207     djm      1314:                multistate_ptr = multistate_tunnel;
                   1315:                goto parse_multistate;
1.144     reyk     1316:
                   1317:        case oTunnelDevice:
                   1318:                arg = strdelim(&s);
                   1319:                if (!arg || *arg == '\0')
                   1320:                        fatal("%.200s line %d: Missing argument.", filename, linenum);
                   1321:                value = a2tun(arg, &value2);
1.145     reyk     1322:                if (value == SSH_TUNID_ERR)
1.144     reyk     1323:                        fatal("%.200s line %d: Bad tun device.", filename, linenum);
                   1324:                if (*activep) {
                   1325:                        options->tun_local = value;
                   1326:                        options->tun_remote = value2;
                   1327:                }
                   1328:                break;
                   1329:
                   1330:        case oLocalCommand:
                   1331:                charptr = &options->local_command;
                   1332:                goto parse_command;
                   1333:
                   1334:        case oPermitLocalCommand:
                   1335:                intptr = &options->permit_local_command;
                   1336:                goto parse_flag;
                   1337:
1.167     grunk    1338:        case oVisualHostKey:
                   1339:                intptr = &options->visual_host_key;
                   1340:                goto parse_flag;
                   1341:
1.190     djm      1342:        case oIPQoS:
                   1343:                arg = strdelim(&s);
                   1344:                if ((value = parse_ipqos(arg)) == -1)
                   1345:                        fatal("%s line %d: Bad IPQoS value: %s",
                   1346:                            filename, linenum, arg);
                   1347:                arg = strdelim(&s);
                   1348:                if (arg == NULL)
                   1349:                        value2 = value;
                   1350:                else if ((value2 = parse_ipqos(arg)) == -1)
                   1351:                        fatal("%s line %d: Bad IPQoS value: %s",
                   1352:                            filename, linenum, arg);
                   1353:                if (*activep) {
                   1354:                        options->ip_qos_interactive = value;
                   1355:                        options->ip_qos_bulk = value2;
                   1356:                }
                   1357:                break;
                   1358:
1.177     andreas  1359:        case oUseRoaming:
                   1360:                intptr = &options->use_roaming;
                   1361:                goto parse_flag;
                   1362:
1.192     djm      1363:        case oRequestTTY:
                   1364:                intptr = &options->request_tty;
1.207     djm      1365:                multistate_ptr = multistate_requesttty;
                   1366:                goto parse_multistate;
1.192     djm      1367:
1.199     djm      1368:        case oIgnoreUnknown:
                   1369:                charptr = &options->ignored_unknown;
                   1370:                goto parse_string;
                   1371:
1.205     djm      1372:        case oProxyUseFdpass:
                   1373:                intptr = &options->proxy_use_fdpass;
                   1374:                goto parse_flag;
                   1375:
1.208     djm      1376:        case oCanonicalDomains:
                   1377:                value = options->num_canonical_domains != 0;
                   1378:                while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
                   1379:                        valid_domain(arg, filename, linenum);
                   1380:                        if (!*activep || value)
                   1381:                                continue;
                   1382:                        if (options->num_canonical_domains >= MAX_CANON_DOMAINS)
                   1383:                                fatal("%s line %d: too many hostname suffixes.",
                   1384:                                    filename, linenum);
                   1385:                        options->canonical_domains[
                   1386:                            options->num_canonical_domains++] = xstrdup(arg);
                   1387:                }
                   1388:                break;
                   1389:
1.209     djm      1390:        case oCanonicalizePermittedCNAMEs:
1.208     djm      1391:                value = options->num_permitted_cnames != 0;
                   1392:                while ((arg = strdelim(&s)) != NULL && *arg != '\0') {
                   1393:                        /* Either '*' for everything or 'list:list' */
                   1394:                        if (strcmp(arg, "*") == 0)
                   1395:                                arg2 = arg;
                   1396:                        else {
                   1397:                                lowercase(arg);
                   1398:                                if ((arg2 = strchr(arg, ':')) == NULL ||
                   1399:                                    arg2[1] == '\0') {
                   1400:                                        fatal("%s line %d: "
                   1401:                                            "Invalid permitted CNAME \"%s\"",
                   1402:                                            filename, linenum, arg);
                   1403:                                }
                   1404:                                *arg2 = '\0';
                   1405:                                arg2++;
                   1406:                        }
                   1407:                        if (!*activep || value)
                   1408:                                continue;
                   1409:                        if (options->num_permitted_cnames >= MAX_CANON_DOMAINS)
                   1410:                                fatal("%s line %d: too many permitted CNAMEs.",
                   1411:                                    filename, linenum);
                   1412:                        cname = options->permitted_cnames +
                   1413:                            options->num_permitted_cnames++;
                   1414:                        cname->source_list = xstrdup(arg);
                   1415:                        cname->target_list = xstrdup(arg2);
                   1416:                }
                   1417:                break;
                   1418:
1.209     djm      1419:        case oCanonicalizeHostname:
                   1420:                intptr = &options->canonicalize_hostname;
                   1421:                multistate_ptr = multistate_canonicalizehostname;
1.208     djm      1422:                goto parse_multistate;
                   1423:
1.209     djm      1424:        case oCanonicalizeMaxDots:
                   1425:                intptr = &options->canonicalize_max_dots;
1.208     djm      1426:                goto parse_int;
                   1427:
1.209     djm      1428:        case oCanonicalizeFallbackLocal:
                   1429:                intptr = &options->canonicalize_fallback_local;
1.208     djm      1430:                goto parse_flag;
                   1431:
1.220     millert  1432:        case oStreamLocalBindMask:
                   1433:                arg = strdelim(&s);
                   1434:                if (!arg || *arg == '\0')
                   1435:                        fatal("%.200s line %d: Missing StreamLocalBindMask argument.", filename, linenum);
                   1436:                /* Parse mode in octal format */
                   1437:                value = strtol(arg, &endofnumber, 8);
                   1438:                if (arg == endofnumber || value < 0 || value > 0777)
                   1439:                        fatal("%.200s line %d: Bad mask.", filename, linenum);
                   1440:                options->fwd_opts.streamlocal_bind_mask = (mode_t)value;
                   1441:                break;
                   1442:
                   1443:        case oStreamLocalBindUnlink:
                   1444:                intptr = &options->fwd_opts.streamlocal_bind_unlink;
                   1445:                goto parse_flag;
                   1446:
1.96      markus   1447:        case oDeprecated:
1.98      markus   1448:                debug("%s line %d: Deprecated option \"%s\"",
1.96      markus   1449:                    filename, linenum, keyword);
1.98      markus   1450:                return 0;
1.96      markus   1451:
1.110     jakob    1452:        case oUnsupported:
                   1453:                error("%s line %d: Unsupported option \"%s\"",
                   1454:                    filename, linenum, keyword);
                   1455:                return 0;
                   1456:
1.17      markus   1457:        default:
1.221   ! djm      1458:                fatal("%s: Unimplemented opcode %d", __func__, opcode);
1.17      markus   1459:        }
                   1460:
                   1461:        /* Check that there is no garbage at end of line. */
1.57      djm      1462:        if ((arg = strdelim(&s)) != NULL && *arg != '\0') {
1.39      ho       1463:                fatal("%.200s line %d: garbage at end of line; \"%.200s\".",
1.142     djm      1464:                    filename, linenum, arg);
1.39      ho       1465:        }
1.17      markus   1466:        return 0;
1.1       deraadt  1467: }
                   1468:
                   1469:
1.19      markus   1470: /*
                   1471:  * Reads the config file and modifies the options accordingly.  Options
                   1472:  * should already be initialized before this call.  This never returns if
1.89      stevesk  1473:  * there is an error.  If the file does not exist, this returns 0.
1.19      markus   1474:  */
1.1       deraadt  1475:
1.89      stevesk  1476: int
1.206     djm      1477: read_config_file(const char *filename, struct passwd *pw, const char *host,
1.221   ! djm      1478:     const char *original_host, Options *options, int flags)
1.1       deraadt  1479: {
1.17      markus   1480:        FILE *f;
                   1481:        char line[1024];
                   1482:        int active, linenum;
                   1483:        int bad_options = 0;
                   1484:
1.129     djm      1485:        if ((f = fopen(filename, "r")) == NULL)
1.89      stevesk  1486:                return 0;
1.129     djm      1487:
1.196     dtucker  1488:        if (flags & SSHCONF_CHECKPERM) {
1.129     djm      1489:                struct stat sb;
1.134     deraadt  1490:
1.131     dtucker  1491:                if (fstat(fileno(f), &sb) == -1)
1.129     djm      1492:                        fatal("fstat %s: %s", filename, strerror(errno));
                   1493:                if (((sb.st_uid != 0 && sb.st_uid != getuid()) ||
1.131     dtucker  1494:                    (sb.st_mode & 022) != 0))
1.129     djm      1495:                        fatal("Bad owner or permissions on %s", filename);
                   1496:        }
1.17      markus   1497:
                   1498:        debug("Reading configuration data %.200s", filename);
                   1499:
1.19      markus   1500:        /*
                   1501:         * Mark that we are now processing the options.  This flag is turned
                   1502:         * on/off by Host specifications.
                   1503:         */
1.17      markus   1504:        active = 1;
                   1505:        linenum = 0;
                   1506:        while (fgets(line, sizeof(line), f)) {
                   1507:                /* Update line number counter. */
                   1508:                linenum++;
1.221   ! djm      1509:                if (process_config_line(options, pw, host, original_host,
        !          1510:                    line, filename, linenum, &active, flags) != 0)
1.17      markus   1511:                        bad_options++;
                   1512:        }
                   1513:        fclose(f);
                   1514:        if (bad_options > 0)
1.64      millert  1515:                fatal("%s: terminating, %d bad configuration options",
1.93      deraadt  1516:                    filename, bad_options);
1.89      stevesk  1517:        return 1;
1.1       deraadt  1518: }
                   1519:
1.218     djm      1520: /* Returns 1 if a string option is unset or set to "none" or 0 otherwise. */
                   1521: int
                   1522: option_clear_or_none(const char *o)
                   1523: {
                   1524:        return o == NULL || strcasecmp(o, "none") == 0;
                   1525: }
                   1526:
1.19      markus   1527: /*
                   1528:  * Initializes options to special values that indicate that they have not yet
                   1529:  * been set.  Read_config_file will only set options with this value. Options
                   1530:  * are processed in the following order: command line, user config file,
                   1531:  * system config file.  Last, fill_default_options is called.
                   1532:  */
1.1       deraadt  1533:
1.26      markus   1534: void
1.17      markus   1535: initialize_options(Options * options)
1.1       deraadt  1536: {
1.17      markus   1537:        memset(options, 'X', sizeof(*options));
                   1538:        options->forward_agent = -1;
                   1539:        options->forward_x11 = -1;
1.123     markus   1540:        options->forward_x11_trusted = -1;
1.186     djm      1541:        options->forward_x11_timeout = -1;
1.153     markus   1542:        options->exit_on_forward_failure = -1;
1.34      markus   1543:        options->xauth_location = NULL;
1.220     millert  1544:        options->fwd_opts.gateway_ports = -1;
                   1545:        options->fwd_opts.streamlocal_bind_mask = (mode_t)-1;
                   1546:        options->fwd_opts.streamlocal_bind_unlink = -1;
1.17      markus   1547:        options->use_privileged_port = -1;
                   1548:        options->rsa_authentication = -1;
1.50      markus   1549:        options->pubkey_authentication = -1;
1.78      markus   1550:        options->challenge_response_authentication = -1;
1.118     markus   1551:        options->gss_authentication = -1;
                   1552:        options->gss_deleg_creds = -1;
1.17      markus   1553:        options->password_authentication = -1;
1.48      markus   1554:        options->kbd_interactive_authentication = -1;
                   1555:        options->kbd_interactive_devices = NULL;
1.17      markus   1556:        options->rhosts_rsa_authentication = -1;
1.72      markus   1557:        options->hostbased_authentication = -1;
1.17      markus   1558:        options->batch_mode = -1;
                   1559:        options->check_host_ip = -1;
                   1560:        options->strict_host_key_checking = -1;
                   1561:        options->compression = -1;
1.126     markus   1562:        options->tcp_keep_alive = -1;
1.17      markus   1563:        options->compression_level = -1;
                   1564:        options->port = -1;
1.114     djm      1565:        options->address_family = -1;
1.17      markus   1566:        options->connection_attempts = -1;
1.111     djm      1567:        options->connection_timeout = -1;
1.17      markus   1568:        options->number_of_password_prompts = -1;
                   1569:        options->cipher = -1;
1.25      markus   1570:        options->ciphers = NULL;
1.62      markus   1571:        options->macs = NULL;
1.189     djm      1572:        options->kex_algorithms = NULL;
1.76      markus   1573:        options->hostkeyalgorithms = NULL;
1.25      markus   1574:        options->protocol = SSH_PROTO_UNKNOWN;
1.17      markus   1575:        options->num_identity_files = 0;
                   1576:        options->hostname = NULL;
1.52      markus   1577:        options->host_key_alias = NULL;
1.17      markus   1578:        options->proxy_command = NULL;
                   1579:        options->user = NULL;
                   1580:        options->escape_char = -1;
1.193     djm      1581:        options->num_system_hostfiles = 0;
                   1582:        options->num_user_hostfiles = 0;
1.185     djm      1583:        options->local_forwards = NULL;
1.17      markus   1584:        options->num_local_forwards = 0;
1.185     djm      1585:        options->remote_forwards = NULL;
1.17      markus   1586:        options->num_remote_forwards = 0;
1.90      stevesk  1587:        options->clear_forwardings = -1;
1.95      markus   1588:        options->log_level = SYSLOG_LEVEL_NOT_SET;
1.67      markus   1589:        options->preferred_authentications = NULL;
1.77      markus   1590:        options->bind_address = NULL;
1.183     markus   1591:        options->pkcs11_provider = NULL;
1.101     markus   1592:        options->enable_ssh_keysign = - 1;
1.91      markus   1593:        options->no_host_authentication_for_localhost = - 1;
1.128     markus   1594:        options->identities_only = - 1;
1.105     markus   1595:        options->rekey_limit = - 1;
1.198     dtucker  1596:        options->rekey_interval = -1;
1.107     jakob    1597:        options->verify_host_key_dns = -1;
1.127     markus   1598:        options->server_alive_interval = -1;
                   1599:        options->server_alive_count_max = -1;
1.130     djm      1600:        options->num_send_env = 0;
1.132     djm      1601:        options->control_path = NULL;
                   1602:        options->control_master = -1;
1.187     djm      1603:        options->control_persist = -1;
                   1604:        options->control_persist_timeout = 0;
1.136     djm      1605:        options->hash_known_hosts = -1;
1.144     reyk     1606:        options->tun_open = -1;
                   1607:        options->tun_local = -1;
                   1608:        options->tun_remote = -1;
                   1609:        options->local_command = NULL;
                   1610:        options->permit_local_command = -1;
1.177     andreas  1611:        options->use_roaming = -1;
1.167     grunk    1612:        options->visual_host_key = -1;
1.190     djm      1613:        options->ip_qos_interactive = -1;
                   1614:        options->ip_qos_bulk = -1;
1.192     djm      1615:        options->request_tty = -1;
1.205     djm      1616:        options->proxy_use_fdpass = -1;
1.199     djm      1617:        options->ignored_unknown = NULL;
1.208     djm      1618:        options->num_canonical_domains = 0;
                   1619:        options->num_permitted_cnames = 0;
1.209     djm      1620:        options->canonicalize_max_dots = -1;
                   1621:        options->canonicalize_fallback_local = -1;
                   1622:        options->canonicalize_hostname = -1;
1.1       deraadt  1623: }
                   1624:
1.19      markus   1625: /*
1.218     djm      1626:  * A petite version of fill_default_options() that just fills the options
                   1627:  * needed for hostname canonicalization to proceed.
                   1628:  */
                   1629: void
                   1630: fill_default_options_for_canonicalization(Options *options)
                   1631: {
                   1632:        if (options->canonicalize_max_dots == -1)
                   1633:                options->canonicalize_max_dots = 1;
                   1634:        if (options->canonicalize_fallback_local == -1)
                   1635:                options->canonicalize_fallback_local = 1;
                   1636:        if (options->canonicalize_hostname == -1)
                   1637:                options->canonicalize_hostname = SSH_CANONICALISE_NO;
                   1638: }
                   1639:
                   1640: /*
1.19      markus   1641:  * Called after processing other sources of option data, this fills those
                   1642:  * options for which no value has been specified with their default values.
                   1643:  */
1.26      markus   1644: void
1.17      markus   1645: fill_default_options(Options * options)
1.1       deraadt  1646: {
1.17      markus   1647:        if (options->forward_agent == -1)
1.33      markus   1648:                options->forward_agent = 0;
1.17      markus   1649:        if (options->forward_x11 == -1)
1.23      markus   1650:                options->forward_x11 = 0;
1.123     markus   1651:        if (options->forward_x11_trusted == -1)
                   1652:                options->forward_x11_trusted = 0;
1.186     djm      1653:        if (options->forward_x11_timeout == -1)
                   1654:                options->forward_x11_timeout = 1200;
1.153     markus   1655:        if (options->exit_on_forward_failure == -1)
                   1656:                options->exit_on_forward_failure = 0;
1.34      markus   1657:        if (options->xauth_location == NULL)
1.80      markus   1658:                options->xauth_location = _PATH_XAUTH;
1.220     millert  1659:        if (options->fwd_opts.gateway_ports == -1)
                   1660:                options->fwd_opts.gateway_ports = 0;
                   1661:        if (options->fwd_opts.streamlocal_bind_mask == (mode_t)-1)
                   1662:                options->fwd_opts.streamlocal_bind_mask = 0177;
                   1663:        if (options->fwd_opts.streamlocal_bind_unlink == -1)
                   1664:                options->fwd_opts.streamlocal_bind_unlink = 0;
1.17      markus   1665:        if (options->use_privileged_port == -1)
1.65      markus   1666:                options->use_privileged_port = 0;
1.17      markus   1667:        if (options->rsa_authentication == -1)
                   1668:                options->rsa_authentication = 1;
1.50      markus   1669:        if (options->pubkey_authentication == -1)
                   1670:                options->pubkey_authentication = 1;
1.78      markus   1671:        if (options->challenge_response_authentication == -1)
1.83      markus   1672:                options->challenge_response_authentication = 1;
1.118     markus   1673:        if (options->gss_authentication == -1)
1.122     markus   1674:                options->gss_authentication = 0;
1.118     markus   1675:        if (options->gss_deleg_creds == -1)
                   1676:                options->gss_deleg_creds = 0;
1.17      markus   1677:        if (options->password_authentication == -1)
                   1678:                options->password_authentication = 1;
1.48      markus   1679:        if (options->kbd_interactive_authentication == -1)
1.59      markus   1680:                options->kbd_interactive_authentication = 1;
1.17      markus   1681:        if (options->rhosts_rsa_authentication == -1)
1.99      stevesk  1682:                options->rhosts_rsa_authentication = 0;
1.72      markus   1683:        if (options->hostbased_authentication == -1)
                   1684:                options->hostbased_authentication = 0;
1.17      markus   1685:        if (options->batch_mode == -1)
                   1686:                options->batch_mode = 0;
                   1687:        if (options->check_host_ip == -1)
                   1688:                options->check_host_ip = 1;
                   1689:        if (options->strict_host_key_checking == -1)
                   1690:                options->strict_host_key_checking = 2;  /* 2 is default */
                   1691:        if (options->compression == -1)
                   1692:                options->compression = 0;
1.126     markus   1693:        if (options->tcp_keep_alive == -1)
                   1694:                options->tcp_keep_alive = 1;
1.17      markus   1695:        if (options->compression_level == -1)
                   1696:                options->compression_level = 6;
                   1697:        if (options->port == -1)
                   1698:                options->port = 0;      /* Filled in ssh_connect. */
1.114     djm      1699:        if (options->address_family == -1)
                   1700:                options->address_family = AF_UNSPEC;
1.17      markus   1701:        if (options->connection_attempts == -1)
1.84      markus   1702:                options->connection_attempts = 1;
1.17      markus   1703:        if (options->number_of_password_prompts == -1)
                   1704:                options->number_of_password_prompts = 3;
                   1705:        /* Selected in ssh_login(). */
                   1706:        if (options->cipher == -1)
                   1707:                options->cipher = SSH_CIPHER_NOT_SET;
1.31      markus   1708:        /* options->ciphers, default set in myproposals.h */
1.62      markus   1709:        /* options->macs, default set in myproposals.h */
1.189     djm      1710:        /* options->kex_algorithms, default set in myproposals.h */
1.76      markus   1711:        /* options->hostkeyalgorithms, default set in myproposals.h */
1.25      markus   1712:        if (options->protocol == SSH_PROTO_UNKNOWN)
1.178     markus   1713:                options->protocol = SSH_PROTO_2;
1.17      markus   1714:        if (options->num_identity_files == 0) {
1.50      markus   1715:                if (options->protocol & SSH_PROTO_1) {
1.195     dtucker  1716:                        add_identity_file(options, "~/",
                   1717:                            _PATH_SSH_CLIENT_IDENTITY, 0);
1.50      markus   1718:                }
                   1719:                if (options->protocol & SSH_PROTO_2) {
1.195     dtucker  1720:                        add_identity_file(options, "~/",
                   1721:                            _PATH_SSH_CLIENT_ID_RSA, 0);
                   1722:                        add_identity_file(options, "~/",
                   1723:                            _PATH_SSH_CLIENT_ID_DSA, 0);
                   1724:                        add_identity_file(options, "~/",
                   1725:                            _PATH_SSH_CLIENT_ID_ECDSA, 0);
1.215     markus   1726:                        add_identity_file(options, "~/",
                   1727:                            _PATH_SSH_CLIENT_ID_ED25519, 0);
1.50      markus   1728:                }
1.27      markus   1729:        }
1.17      markus   1730:        if (options->escape_char == -1)
                   1731:                options->escape_char = '~';
1.193     djm      1732:        if (options->num_system_hostfiles == 0) {
                   1733:                options->system_hostfiles[options->num_system_hostfiles++] =
                   1734:                    xstrdup(_PATH_SSH_SYSTEM_HOSTFILE);
                   1735:                options->system_hostfiles[options->num_system_hostfiles++] =
                   1736:                    xstrdup(_PATH_SSH_SYSTEM_HOSTFILE2);
                   1737:        }
                   1738:        if (options->num_user_hostfiles == 0) {
                   1739:                options->user_hostfiles[options->num_user_hostfiles++] =
                   1740:                    xstrdup(_PATH_SSH_USER_HOSTFILE);
                   1741:                options->user_hostfiles[options->num_user_hostfiles++] =
                   1742:                    xstrdup(_PATH_SSH_USER_HOSTFILE2);
                   1743:        }
1.95      markus   1744:        if (options->log_level == SYSLOG_LEVEL_NOT_SET)
1.54      markus   1745:                options->log_level = SYSLOG_LEVEL_INFO;
1.90      stevesk  1746:        if (options->clear_forwardings == 1)
                   1747:                clear_forwardings(options);
1.91      markus   1748:        if (options->no_host_authentication_for_localhost == - 1)
                   1749:                options->no_host_authentication_for_localhost = 0;
1.128     markus   1750:        if (options->identities_only == -1)
                   1751:                options->identities_only = 0;
1.101     markus   1752:        if (options->enable_ssh_keysign == -1)
                   1753:                options->enable_ssh_keysign = 0;
1.105     markus   1754:        if (options->rekey_limit == -1)
                   1755:                options->rekey_limit = 0;
1.198     dtucker  1756:        if (options->rekey_interval == -1)
                   1757:                options->rekey_interval = 0;
1.107     jakob    1758:        if (options->verify_host_key_dns == -1)
                   1759:                options->verify_host_key_dns = 0;
1.127     markus   1760:        if (options->server_alive_interval == -1)
                   1761:                options->server_alive_interval = 0;
                   1762:        if (options->server_alive_count_max == -1)
                   1763:                options->server_alive_count_max = 3;
1.132     djm      1764:        if (options->control_master == -1)
                   1765:                options->control_master = 0;
1.187     djm      1766:        if (options->control_persist == -1) {
                   1767:                options->control_persist = 0;
                   1768:                options->control_persist_timeout = 0;
                   1769:        }
1.136     djm      1770:        if (options->hash_known_hosts == -1)
                   1771:                options->hash_known_hosts = 0;
1.144     reyk     1772:        if (options->tun_open == -1)
1.145     reyk     1773:                options->tun_open = SSH_TUNMODE_NO;
                   1774:        if (options->tun_local == -1)
                   1775:                options->tun_local = SSH_TUNID_ANY;
                   1776:        if (options->tun_remote == -1)
                   1777:                options->tun_remote = SSH_TUNID_ANY;
1.144     reyk     1778:        if (options->permit_local_command == -1)
                   1779:                options->permit_local_command = 0;
1.177     andreas  1780:        if (options->use_roaming == -1)
                   1781:                options->use_roaming = 1;
1.167     grunk    1782:        if (options->visual_host_key == -1)
                   1783:                options->visual_host_key = 0;
1.190     djm      1784:        if (options->ip_qos_interactive == -1)
                   1785:                options->ip_qos_interactive = IPTOS_LOWDELAY;
                   1786:        if (options->ip_qos_bulk == -1)
                   1787:                options->ip_qos_bulk = IPTOS_THROUGHPUT;
1.192     djm      1788:        if (options->request_tty == -1)
                   1789:                options->request_tty = REQUEST_TTY_AUTO;
1.205     djm      1790:        if (options->proxy_use_fdpass == -1)
                   1791:                options->proxy_use_fdpass = 0;
1.209     djm      1792:        if (options->canonicalize_max_dots == -1)
                   1793:                options->canonicalize_max_dots = 1;
                   1794:        if (options->canonicalize_fallback_local == -1)
                   1795:                options->canonicalize_fallback_local = 1;
                   1796:        if (options->canonicalize_hostname == -1)
                   1797:                options->canonicalize_hostname = SSH_CANONICALISE_NO;
1.207     djm      1798: #define CLEAR_ON_NONE(v) \
                   1799:        do { \
1.218     djm      1800:                if (option_clear_or_none(v)) { \
1.207     djm      1801:                        free(v); \
                   1802:                        v = NULL; \
                   1803:                } \
                   1804:        } while(0)
                   1805:        CLEAR_ON_NONE(options->local_command);
                   1806:        CLEAR_ON_NONE(options->proxy_command);
                   1807:        CLEAR_ON_NONE(options->control_path);
1.17      markus   1808:        /* options->user will be set in the main program if appropriate */
                   1809:        /* options->hostname will be set in the main program if appropriate */
1.52      markus   1810:        /* options->host_key_alias should not be set by default */
1.67      markus   1811:        /* options->preferred_authentications will be set in ssh */
1.135     djm      1812: }
                   1813:
1.220     millert  1814: struct fwdarg {
                   1815:        char *arg;
                   1816:        int ispath;
                   1817: };
                   1818:
                   1819: /*
                   1820:  * parse_fwd_field
                   1821:  * parses the next field in a port forwarding specification.
                   1822:  * sets fwd to the parsed field and advances p past the colon
                   1823:  * or sets it to NULL at end of string.
                   1824:  * returns 0 on success, else non-zero.
                   1825:  */
                   1826: static int
                   1827: parse_fwd_field(char **p, struct fwdarg *fwd)
                   1828: {
                   1829:        char *ep, *cp = *p;
                   1830:        int ispath = 0;
                   1831:
                   1832:        if (*cp == '\0') {
                   1833:                *p = NULL;
                   1834:                return -1;      /* end of string */
                   1835:        }
                   1836:
                   1837:        /*
                   1838:         * A field escaped with square brackets is used literally.
                   1839:         * XXX - allow ']' to be escaped via backslash?
                   1840:         */
                   1841:        if (*cp == '[') {
                   1842:                /* find matching ']' */
                   1843:                for (ep = cp + 1; *ep != ']' && *ep != '\0'; ep++) {
                   1844:                        if (*ep == '/')
                   1845:                                ispath = 1;
                   1846:                }
                   1847:                /* no matching ']' or not at end of field. */
                   1848:                if (ep[0] != ']' || (ep[1] != ':' && ep[1] != '\0'))
                   1849:                        return -1;
                   1850:                /* NUL terminate the field and advance p past the colon */
                   1851:                *ep++ = '\0';
                   1852:                if (*ep != '\0')
                   1853:                        *ep++ = '\0';
                   1854:                fwd->arg = cp + 1;
                   1855:                fwd->ispath = ispath;
                   1856:                *p = ep;
                   1857:                return 0;
                   1858:        }
                   1859:
                   1860:        for (cp = *p; *cp != '\0'; cp++) {
                   1861:                switch (*cp) {
                   1862:                case '\\':
                   1863:                        memmove(cp, cp + 1, strlen(cp + 1) + 1);
                   1864:                        cp++;
                   1865:                        break;
                   1866:                case '/':
                   1867:                        ispath = 1;
                   1868:                        break;
                   1869:                case ':':
                   1870:                        *cp++ = '\0';
                   1871:                        goto done;
                   1872:                }
                   1873:        }
                   1874: done:
                   1875:        fwd->arg = *p;
                   1876:        fwd->ispath = ispath;
                   1877:        *p = cp;
                   1878:        return 0;
                   1879: }
                   1880:
1.135     djm      1881: /*
                   1882:  * parse_forward
                   1883:  * parses a string containing a port forwarding specification of the form:
1.168     stevesk  1884:  *   dynamicfwd == 0
1.220     millert  1885:  *     [listenhost:]listenport|listenpath:connecthost:connectport|connectpath
                   1886:  *     listenpath:connectpath
1.168     stevesk  1887:  *   dynamicfwd == 1
                   1888:  *     [listenhost:]listenport
1.135     djm      1889:  * returns number of arguments parsed or zero on error
                   1890:  */
                   1891: int
1.220     millert  1892: parse_forward(struct Forward *fwd, const char *fwdspec, int dynamicfwd, int remotefwd)
1.135     djm      1893: {
1.220     millert  1894:        struct fwdarg fwdargs[4];
                   1895:        char *p, *cp;
1.135     djm      1896:        int i;
                   1897:
1.220     millert  1898:        memset(fwd, 0, sizeof(*fwd));
                   1899:        memset(fwdargs, 0, sizeof(fwdargs));
1.135     djm      1900:
                   1901:        cp = p = xstrdup(fwdspec);
                   1902:
                   1903:        /* skip leading spaces */
1.214     deraadt  1904:        while (isspace((u_char)*cp))
1.135     djm      1905:                cp++;
                   1906:
1.220     millert  1907:        for (i = 0; i < 4; ++i) {
                   1908:                if (parse_fwd_field(&cp, &fwdargs[i]) != 0)
1.135     djm      1909:                        break;
1.220     millert  1910:        }
1.135     djm      1911:
1.170     stevesk  1912:        /* Check for trailing garbage */
1.220     millert  1913:        if (cp != NULL && *cp != '\0') {
1.135     djm      1914:                i = 0;  /* failure */
1.220     millert  1915:        }
1.135     djm      1916:
                   1917:        switch (i) {
1.168     stevesk  1918:        case 1:
1.220     millert  1919:                if (fwdargs[0].ispath) {
                   1920:                        fwd->listen_path = xstrdup(fwdargs[0].arg);
                   1921:                        fwd->listen_port = PORT_STREAMLOCAL;
                   1922:                } else {
                   1923:                        fwd->listen_host = NULL;
                   1924:                        fwd->listen_port = a2port(fwdargs[0].arg);
                   1925:                }
1.168     stevesk  1926:                fwd->connect_host = xstrdup("socks");
                   1927:                break;
                   1928:
                   1929:        case 2:
1.220     millert  1930:                if (fwdargs[0].ispath && fwdargs[1].ispath) {
                   1931:                        fwd->listen_path = xstrdup(fwdargs[0].arg);
                   1932:                        fwd->listen_port = PORT_STREAMLOCAL;
                   1933:                        fwd->connect_path = xstrdup(fwdargs[1].arg);
                   1934:                        fwd->connect_port = PORT_STREAMLOCAL;
                   1935:                } else if (fwdargs[1].ispath) {
                   1936:                        fwd->listen_host = NULL;
                   1937:                        fwd->listen_port = a2port(fwdargs[0].arg);
                   1938:                        fwd->connect_path = xstrdup(fwdargs[1].arg);
                   1939:                        fwd->connect_port = PORT_STREAMLOCAL;
                   1940:                } else {
                   1941:                        fwd->listen_host = xstrdup(fwdargs[0].arg);
                   1942:                        fwd->listen_port = a2port(fwdargs[1].arg);
                   1943:                        fwd->connect_host = xstrdup("socks");
                   1944:                }
1.168     stevesk  1945:                break;
                   1946:
1.135     djm      1947:        case 3:
1.220     millert  1948:                if (fwdargs[0].ispath) {
                   1949:                        fwd->listen_path = xstrdup(fwdargs[0].arg);
                   1950:                        fwd->listen_port = PORT_STREAMLOCAL;
                   1951:                        fwd->connect_host = xstrdup(fwdargs[1].arg);
                   1952:                        fwd->connect_port = a2port(fwdargs[2].arg);
                   1953:                } else if (fwdargs[2].ispath) {
                   1954:                        fwd->listen_host = xstrdup(fwdargs[0].arg);
                   1955:                        fwd->listen_port = a2port(fwdargs[1].arg);
                   1956:                        fwd->connect_path = xstrdup(fwdargs[2].arg);
                   1957:                        fwd->connect_port = PORT_STREAMLOCAL;
                   1958:                } else {
                   1959:                        fwd->listen_host = NULL;
                   1960:                        fwd->listen_port = a2port(fwdargs[0].arg);
                   1961:                        fwd->connect_host = xstrdup(fwdargs[1].arg);
                   1962:                        fwd->connect_port = a2port(fwdargs[2].arg);
                   1963:                }
1.135     djm      1964:                break;
                   1965:
                   1966:        case 4:
1.220     millert  1967:                fwd->listen_host = xstrdup(fwdargs[0].arg);
                   1968:                fwd->listen_port = a2port(fwdargs[1].arg);
                   1969:                fwd->connect_host = xstrdup(fwdargs[2].arg);
                   1970:                fwd->connect_port = a2port(fwdargs[3].arg);
1.135     djm      1971:                break;
                   1972:        default:
                   1973:                i = 0; /* failure */
                   1974:        }
                   1975:
1.202     djm      1976:        free(p);
1.135     djm      1977:
1.168     stevesk  1978:        if (dynamicfwd) {
                   1979:                if (!(i == 1 || i == 2))
                   1980:                        goto fail_free;
                   1981:        } else {
1.220     millert  1982:                if (!(i == 3 || i == 4)) {
                   1983:                        if (fwd->connect_path == NULL &&
                   1984:                            fwd->listen_path == NULL)
                   1985:                                goto fail_free;
                   1986:                }
                   1987:                if (fwd->connect_port <= 0 && fwd->connect_path == NULL)
1.168     stevesk  1988:                        goto fail_free;
                   1989:        }
                   1990:
1.220     millert  1991:        if ((fwd->listen_port < 0 && fwd->listen_path == NULL) ||
                   1992:            (!remotefwd && fwd->listen_port == 0))
1.135     djm      1993:                goto fail_free;
                   1994:        if (fwd->connect_host != NULL &&
                   1995:            strlen(fwd->connect_host) >= NI_MAXHOST)
                   1996:                goto fail_free;
1.220     millert  1997:        /* XXX - if connecting to a remote socket, max sun len may not match this host */
                   1998:        if (fwd->connect_path != NULL &&
                   1999:            strlen(fwd->connect_path) >= PATH_MAX_SUN)
                   2000:                goto fail_free;
1.176     djm      2001:        if (fwd->listen_host != NULL &&
                   2002:            strlen(fwd->listen_host) >= NI_MAXHOST)
                   2003:                goto fail_free;
1.220     millert  2004:        if (fwd->listen_path != NULL &&
                   2005:            strlen(fwd->listen_path) >= PATH_MAX_SUN)
                   2006:                goto fail_free;
1.135     djm      2007:
                   2008:        return (i);
                   2009:
                   2010:  fail_free:
1.202     djm      2011:        free(fwd->connect_host);
                   2012:        fwd->connect_host = NULL;
1.220     millert  2013:        free(fwd->connect_path);
                   2014:        fwd->connect_path = NULL;
1.202     djm      2015:        free(fwd->listen_host);
                   2016:        fwd->listen_host = NULL;
1.220     millert  2017:        free(fwd->listen_path);
                   2018:        fwd->listen_path = NULL;
1.135     djm      2019:        return (0);
1.221   ! djm      2020: }
        !          2021:
        !          2022: /* XXX the following is a near-vebatim copy from servconf.c; refactor */
        !          2023: static const char *
        !          2024: fmt_multistate_int(int val, const struct multistate *m)
        !          2025: {
        !          2026:        u_int i;
        !          2027:
        !          2028:        for (i = 0; m[i].key != NULL; i++) {
        !          2029:                if (m[i].value == val)
        !          2030:                        return m[i].key;
        !          2031:        }
        !          2032:        return "UNKNOWN";
        !          2033: }
        !          2034:
        !          2035: static const char *
        !          2036: fmt_intarg(OpCodes code, int val)
        !          2037: {
        !          2038:        if (val == -1)
        !          2039:                return "unset";
        !          2040:        switch (code) {
        !          2041:        case oAddressFamily:
        !          2042:                return fmt_multistate_int(val, multistate_addressfamily);
        !          2043:        case oVerifyHostKeyDNS:
        !          2044:        case oStrictHostKeyChecking:
        !          2045:                return fmt_multistate_int(val, multistate_yesnoask);
        !          2046:        case oControlMaster:
        !          2047:                return fmt_multistate_int(val, multistate_controlmaster);
        !          2048:        case oTunnel:
        !          2049:                return fmt_multistate_int(val, multistate_tunnel);
        !          2050:        case oRequestTTY:
        !          2051:                return fmt_multistate_int(val, multistate_requesttty);
        !          2052:        case oCanonicalizeHostname:
        !          2053:                return fmt_multistate_int(val, multistate_canonicalizehostname);
        !          2054:        case oProtocol:
        !          2055:                switch (val) {
        !          2056:                case SSH_PROTO_1:
        !          2057:                        return "1";
        !          2058:                case SSH_PROTO_2:
        !          2059:                        return "2";
        !          2060:                case (SSH_PROTO_1|SSH_PROTO_2):
        !          2061:                        return "2,1";
        !          2062:                default:
        !          2063:                        return "UNKNOWN";
        !          2064:                }
        !          2065:        default:
        !          2066:                switch (val) {
        !          2067:                case 0:
        !          2068:                        return "no";
        !          2069:                case 1:
        !          2070:                        return "yes";
        !          2071:                default:
        !          2072:                        return "UNKNOWN";
        !          2073:                }
        !          2074:        }
        !          2075: }
        !          2076:
        !          2077: static const char *
        !          2078: lookup_opcode_name(OpCodes code)
        !          2079: {
        !          2080:        u_int i;
        !          2081:
        !          2082:        for (i = 0; keywords[i].name != NULL; i++)
        !          2083:                if (keywords[i].opcode == code)
        !          2084:                        return(keywords[i].name);
        !          2085:        return "UNKNOWN";
        !          2086: }
        !          2087:
        !          2088: static void
        !          2089: dump_cfg_int(OpCodes code, int val)
        !          2090: {
        !          2091:        printf("%s %d\n", lookup_opcode_name(code), val);
        !          2092: }
        !          2093:
        !          2094: static void
        !          2095: dump_cfg_fmtint(OpCodes code, int val)
        !          2096: {
        !          2097:        printf("%s %s\n", lookup_opcode_name(code), fmt_intarg(code, val));
        !          2098: }
        !          2099:
        !          2100: static void
        !          2101: dump_cfg_string(OpCodes code, const char *val)
        !          2102: {
        !          2103:        if (val == NULL)
        !          2104:                return;
        !          2105:        printf("%s %s\n", lookup_opcode_name(code), val);
        !          2106: }
        !          2107:
        !          2108: static void
        !          2109: dump_cfg_strarray(OpCodes code, u_int count, char **vals)
        !          2110: {
        !          2111:        u_int i;
        !          2112:
        !          2113:        for (i = 0; i < count; i++)
        !          2114:                printf("%s %s\n", lookup_opcode_name(code), vals[i]);
        !          2115: }
        !          2116:
        !          2117: static void
        !          2118: dump_cfg_strarray_oneline(OpCodes code, u_int count, char **vals)
        !          2119: {
        !          2120:        u_int i;
        !          2121:
        !          2122:        printf("%s", lookup_opcode_name(code));
        !          2123:        for (i = 0; i < count; i++)
        !          2124:                printf(" %s",  vals[i]);
        !          2125:        printf("\n");
        !          2126: }
        !          2127:
        !          2128: static void
        !          2129: dump_cfg_forwards(OpCodes code, u_int count, const struct Forward *fwds)
        !          2130: {
        !          2131:        const struct Forward *fwd;
        !          2132:        u_int i;
        !          2133:
        !          2134:        /* oDynamicForward */
        !          2135:        for (i = 0; i < count; i++) {
        !          2136:                fwd = &fwds[i];
        !          2137:                if (code == oDynamicForward &&
        !          2138:                    strcmp(fwd->connect_host, "socks") != 0)
        !          2139:                        continue;
        !          2140:                if (code == oLocalForward &&
        !          2141:                    strcmp(fwd->connect_host, "socks") == 0)
        !          2142:                        continue;
        !          2143:                printf("%s", lookup_opcode_name(code));
        !          2144:                if (fwd->listen_port == PORT_STREAMLOCAL)
        !          2145:                        printf(" %s", fwd->listen_path);
        !          2146:                else if (fwd->listen_host == NULL)
        !          2147:                        printf(" %d", fwd->listen_port);
        !          2148:                else {
        !          2149:                        printf(" [%s]:%d",
        !          2150:                            fwd->listen_host, fwd->listen_port);
        !          2151:                }
        !          2152:                if (code != oDynamicForward) {
        !          2153:                        if (fwd->connect_port == PORT_STREAMLOCAL)
        !          2154:                                printf(" %s", fwd->connect_path);
        !          2155:                        else if (fwd->connect_host == NULL)
        !          2156:                                printf(" %d", fwd->connect_port);
        !          2157:                        else {
        !          2158:                                printf(" [%s]:%d",
        !          2159:                                    fwd->connect_host, fwd->connect_port);
        !          2160:                        }
        !          2161:                }
        !          2162:                printf("\n");
        !          2163:        }
        !          2164: }
        !          2165:
        !          2166: void
        !          2167: dump_client_config(Options *o, const char *host)
        !          2168: {
        !          2169:        int i;
        !          2170:        char vbuf[5];
        !          2171:
        !          2172:        /* Most interesting options first: user, host, port */
        !          2173:        dump_cfg_string(oUser, o->user);
        !          2174:        dump_cfg_string(oHostName, host);
        !          2175:        dump_cfg_int(oPort, o->port);
        !          2176:
        !          2177:        /* Flag options */
        !          2178:        dump_cfg_fmtint(oAddressFamily, o->address_family);
        !          2179:        dump_cfg_fmtint(oBatchMode, o->batch_mode);
        !          2180:        dump_cfg_fmtint(oCanonicalizeFallbackLocal, o->canonicalize_fallback_local);
        !          2181:        dump_cfg_fmtint(oCanonicalizeHostname, o->canonicalize_hostname);
        !          2182:        dump_cfg_fmtint(oChallengeResponseAuthentication, o->challenge_response_authentication);
        !          2183:        dump_cfg_fmtint(oCheckHostIP, o->check_host_ip);
        !          2184:        dump_cfg_fmtint(oCompression, o->compression);
        !          2185:        dump_cfg_fmtint(oControlMaster, o->control_master);
        !          2186:        dump_cfg_fmtint(oEnableSSHKeysign, o->enable_ssh_keysign);
        !          2187:        dump_cfg_fmtint(oExitOnForwardFailure, o->exit_on_forward_failure);
        !          2188:        dump_cfg_fmtint(oForwardAgent, o->forward_agent);
        !          2189:        dump_cfg_fmtint(oForwardX11, o->forward_x11);
        !          2190:        dump_cfg_fmtint(oForwardX11Trusted, o->forward_x11_trusted);
        !          2191:        dump_cfg_fmtint(oGatewayPorts, o->fwd_opts.gateway_ports);
        !          2192: #ifdef GSSAPI
        !          2193:        dump_cfg_fmtint(oGssAuthentication, o->gss_authentication);
        !          2194:        dump_cfg_fmtint(oGssDelegateCreds, o->gss_deleg_creds);
        !          2195: #endif /* GSSAPI */
        !          2196:        dump_cfg_fmtint(oHashKnownHosts, o->hash_known_hosts);
        !          2197:        dump_cfg_fmtint(oHostbasedAuthentication, o->hostbased_authentication);
        !          2198:        dump_cfg_fmtint(oIdentitiesOnly, o->identities_only);
        !          2199:        dump_cfg_fmtint(oKbdInteractiveAuthentication, o->kbd_interactive_authentication);
        !          2200:        dump_cfg_fmtint(oNoHostAuthenticationForLocalhost, o->no_host_authentication_for_localhost);
        !          2201:        dump_cfg_fmtint(oPasswordAuthentication, o->password_authentication);
        !          2202:        dump_cfg_fmtint(oPermitLocalCommand, o->permit_local_command);
        !          2203:        dump_cfg_fmtint(oProtocol, o->protocol);
        !          2204:        dump_cfg_fmtint(oProxyUseFdpass, o->proxy_use_fdpass);
        !          2205:        dump_cfg_fmtint(oPubkeyAuthentication, o->pubkey_authentication);
        !          2206:        dump_cfg_fmtint(oRequestTTY, o->request_tty);
        !          2207:        dump_cfg_fmtint(oRhostsRSAAuthentication, o->rhosts_rsa_authentication);
        !          2208:        dump_cfg_fmtint(oRSAAuthentication, o->rsa_authentication);
        !          2209:        dump_cfg_fmtint(oStreamLocalBindUnlink, o->fwd_opts.streamlocal_bind_unlink);
        !          2210:        dump_cfg_fmtint(oStrictHostKeyChecking, o->strict_host_key_checking);
        !          2211:        dump_cfg_fmtint(oTCPKeepAlive, o->tcp_keep_alive);
        !          2212:        dump_cfg_fmtint(oTunnel, o->tun_open);
        !          2213:        dump_cfg_fmtint(oUsePrivilegedPort, o->use_privileged_port);
        !          2214:        dump_cfg_fmtint(oVerifyHostKeyDNS, o->verify_host_key_dns);
        !          2215:        dump_cfg_fmtint(oVisualHostKey, o->visual_host_key);
        !          2216:
        !          2217:        /* Integer options */
        !          2218:        dump_cfg_int(oCanonicalizeMaxDots, o->canonicalize_max_dots);
        !          2219:        dump_cfg_int(oCompressionLevel, o->compression_level);
        !          2220:        dump_cfg_int(oConnectionAttempts, o->connection_attempts);
        !          2221:        dump_cfg_int(oForwardX11Timeout, o->forward_x11_timeout);
        !          2222:        dump_cfg_int(oNumberOfPasswordPrompts, o->number_of_password_prompts);
        !          2223:        dump_cfg_int(oServerAliveCountMax, o->server_alive_count_max);
        !          2224:        dump_cfg_int(oServerAliveInterval, o->server_alive_interval);
        !          2225:
        !          2226:        /* String options */
        !          2227:        dump_cfg_string(oBindAddress, o->bind_address);
        !          2228:        dump_cfg_string(oCiphers, o->ciphers ? o->ciphers : KEX_CLIENT_ENCRYPT);
        !          2229:        dump_cfg_string(oControlPath, o->control_path);
        !          2230:        dump_cfg_string(oHostKeyAlgorithms, o->hostkeyalgorithms ? o->hostkeyalgorithms : KEX_DEFAULT_PK_ALG);
        !          2231:        dump_cfg_string(oHostKeyAlias, o->host_key_alias);
        !          2232:        dump_cfg_string(oKbdInteractiveDevices, o->kbd_interactive_devices);
        !          2233:        dump_cfg_string(oKexAlgorithms, o->kex_algorithms ? o->kex_algorithms : KEX_CLIENT_KEX);
        !          2234:        dump_cfg_string(oLocalCommand, o->local_command);
        !          2235:        dump_cfg_string(oLogLevel, log_level_name(o->log_level));
        !          2236:        dump_cfg_string(oMacs, o->macs ? o->macs : KEX_CLIENT_MAC);
        !          2237:        dump_cfg_string(oPKCS11Provider, o->pkcs11_provider);
        !          2238:        dump_cfg_string(oPreferredAuthentications, o->preferred_authentications);
        !          2239:        dump_cfg_string(oProxyCommand, o->proxy_command);
        !          2240:        dump_cfg_string(oXAuthLocation, o->xauth_location);
        !          2241:
        !          2242:        dump_cfg_forwards(oDynamicForward, o->num_local_forwards, o->local_forwards);
        !          2243:        dump_cfg_forwards(oLocalForward, o->num_local_forwards, o->local_forwards);
        !          2244:        dump_cfg_forwards(oRemoteForward, o->num_remote_forwards, o->remote_forwards);
        !          2245:
        !          2246:        /* String array options */
        !          2247:        dump_cfg_strarray(oIdentityFile, o->num_identity_files, o->identity_files);
        !          2248:        dump_cfg_strarray_oneline(oCanonicalDomains, o->num_canonical_domains, o->canonical_domains);
        !          2249:        dump_cfg_strarray_oneline(oGlobalKnownHostsFile, o->num_system_hostfiles, o->system_hostfiles);
        !          2250:        dump_cfg_strarray_oneline(oUserKnownHostsFile, o->num_user_hostfiles, o->user_hostfiles);
        !          2251:        dump_cfg_strarray(oSendEnv, o->num_send_env, o->send_env);
        !          2252:
        !          2253:        /* Special cases */
        !          2254:
        !          2255:        /* oConnectTimeout */
        !          2256:        if (o->connection_timeout == -1)
        !          2257:                printf("connecttimeout none\n");
        !          2258:        else
        !          2259:                dump_cfg_int(oConnectTimeout, o->connection_timeout);
        !          2260:
        !          2261:        /* oTunnelDevice */
        !          2262:        printf("tunneldevice");
        !          2263:        if (o->tun_local == SSH_TUNID_ANY)
        !          2264:                printf(" any");
        !          2265:        else
        !          2266:                printf(" %d", o->tun_local);
        !          2267:        if (o->tun_remote == SSH_TUNID_ANY)
        !          2268:                printf(":any");
        !          2269:        else
        !          2270:                printf(":%d", o->tun_remote);
        !          2271:        printf("\n");
        !          2272:
        !          2273:        /* oCanonicalizePermittedCNAMEs */
        !          2274:        if ( o->num_permitted_cnames > 0) {
        !          2275:                printf("canonicalizePermittedcnames");
        !          2276:                for (i = 0; i < o->num_permitted_cnames; i++) {
        !          2277:                        printf(" %s:%s", o->permitted_cnames[i].source_list,
        !          2278:                            o->permitted_cnames[i].target_list);
        !          2279:                }
        !          2280:                printf("\n");
        !          2281:        }
        !          2282:
        !          2283:        /* oCipher */
        !          2284:        if (o->cipher != SSH_CIPHER_NOT_SET)
        !          2285:                printf("Cipher %s\n", cipher_name(o->cipher));
        !          2286:
        !          2287:        /* oControlPersist */
        !          2288:        if (o->control_persist == 0 || o->control_persist_timeout == 0)
        !          2289:                dump_cfg_fmtint(oControlPersist, o->control_persist);
        !          2290:        else
        !          2291:                dump_cfg_int(oControlPersist, o->control_persist_timeout);
        !          2292:
        !          2293:        /* oEscapeChar */
        !          2294:        if (o->escape_char == SSH_ESCAPECHAR_NONE)
        !          2295:                printf("escapechar none\n");
        !          2296:        else {
        !          2297:                vis(vbuf, o->escape_char, VIS_WHITE, 0);
        !          2298:                printf("escapechar %s\n", vbuf);
        !          2299:        }
        !          2300:
        !          2301:        /* oIPQoS */
        !          2302:        printf("ipqos %s ", iptos2str(o->ip_qos_interactive));
        !          2303:        printf("%s\n", iptos2str(o->ip_qos_bulk));
        !          2304:
        !          2305:        /* oRekeyLimit */
        !          2306:        printf("rekeylimit %lld %d\n",
        !          2307:            (long long)o->rekey_limit, o->rekey_interval);
        !          2308:
        !          2309:        /* oStreamLocalBindMask */
        !          2310:        printf("streamlocalbindmask 0%o\n",
        !          2311:            o->fwd_opts.streamlocal_bind_mask);
1.1       deraadt  2312: }