diff options
author | Jason Downs <downsj@cvs.openbsd.org> | 1997-02-26 03:07:00 +0000 |
---|---|---|
committer | Jason Downs <downsj@cvs.openbsd.org> | 1997-02-26 03:07:00 +0000 |
commit | 805f364a7afb206a7c89e333232aca351b6e19e0 (patch) | |
tree | abb8889a3045ea5aa67c32f60cbd18196419b899 /lib/libwrap | |
parent | 69b5d60558dcb932964f8d6d64517209707041b5 (diff) |
Initial integration of a much cleaned up libwrap.
Diffstat (limited to 'lib/libwrap')
-rw-r--r-- | lib/libwrap/Makefile | 32 | ||||
-rw-r--r-- | lib/libwrap/clean_exit.c | 47 | ||||
-rw-r--r-- | lib/libwrap/diag.c | 75 | ||||
-rw-r--r-- | lib/libwrap/eval.c | 142 | ||||
-rw-r--r-- | lib/libwrap/fix_options.c | 132 | ||||
-rw-r--r-- | lib/libwrap/hosts_access.3 | 94 | ||||
-rw-r--r-- | lib/libwrap/hosts_access.5 | 379 | ||||
-rw-r--r-- | lib/libwrap/hosts_access.c | 339 | ||||
-rw-r--r-- | lib/libwrap/hosts_ctl.c | 44 | ||||
-rw-r--r-- | lib/libwrap/hosts_options.5 | 173 | ||||
-rw-r--r-- | lib/libwrap/misc.c | 91 | ||||
-rw-r--r-- | lib/libwrap/options.c | 629 | ||||
-rw-r--r-- | lib/libwrap/percent_m.c | 49 | ||||
-rw-r--r-- | lib/libwrap/percent_x.c | 91 | ||||
-rw-r--r-- | lib/libwrap/refuse.c | 38 | ||||
-rw-r--r-- | lib/libwrap/rfc931.c | 173 | ||||
-rw-r--r-- | lib/libwrap/scaffold.c | 219 | ||||
-rw-r--r-- | lib/libwrap/scaffold.h | 15 | ||||
-rw-r--r-- | lib/libwrap/shell_cmd.c | 99 | ||||
-rw-r--r-- | lib/libwrap/shlib_version | 2 | ||||
-rw-r--r-- | lib/libwrap/socket.c | 240 | ||||
-rw-r--r-- | lib/libwrap/tcpd.h | 221 | ||||
-rw-r--r-- | lib/libwrap/update.c | 126 |
23 files changed, 3450 insertions, 0 deletions
diff --git a/lib/libwrap/Makefile b/lib/libwrap/Makefile new file mode 100644 index 00000000000..14fb6b27ce2 --- /dev/null +++ b/lib/libwrap/Makefile @@ -0,0 +1,32 @@ +# $OpenBSD: Makefile,v 1.1 1997/02/26 03:06:49 downsj Exp $ + +LIB= wrap +SRCS= hosts_access.c options.c shell_cmd.c rfc931.c eval.c \ + hosts_ctl.c refuse.c percent_x.c clean_exit.c \ + fix_options.c socket.c update.c misc.c \ + diag.c percent_m.c +HDRS= tcpd.h + +# Configuration options for libwrap. +CFLAGS+=-DPROCESS_OPTIONS -DFACILITY=LOG_AUTH -DSEVERITY=LOG_INFO \ + -DRFC931_TIMEOUT=10 -DHOSTS_ACCESS -DALWAYS_HOSTNAME \ + -DHOSTS_DENY=\"/etc/hosts.deny\" -DHOSTS_ALLOW=\"/etc/hosts.allow\" \ + -DNETGROUP -DSYS_ERRLIST_DEFINED + +MAN= hosts_access.3 hosts_access.5 hosts_options.5 +MLINKS+=hosts_access.5 hosts.allow.5 +MLINKS+=hosts_access.5 hosts.deny.5 +MLINKS+=hosts_access.3 hosts_ctl.3 +MLINKS+=hosts_access.3 request_init.3 +MLINKS+=hosts_access.3 request_set.3 + +includes: + @cd ${.CURDIR}; for i in $(HDRS); do \ + j="cmp -s $$i ${DESTDIR}/usr/include/$$i || \ + ${INSTALL} ${COPY} -o ${BINOWN} -g ${BINGRP} -m 444 $$i \ + ${DESTDIR}/usr/include"; \ + echo $$j; \ + eval "$$j"; \ + done + +.include <bsd.lib.mk> diff --git a/lib/libwrap/clean_exit.c b/lib/libwrap/clean_exit.c new file mode 100644 index 00000000000..3e6f3815462 --- /dev/null +++ b/lib/libwrap/clean_exit.c @@ -0,0 +1,47 @@ +/* $OpenBSD: clean_exit.c,v 1.1 1997/02/26 03:06:50 downsj Exp $ */ + +/* + * clean_exit() cleans up and terminates the program. It should be called + * instead of exit() when for some reason the real network daemon will not or + * cannot be run. Reason: in the case of a datagram-oriented service we must + * discard the not-yet received data from the client. Otherwise, inetd will + * see the same datagram again and again, and go into a loop. + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) clean_exit.c 1.4 94/12/28 17:42:19"; +#else +static char rcsid[] = "$OpenBSD: clean_exit.c,v 1.1 1997/02/26 03:06:50 downsj Exp $"; +#endif +#endif + +#include <stdio.h> +#include <unistd.h> + +#include "tcpd.h" + +/* clean_exit - clean up and exit */ + +void clean_exit(request) +struct request_info *request; +{ + + /* + * In case of unconnected protocols we must eat up the not-yet received + * data or inetd will loop. + */ + + if (request->sink) + request->sink(request->fd); + + /* + * Be kind to the inetd. We already reported the problem via the syslogd, + * and there is no need for additional garbage in the logfile. + */ + + sleep(5); + exit(0); +} diff --git a/lib/libwrap/diag.c b/lib/libwrap/diag.c new file mode 100644 index 00000000000..ed8d064ed56 --- /dev/null +++ b/lib/libwrap/diag.c @@ -0,0 +1,75 @@ +/* $OpenBSD: diag.c,v 1.1 1997/02/26 03:06:50 downsj Exp $ */ + + /* + * Routines to report various classes of problems. Each report is decorated + * with the current context (file name and line number), if available. + * + * tcpd_warn() reports a problem and proceeds. + * + * tcpd_jump() reports a problem and jumps. + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) diag.c 1.1 94/12/28 17:42:20"; +#else +static char rcsid[] = "$OpenBSD: diag.c,v 1.1 1997/02/26 03:06:50 downsj Exp $"; +#endif +#endif + +/* System libraries */ + +#include <syslog.h> +#include <stdio.h> +#include <stdarg.h> +#include <setjmp.h> + +/* Local stuff */ + +#include "tcpd.h" + +struct tcpd_context tcpd_context; +jmp_buf tcpd_buf; + +/* tcpd_diag - centralize error reporter */ + +static void tcpd_diag(severity, tag, format, ap) +int severity; +char *tag; +char *format; +va_list ap; +{ + char fmt[BUFSIZ]; + + if (tcpd_context.file) + sprintf(fmt, "%s: %s, line %d: %s", + tag, tcpd_context.file, tcpd_context.line, format); + else + sprintf(fmt, "%s: %s", tag, format); + vsyslog(severity, fmt, ap); +} + +/* tcpd_warn - report problem of some sort and proceed */ + +void VARARGS(tcpd_warn, char *, format) +{ + va_list ap; + + VASTART(ap, char *, format); + tcpd_diag(LOG_ERR, "warning", format, ap); + VAEND(ap); +} + +/* tcpd_jump - report serious problem and jump */ + +void VARARGS(tcpd_jump, char *, format) +{ + va_list ap; + + VASTART(ap, char *, format); + tcpd_diag(LOG_ERR, "error", format, ap); + VAEND(ap); + longjmp(tcpd_buf, AC_ERROR); +} diff --git a/lib/libwrap/eval.c b/lib/libwrap/eval.c new file mode 100644 index 00000000000..ef8bc4562aa --- /dev/null +++ b/lib/libwrap/eval.c @@ -0,0 +1,142 @@ +/* $OpenBSD: eval.c,v 1.1 1997/02/26 03:06:50 downsj Exp $ */ + + /* + * Routines for controlled evaluation of host names, user names, and so on. + * They are, in fact, wrappers around the functions that are specific for + * the sockets or TLI programming interfaces. The request_info and host_info + * structures are used for result cacheing. + * + * These routines allows us to postpone expensive operations until their + * results are really needed. Examples are hostname lookups and double + * checks, or username lookups. Information that cannot be retrieved is + * given the value "unknown" ("paranoid" in case of hostname problems). + * + * When ALWAYS_HOSTNAME is off, hostname lookup is done only when required by + * tcpd paranoid mode, by access control patterns, or by %letter expansions. + * + * When ALWAYS_RFC931 mode is off, user lookup is done only when required by + * access control patterns or %letter expansions. + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) eval.c 1.3 95/01/30 19:51:45"; +#else +static char rcsid[] = "$OpenBSD: eval.c,v 1.1 1997/02/26 03:06:50 downsj Exp $"; +#endif +#endif + +/* System libraries. */ + +#include <stdio.h> +#include <string.h> + +/* Local stuff. */ + +#include "tcpd.h" + + /* + * When a string has the value STRING_UNKNOWN, it means: don't bother, I + * tried to look up the data but it was unavailable for some reason. When a + * host name has the value STRING_PARANOID it means there was a name/address + * conflict. + */ +char unknown[] = STRING_UNKNOWN; +char paranoid[] = STRING_PARANOID; + +/* eval_user - look up user name */ + +char *eval_user(request) +struct request_info *request; +{ + if (request->user[0] == 0) { + strcpy(request->user, unknown); + if (request->sink == 0 && request->client->sin && request->server->sin) + rfc931(request->client->sin, request->server->sin, request->user); + } + return (request->user); +} + +/* eval_hostaddr - look up printable address */ + +char *eval_hostaddr(host) +struct host_info *host; +{ + if (host->addr[0] == 0) { + strcpy(host->addr, unknown); + if (host->request->hostaddr != 0) + host->request->hostaddr(host); + } + return (host->addr); +} + +/* eval_hostname - look up host name */ + +char *eval_hostname(host) +struct host_info *host; +{ + if (host->name[0] == 0) { + strcpy(host->name, unknown); + if (host->request->hostname != 0) + host->request->hostname(host); + } + return (host->name); +} + +/* eval_hostinfo - return string with host name (preferred) or address */ + +char *eval_hostinfo(host) +struct host_info *host; +{ + char *hostname; + +#ifndef ALWAYS_HOSTNAME /* no implicit host lookups */ + if (host->name[0] == 0) + return (eval_hostaddr(host)); +#endif + hostname = eval_hostname(host); + if (HOSTNAME_KNOWN(hostname)) { + return (host->name); + } else { + return (eval_hostaddr(host)); + } +} + +/* eval_client - return string with as much about the client as we know */ + +char *eval_client(request) +struct request_info *request; +{ + static char both[2 * STRING_LENGTH]; + char *hostinfo = eval_hostinfo(request->client); + +#ifndef ALWAYS_RFC931 /* no implicit user lookups */ + if (request->user[0] == 0) + return (hostinfo); +#endif + if (STR_NE(eval_user(request), unknown)) { + sprintf(both, "%s@%s", request->user, hostinfo); + return (both); + } else { + return (hostinfo); + } +} + +/* eval_server - return string with as much about the server as we know */ + +char *eval_server(request) +struct request_info *request; +{ + static char both[2 * STRING_LENGTH]; + char *host = eval_hostinfo(request->server); + char *daemon = eval_daemon(request); + + if (STR_NE(host, unknown)) { + sprintf(both, "%s@%s", daemon, host); + return (both); + } else { + return (daemon); + } +} diff --git a/lib/libwrap/fix_options.c b/lib/libwrap/fix_options.c new file mode 100644 index 00000000000..619f1469952 --- /dev/null +++ b/lib/libwrap/fix_options.c @@ -0,0 +1,132 @@ +/* $OpenBSD: fix_options.c,v 1.1 1997/02/26 03:06:51 downsj Exp $ */ + + /* + * Routine to disable IP-level socket options. This code was taken from 4.4BSD + * rlogind and kernel source, but all mistakes in it are my fault. + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) fix_options.c 1.4 97/02/12 02:13:22"; +#else +static char rcsid[] = "$OpenBSD: fix_options.c,v 1.1 1997/02/26 03:06:51 downsj Exp $"; +#endif +#endif + +#include <sys/types.h> +#include <sys/param.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <netinet/in_systm.h> +#include <netinet/ip.h> +#include <netdb.h> +#include <stdio.h> +#include <syslog.h> + +#ifndef IPOPT_OPTVAL +#define IPOPT_OPTVAL 0 +#define IPOPT_OLEN 1 +#endif + +#include "tcpd.h" + +#define BUFFER_SIZE 512 /* Was: BUFSIZ */ + +/* fix_options - get rid of IP-level socket options */ + +void +fix_options(request) +struct request_info *request; +{ +#ifdef IP_OPTIONS + unsigned char optbuf[BUFFER_SIZE / 3], *cp; + char lbuf[BUFFER_SIZE], *lp; + int optsize = sizeof(optbuf), ipproto; + struct protoent *ip; + int fd = request->fd; + unsigned int opt; + int optlen; + unsigned char *first_option = optbuf; + + if ((ip = getprotobyname("ip")) != 0) + ipproto = ip->p_proto; + else + ipproto = IPPROTO_IP; + + if (getsockopt(fd, ipproto, IP_OPTIONS, (char *) optbuf, &optsize) == 0 + && optsize != 0) { + + /* + * Horror! 4.[34] BSD getsockopt() prepends the first-hop destination + * address to the result IP options list when source routing options + * are present (see <netinet/ip_var.h>), but produces no output for + * other IP options. Solaris 2.x getsockopt() does produce output for + * non-routing IP options, and uses the same format as BSD even when + * the space for the destination address is unused. However, we must + * be prepared to deal with systems that return the options only. The + * code below does the right thing with 4.[34]BSD derivatives and + * Solaris 2, but may occasionally miss source routing options on + * incompatible systems such as Linux. Their choice. + */ +#define ADDR_LEN sizeof(struct in_addr) + + for (cp = optbuf + ADDR_LEN; cp < optbuf + optsize; cp++) { + opt = cp[IPOPT_OPTVAL]; + if (opt != IPOPT_NOP) { + if (opt == IPOPT_RR + || opt == IPOPT_TS + || opt == IPOPT_SECURITY + || opt == IPOPT_LSRR + || opt == IPOPT_SATID + || opt == IPOPT_SSRR) + first_option = cp; + break; + } + } + + /* + * Look for source routing options. Drop the connection when one is + * found. Just wiping the IP options is insufficient: we would still + * help the attacker by providing a real TCP sequence number, and the + * attacker would still be able to send packets (blind spoofing). I + * discussed this attack with Niels Provos, half a year before the + * attack was described in open mailing lists. + * + * It would be cleaner to just return a yes/no reply and let the caller + * decide how to deal with it. Resident servers should not terminate. + * However I am not prepared to make changes to internal interfaces + * on short notice. + */ + for (cp = first_option; cp < optbuf + optsize; cp += optlen) { + opt = cp[IPOPT_OPTVAL]; + if (opt == IPOPT_LSRR || opt == IPOPT_SSRR) { + syslog(LOG_WARNING, + "refused connect from %s with IP source routing options", + eval_client(request)); + clean_exit(request); + } + if (opt == IPOPT_EOL) + break; + if (opt == IPOPT_NOP) { + optlen = 1; + } else { + optlen = cp[IPOPT_OLEN]; + if (optlen <= 0) /* Do not loop! */ + break; + } + } + lp = lbuf; + for (cp = optbuf; optsize > 0; cp++, optsize--, lp += 3) + sprintf(lp, " %2.2x", *cp); + syslog(LOG_NOTICE, + "connect from %s with IP options (ignored):%s", + eval_client(request), lbuf); + if (setsockopt(fd, ipproto, IP_OPTIONS, (char *) 0, optsize) != 0) { + syslog(LOG_ERR, "setsockopt IP_OPTIONS NULL: %m"); + clean_exit(request); + } + } +#endif +} diff --git a/lib/libwrap/hosts_access.3 b/lib/libwrap/hosts_access.3 new file mode 100644 index 00000000000..2614dbac21b --- /dev/null +++ b/lib/libwrap/hosts_access.3 @@ -0,0 +1,94 @@ +.\" $OpenBSD: hosts_access.3,v 1.1 1997/02/26 03:06:51 downsj Exp $ +.TH HOSTS_ACCESS 3 +.SH NAME +hosts_access, hosts_ctl, request_init, request_set \- access control library +.SH SYNOPSIS +.nf +#include "tcpd.h" + +extern int allow_severity; +extern int deny_severity; + +struct request_info *request_init(request, key, value, ..., 0) +struct request_info *request; + +struct request_info *request_set(request, key, value, ..., 0) +struct request_info *request; + +int hosts_access(request) +struct request_info *request; + +int hosts_ctl(daemon, client_name, client_addr, client_user) +char *daemon; +char *client_name; +char *client_addr; +char *client_user; +.fi +.SH DESCRIPTION +The routines described in this document are part of the \fIlibwrap.a\fR +library. They implement a rule-based access control language with +optional shell commands that are executed when a rule fires. +.PP +request_init() initializes a structure with information about a client +request. request_set() updates an already initialized request +structure. Both functions take a variable-length list of key-value +pairs and return their first argument. The argument lists are +terminated with a zero key value. All string-valued arguments are +copied. The expected keys (and corresponding value types) are: +.IP "RQ_FILE (int)" +The file descriptor associated with the request. +.IP "RQ_CLIENT_NAME (char *)" +The client host name. +.IP "RQ_CLIENT_ADDR (char *)" +A printable representation of the client network address. +.IP "RQ_CLIENT_SIN (struct sockaddr_in *)" +An internal representation of the client network address and port. The +contents of the structure are not copied. +.IP "RQ_SERVER_NAME (char *)" +The hostname associated with the server endpoint address. +.IP "RQ_SERVER_ADDR (char *)" +A printable representation of the server endpoint address. +.IP "RQ_SERVER_SIN (struct sockaddr_in *)" +An internal representation of the server endpoint address and port. +The contents of the structure are not copied. +.IP "RQ_DAEMON (char *)" +The name of the daemon process running on the server host. +.IP "RQ_USER (char *)" +The name of the user on whose behalf the client host makes the request. +.PP +hosts_access() consults the access control tables described in the +\fIhosts_access(5)\fR manual page. When internal endpoint information +is available, host names and client user names are looked up on demand, +using the request structure as a cache. hosts_access() returns zero if +access should be denied. +.PP +hosts_ctl() is a wrapper around the request_init() and hosts_access() +routines with a perhaps more convenient interface (though it does not +pass on enough information to support automated client username +lookups). The client host address, client host name and username +arguments should contain valid data or STRING_UNKNOWN. hosts_ctl() +returns zero if access should be denied. +.PP +The \fIallow_severity\fR and \fIdeny_severity\fR variables determine +how accepted and rejected requests may be logged. They must be provided +by the caller and may be modified by rules in the access control +tables. +.SH DIAGNOSTICS +Problems are reported via the syslog daemon. +.SH SEE ALSO +hosts_access(5), format of the access control tables. +hosts_options(5), optional extensions to the base language. +.SH FILES +/etc/hosts.allow, /etc/hosts.deny, access control tables. +.SH BUGS +hosts_access() uses the strtok() library function. This may interfere +with other code that relies on strtok(). +.SH AUTHOR +.na +.nf +Wietse Venema (wietse@wzv.win.tue.nl) +Department of Mathematics and Computing Science +Eindhoven University of Technology +Den Dolech 2, P.O. Box 513, +5600 MB Eindhoven, The Netherlands +\" @(#) hosts_access.3 1.8 96/02/11 17:01:26 diff --git a/lib/libwrap/hosts_access.5 b/lib/libwrap/hosts_access.5 new file mode 100644 index 00000000000..feab610e485 --- /dev/null +++ b/lib/libwrap/hosts_access.5 @@ -0,0 +1,379 @@ +.\" $OpenBSD: hosts_access.5,v 1.1 1997/02/26 03:06:52 downsj Exp $ +.TH HOSTS_ACCESS 5 +.SH NAME +hosts_access \- format of host access control files +.SH DESCRIPTION +This manual page describes a simple access control language that is +based on client (host name/address, user name), and server (process +name, host name/address) patterns. Examples are given at the end. The +impatient reader is encouraged to skip to the EXAMPLES section for a +quick introduction. +.PP +An extended version of the access control language is described in the +\fIhosts_options\fR(5) document. The extensions are turned on at +program build time by building with -DPROCESS_OPTIONS. +.PP +In the following text, \fIdaemon\fR is the the process name of a +network daemon process, and \fIclient\fR is the name and/or address of +a host requesting service. Network daemon process names are specified +in the inetd configuration file. +.SH ACCESS CONTROL FILES +The access control software consults two files. The search stops +at the first match: +.IP \(bu +Access will be granted when a (daemon,client) pair matches an entry in +the \fI/etc/hosts.allow\fR file. +.IP \(bu +Otherwise, access will be denied when a (daemon,client) pair matches an +entry in the \fI/etc/hosts.deny\fR file. +.IP \(bu +Otherwise, access will be granted. +.PP +A non-existing access control file is treated as if it were an empty +file. Thus, access control can be turned off by providing no access +control files. +.SH ACCESS CONTROL RULES +Each access control file consists of zero or more lines of text. These +lines are processed in order of appearance. The search terminates when a +match is found. +.IP \(bu +A newline character is ignored when it is preceded by a backslash +character. This permits you to break up long lines so that they are +easier to edit. +.IP \(bu +Blank lines or lines that begin with a `#\' character are ignored. +This permits you to insert comments and whitespace so that the tables +are easier to read. +.IP \(bu +All other lines should satisfy the following format, things between [] +being optional: +.sp +.ti +3 +daemon_list : client_list [ : shell_command ] +.PP +\fIdaemon_list\fR is a list of one or more daemon process names +(argv[0] values) or wildcards (see below). +.PP +\fIclient_list\fR is a list +of one or more host names, host addresses, patterns or wildcards (see +below) that will be matched against the client host name or address. +.PP +The more complex forms \fIdaemon@host\fR and \fIuser@host\fR are +explained in the sections on server endpoint patterns and on client +username lookups, respectively. +.PP +List elements should be separated by blanks and/or commas. +.PP +With the exception of NIS (YP) netgroup lookups, all access control +checks are case insensitive. +.ne 4 +.SH PATTERNS +The access control language implements the following patterns: +.IP \(bu +A string that begins with a `.\' character. A host name is matched if +the last components of its name match the specified pattern. For +example, the pattern `.tue.nl\' matches the host name +`wzv.win.tue.nl\'. +.IP \(bu +A string that ends with a `.\' character. A host address is matched if +its first numeric fields match the given string. For example, the +pattern `131.155.\' matches the address of (almost) every host on the +Eind\%hoven University network (131.155.x.x). +.IP \(bu +A string that begins with an `@\' character is treated as an NIS +(formerly YP) netgroup name. A host name is matched if it is a host +member of the specified netgroup. Netgroup matches are not supported +for daemon process names or for client user names. +.IP \(bu +An expression of the form `n.n.n.n/m.m.m.m\' is interpreted as a +`net/mask\' pair. A host address is matched if `net\' is equal to the +bitwise AND of the address and the `mask\'. For example, the net/mask +pattern `131.155.72.0/255.255.254.0\' matches every address in the +range `131.155.72.0\' through `131.155.73.255\'. +.SH WILDCARDS +The access control language supports explicit wildcards: +.IP ALL +The universal wildcard, always matches. +.IP LOCAL +Matches any host whose name does not contain a dot character. +.IP UNKNOWN +Matches any user whose name is unknown, and matches any host whose name +\fIor\fR address are unknown. This pattern should be used with care: +host names may be unavailable due to temporary name server problems. A +network address will be unavailable when the software cannot figure out +what type of network it is talking to. +.IP KNOWN +Matches any user whose name is known, and matches any host whose name +\fIand\fR address are known. This pattern should be used with care: +host names may be unavailable due to temporary name server problems. A +network address will be unavailable when the software cannot figure out +what type of network it is talking to. +.IP PARANOID +Matches any host whose name does not match its address. When tcpd is +built with -DPARANOID (default mode), it drops requests from such +clients even before looking at the access control tables. Build +without -DPARANOID when you want more control over such requests. +.ne 6 +.SH OPERATORS +.IP EXCEPT +Intended use is of the form: `list_1 EXCEPT list_2\'; this construct +matches anything that matches \fIlist_1\fR unless it matches +\fIlist_2\fR. The EXCEPT operator can be used in daemon_lists and in +client_lists. The EXCEPT operator can be nested: if the control +language would permit the use of parentheses, `a EXCEPT b EXCEPT c\' +would parse as `(a EXCEPT (b EXCEPT c))\'. +.br +.ne 6 +.SH SHELL COMMANDS +If the first-matched access control rule contains a shell command, that +command is subjected to %<letter> substitutions (see next section). +The result is executed by a \fI/bin/sh\fR child process with standard +input, output and error connected to \fI/dev/null\fR. Specify an `&\' +at the end of the command if you do not want to wait until it has +completed. +.PP +Shell commands should not rely on the PATH setting of the inetd. +Instead, they should use absolute path names, or they should begin with +an explicit PATH=whatever statement. +.PP +The \fIhosts_options\fR(5) document describes an alternative language +that uses the shell command field in a different and incompatible way. +.SH % EXPANSIONS +The following expansions are available within shell commands: +.IP "%a (%A)" +The client (server) host address. +.IP %c +Client information: user@host, user@address, a host name, or just an +address, depending on how much information is available. +.IP %d +The daemon process name (argv[0] value). +.IP "%h (%H)" +The client (server) host name or address, if the host name is +unavailable. +.IP "%n (%N)" +The client (server) host name (or "unknown" or "paranoid"). +.IP %p +The daemon process id. +.IP %s +Server information: daemon@host, daemon@address, or just a daemon name, +depending on how much information is available. +.IP %u +The client user name (or "unknown"). +.IP %% +Expands to a single `%\' character. +.PP +Characters in % expansions that may confuse the shell are replaced by +underscores. +.SH SERVER ENDPOINT PATTERNS +In order to distinguish clients by the network address that they +connect to, use patterns of the form: +.sp +.ti +3 +process_name@host_pattern : client_list ... +.sp +Patterns like these can be used when the machine has different internet +addresses with different internet hostnames. Service providers can use +this facility to offer FTP, GOPHER or WWW archives with internet names +that may even belong to different organizations. See also the `twist' +option in the hosts_options(5) document. Some systems (Solaris, +FreeBSD) can have more than one internet address on one physical +interface; with other systems you may have to resort to SLIP or PPP +pseudo interfaces that live in a dedicated network address space. +.sp +The host_pattern obeys the same syntax rules as host names and +addresses in client_list context. Usually, server endpoint information +is available only with connection-oriented services. +.SH CLIENT USERNAME LOOKUP +When the client host supports the RFC 931 protocol or one of its +descendants (TAP, IDENT, RFC 1413) the wrapper programs can retrieve +additional information about the owner of a connection. Client username +information, when available, is logged together with the client host +name, and can be used to match patterns like: +.PP +.ti +3 +daemon_list : ... user_pattern@host_pattern ... +.PP +The daemon wrappers can be configured at compile time to perform +rule-driven username lookups (default) or to always interrogate the +client host. In the case of rule-driven username lookups, the above +rule would cause username lookup only when both the \fIdaemon_list\fR +and the \fIhost_pattern\fR match. +.PP +A user pattern has the same syntax as a daemon process pattern, so the +same wildcards apply (netgroup membership is not supported). One +should not get carried away with username lookups, though. +.IP \(bu +The client username information cannot be trusted when it is needed +most, i.e. when the client system has been compromised. In general, +ALL and (UN)KNOWN are the only user name patterns that make sense. +.IP \(bu +Username lookups are possible only with TCP-based services, and only +when the client host runs a suitable daemon; in all other cases the +result is "unknown". +.IP \(bu +A well-known UNIX kernel bug may cause loss of service when username +lookups are blocked by a firewall. The wrapper README document +describes a procedure to find out if your kernel has this bug. +.IP \(bu +Username lookups may cause noticeable delays for non-UNIX users. The +default timeout for username lookups is 10 seconds: too short to cope +with slow networks, but long enough to irritate PC users. +.PP +Selective username lookups can alleviate the last problem. For example, +a rule like: +.PP +.ti +3 +daemon_list : @pcnetgroup ALL@ALL +.PP +would match members of the pc netgroup without doing username lookups, +but would perform username lookups with all other systems. +.SH DETECTING ADDRESS SPOOFING ATTACKS +A flaw in the sequence number generator of many TCP/IP implementations +allows intruders to easily impersonate trusted hosts and to break in +via, for example, the remote shell service. The IDENT (RFC931 etc.) +service can be used to detect such and other host address spoofing +attacks. +.PP +Before accepting a client request, the wrappers can use the IDENT +service to find out that the client did not send the request at all. +When the client host provides IDENT service, a negative IDENT lookup +result (the client matches `UNKNOWN@host') is strong evidence of a host +spoofing attack. +.PP +A positive IDENT lookup result (the client matches `KNOWN@host') is +less trustworthy. It is possible for an intruder to spoof both the +client connection and the IDENT lookup, although doing so is much +harder than spoofing just a client connection. It may also be that +the client\'s IDENT server is lying. +.PP +Note: IDENT lookups don\'t work with UDP services. +.SH EXAMPLES +The language is flexible enough that different types of access control +policy can be expressed with a minimum of fuss. Although the language +uses two access control tables, the most common policies can be +implemented with one of the tables being trivial or even empty. +.PP +When reading the examples below it is important to realize that the +allow table is scanned before the deny table, that the search +terminates when a match is found, and that access is granted when no +match is found at all. +.PP +The examples use host and domain names. They can be improved by +including address and/or network/netmask information, to reduce the +impact of temporary name server lookup failures. +.SH MOSTLY CLOSED +In this case, access is denied by default. Only explicitly authorized +hosts are permitted access. +.PP +The default policy (no access) is implemented with a trivial deny +file: +.PP +.ne 2 +/etc/hosts.deny: +.in +3 +ALL: ALL +.PP +This denies all service to all hosts, unless they are permitted access +by entries in the allow file. +.PP +The explicitly authorized hosts are listed in the allow file. +For example: +.PP +.ne 2 +/etc/hosts.allow: +.in +3 +ALL: LOCAL @some_netgroup +.br +ALL: .foobar.edu EXCEPT terminalserver.foobar.edu +.PP +The first rule permits access from hosts in the local domain (no `.\' +in the host name) and from members of the \fIsome_netgroup\fP +netgroup. The second rule permits access from all hosts in the +\fIfoobar.edu\fP domain (notice the leading dot), with the exception of +\fIterminalserver.foobar.edu\fP. +.SH MOSTLY OPEN +Here, access is granted by default; only explicitly specified hosts are +refused service. +.PP +The default policy (access granted) makes the allow file redundant so +that it can be omitted. The explicitly non-authorized hosts are listed +in the deny file. For example: +.PP +/etc/hosts.deny: +.in +3 +ALL: some.host.name, .some.domain +.br +ALL EXCEPT in.fingerd: other.host.name, .other.domain +.PP +The first rule denies some hosts and domains all services; the second +rule still permits finger requests from other hosts and domains. +.SH BOOBY TRAPS +The next example permits tftp requests from hosts in the local domain +(notice the leading dot). Requests from any other hosts are denied. +Instead of the requested file, a finger probe is sent to the offending +host. The result is mailed to the superuser. +.PP +.ne 2 +/etc/hosts.allow: +.in +3 +.nf +in.tftpd: LOCAL, .my.domain +.PP +.ne 2 +/etc/hosts.deny: +.in +3 +.nf +in.tftpd: ALL: (/some/where/safe_finger -l @%h | \\ + /usr/ucb/mail -s %d-%h root) & +.fi +.PP +The safe_finger command comes with the tcpd wrapper and should be +installed in a suitable place. It limits possible damage from data sent +by the remote finger server. It gives better protection than the +standard finger command. +.PP +The expansion of the %h (client host) and %d (service name) sequences +is described in the section on shell commands. +.PP +Warning: do not booby-trap your finger daemon, unless you are prepared +for infinite finger loops. +.PP +On network firewall systems this trick can be carried even further. +The typical network firewall only provides a limited set of services to +the outer world. All other services can be "bugged" just like the above +tftp example. The result is an excellent early-warning system. +.br +.ne 4 +.SH DIAGNOSTICS +An error is reported when a syntax error is found in a host access +control rule; when the length of an access control rule exceeds the +capacity of an internal buffer; when an access control rule is not +terminated by a newline character; when the result of %<letter> +expansion would overflow an internal buffer; when a system call fails +that shouldn\'t. All problems are reported via the syslog daemon. +.SH FILES +.na +.nf +/etc/hosts.allow, (daemon,client) pairs that are granted access. +/etc/hosts.deny, (daemon,client) pairs that are denied access. +.ad +.fi +.SH SEE ALSO +.nf +tcpd(8) tcp/ip daemon wrapper program. +tcpdchk(8), tcpdmatch(8), test programs. +.SH BUGS +If a name server lookup times out, the host name will not be available +to the access control software, even though the host is registered. +.PP +Domain name server lookups are case insensitive; NIS (formerly YP) +netgroup lookups are case sensitive. +.SH AUTHOR +.na +.nf +Wietse Venema (wietse@wzv.win.tue.nl) +Department of Mathematics and Computing Science +Eindhoven University of Technology +Den Dolech 2, P.O. Box 513, +5600 MB Eindhoven, The Netherlands +\" @(#) hosts_access.5 1.20 95/01/30 19:51:46 diff --git a/lib/libwrap/hosts_access.c b/lib/libwrap/hosts_access.c new file mode 100644 index 00000000000..bb9ca0e4128 --- /dev/null +++ b/lib/libwrap/hosts_access.c @@ -0,0 +1,339 @@ +/* $OpenBSD: hosts_access.c,v 1.1 1997/02/26 03:06:52 downsj Exp $ */ + + /* + * This module implements a simple access control language that is based on + * host (or domain) names, NIS (host) netgroup names, IP addresses (or + * network numbers) and daemon process names. When a match is found the + * search is terminated, and depending on whether PROCESS_OPTIONS is defined, + * a list of options is executed or an optional shell command is executed. + * + * Host and user names are looked up on demand, provided that suitable endpoint + * information is available as sockaddr_in structures or TLI netbufs. As a + * side effect, the pattern matching process may change the contents of + * request structure fields. + * + * Diagnostics are reported through syslog(3). + * + * Compile with -DNETGROUP if your library provides support for netgroups. + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) hosts_access.c 1.21 97/02/12 02:13:22"; +#else +static char rcsid[] = "$OpenBSD: hosts_access.c,v 1.1 1997/02/26 03:06:52 downsj Exp $"; +#endif +#endif + +/* System libraries. */ + +#include <sys/types.h> +#include <sys/param.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <stdio.h> +#include <syslog.h> +#include <ctype.h> +#include <errno.h> +#include <setjmp.h> +#include <string.h> +#ifdef NETGROUP +#include <netgroup.h> +#endif + +extern int errno; + +#ifndef INADDR_NONE +#define INADDR_NONE (-1) /* XXX should be 0xffffffff */ +#endif + +/* Local stuff. */ + +#include "tcpd.h" + +/* Error handling. */ + +extern jmp_buf tcpd_buf; + +/* Delimiters for lists of daemons or clients. */ + +static char sep[] = ", \t\r\n"; + +/* Constants to be used in assignments only, not in comparisons... */ + +#define YES 1 +#define NO 0 + + /* + * These variables are globally visible so that they can be redirected in + * verification mode. + */ + +char *hosts_allow_table = HOSTS_ALLOW; +char *hosts_deny_table = HOSTS_DENY; +int hosts_access_verbose = 0; + + /* + * In a long-running process, we are not at liberty to just go away. + */ + +int resident = (-1); /* -1, 0: unknown; +1: yes */ + +/* Forward declarations. */ + +static int table_match(); +static int list_match(); +static int server_match(); +static int client_match(); +static int host_match(); +static int string_match(); +static int masked_match(); + +/* Size of logical line buffer. */ + +#define BUFLEN 2048 + +/* hosts_access - host access control facility */ + +int hosts_access(request) +struct request_info *request; +{ + int verdict; + + /* + * If the (daemon, client) pair is matched by an entry in the file + * /etc/hosts.allow, access is granted. Otherwise, if the (daemon, + * client) pair is matched by an entry in the file /etc/hosts.deny, + * access is denied. Otherwise, access is granted. A non-existent + * access-control file is treated as an empty file. + * + * After a rule has been matched, the optional language extensions may + * decide to grant or refuse service anyway. Or, while a rule is being + * processed, a serious error is found, and it seems better to play safe + * and deny service. All this is done by jumping back into the + * hosts_access() routine, bypassing the regular return from the + * table_match() function calls below. + */ + + if (resident <= 0) + resident++; + verdict = setjmp(tcpd_buf); + if (verdict != 0) + return (verdict == AC_PERMIT); + if (table_match(hosts_allow_table, request)) + return (YES); + if (table_match(hosts_deny_table, request)) + return (NO); + return (YES); +} + +/* table_match - match table entries with (daemon, client) pair */ + +static int table_match(table, request) +char *table; +struct request_info *request; +{ + FILE *fp; + char sv_list[BUFLEN]; /* becomes list of daemons */ + char *cl_list; /* becomes list of clients */ + char *sh_cmd; /* becomes optional shell command */ + int match = NO; + struct tcpd_context saved_context; + + saved_context = tcpd_context; /* stupid compilers */ + + /* + * Between the fopen() and fclose() calls, avoid jumps that may cause + * file descriptor leaks. + */ + + if ((fp = fopen(table, "r")) != 0) { + tcpd_context.file = table; + tcpd_context.line = 0; + while (match == NO && xgets(sv_list, sizeof(sv_list), fp) != 0) { + if (sv_list[strlen(sv_list) - 1] != '\n') { + tcpd_warn("missing newline or line too long"); + continue; + } + if (sv_list[0] == '#' || sv_list[strspn(sv_list, " \t\r\n")] == 0) + continue; + if ((cl_list = split_at(sv_list, ':')) == 0) { + tcpd_warn("missing \":\" separator"); + continue; + } + sh_cmd = split_at(cl_list, ':'); + match = list_match(sv_list, request, server_match) + && list_match(cl_list, request, client_match); + } + (void) fclose(fp); + } else if (errno != ENOENT) { + tcpd_warn("cannot open %s: %m", table); + } + if (match) { + if (hosts_access_verbose > 1) + syslog(LOG_DEBUG, "matched: %s line %d", + tcpd_context.file, tcpd_context.line); + if (sh_cmd) { +#ifdef PROCESS_OPTIONS + process_options(sh_cmd, request); +#else + char cmd[BUFSIZ]; + shell_cmd(percent_x(cmd, sizeof(cmd), sh_cmd, request)); +#endif + } + } + tcpd_context = saved_context; + return (match); +} + +/* list_match - match a request against a list of patterns with exceptions */ + +static int list_match(list, request, match_fn) +char *list; +struct request_info *request; +int (*match_fn) (); +{ + char *tok; + + /* + * Process tokens one at a time. We have exhausted all possible matches + * when we reach an "EXCEPT" token or the end of the list. If we do find + * a match, look for an "EXCEPT" list and recurse to determine whether + * the match is affected by any exceptions. + */ + + for (tok = strtok(list, sep); tok != 0; tok = strtok((char *) 0, sep)) { + if (STR_EQ(tok, "EXCEPT")) /* EXCEPT: give up */ + return (NO); + if (match_fn(tok, request)) { /* YES: look for exceptions */ + while ((tok = strtok((char *) 0, sep)) && STR_NE(tok, "EXCEPT")) + /* VOID */ ; + return (tok == 0 || list_match((char *) 0, request, match_fn) == 0); + } + } + return (NO); +} + +/* server_match - match server information */ + +static int server_match(tok, request) +char *tok; +struct request_info *request; +{ + char *host; + + if ((host = split_at(tok + 1, '@')) == 0) { /* plain daemon */ + return (string_match(tok, eval_daemon(request))); + } else { /* daemon@host */ + return (string_match(tok, eval_daemon(request)) + && host_match(host, request->server)); + } +} + +/* client_match - match client information */ + +static int client_match(tok, request) +char *tok; +struct request_info *request; +{ + char *host; + + if ((host = split_at(tok + 1, '@')) == 0) { /* plain host */ + return (host_match(tok, request->client)); + } else { /* user@host */ + return (host_match(host, request->client) + && string_match(tok, eval_user(request))); + } +} + +/* host_match - match host name and/or address against pattern */ + +static int host_match(tok, host) +char *tok; +struct host_info *host; +{ + char *mask; + + /* + * This code looks a little hairy because we want to avoid unnecessary + * hostname lookups. + * + * The KNOWN pattern requires that both address AND name be known; some + * patterns are specific to host names or to host addresses; all other + * patterns are satisfied when either the address OR the name match. + */ + + if (tok[0] == '@') { /* netgroup: look it up */ +#ifdef NETGROUP + static char *mydomain = 0; + if (mydomain == 0) + yp_get_default_domain(&mydomain); + return (innetgr(tok + 1, eval_hostname(host), (char *) 0, mydomain)); +#else + tcpd_warn("netgroup support is disabled"); /* not tcpd_jump() */ + return (NO); +#endif + } else if (STR_EQ(tok, "KNOWN")) { /* check address and name */ + char *name = eval_hostname(host); + return (STR_NE(eval_hostaddr(host), unknown) && HOSTNAME_KNOWN(name)); + } else if (STR_EQ(tok, "LOCAL")) { /* local: no dots in name */ + char *name = eval_hostname(host); + return (strchr(name, '.') == 0 && HOSTNAME_KNOWN(name)); + } else if ((mask = split_at(tok, '/')) != 0) { /* net/mask */ + return (masked_match(tok, mask, eval_hostaddr(host))); + } else { /* anything else */ + return (string_match(tok, eval_hostaddr(host)) + || (NOT_INADDR(tok) && string_match(tok, eval_hostname(host)))); + } +} + +/* string_match - match string against pattern */ + +static int string_match(tok, string) +char *tok; +char *string; +{ + int n; + + if (tok[0] == '.') { /* suffix */ + n = strlen(string) - strlen(tok); + return (n > 0 && STR_EQ(tok, string + n)); + } else if (STR_EQ(tok, "ALL")) { /* all: match any */ + return (YES); + } else if (STR_EQ(tok, "KNOWN")) { /* not unknown */ + return (STR_NE(string, unknown)); + } else if (tok[(n = strlen(tok)) - 1] == '.') { /* prefix */ + return (STRN_EQ(tok, string, n)); + } else { /* exact match */ + return (STR_EQ(tok, string)); + } +} + +/* masked_match - match address against netnumber/netmask */ + +static int masked_match(net_tok, mask_tok, string) +char *net_tok; +char *mask_tok; +char *string; +{ + unsigned long net; + unsigned long mask; + unsigned long addr; + + /* + * Disallow forms other than dotted quad: the treatment that inet_addr() + * gives to forms with less than four components is inconsistent with the + * access control language. John P. Rouillard <rouilj@cs.umb.edu>. + */ + + if ((addr = dot_quad_addr(string)) == INADDR_NONE) + return (NO); + if ((net = dot_quad_addr(net_tok)) == INADDR_NONE + || (mask = dot_quad_addr(mask_tok)) == INADDR_NONE) { + tcpd_warn("bad net/mask expression: %s/%s", net_tok, mask_tok); + return (NO); /* not tcpd_jump() */ + } + return ((addr & mask) == net); +} diff --git a/lib/libwrap/hosts_ctl.c b/lib/libwrap/hosts_ctl.c new file mode 100644 index 00000000000..ec53c3f2694 --- /dev/null +++ b/lib/libwrap/hosts_ctl.c @@ -0,0 +1,44 @@ +/* $OpenBSD: hosts_ctl.c,v 1.1 1997/02/26 03:06:53 downsj Exp $ */ + + /* + * hosts_ctl() combines common applications of the host access control + * library routines. It bundles its arguments then calls the hosts_access() + * access control checker. The host name and user name arguments should be + * empty strings, STRING_UNKNOWN or real data. If a match is found, the + * optional shell command is executed. + * + * Restriction: this interface does not pass enough information to support + * selective remote username lookups or selective hostname double checks. + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) hosts_ctl.c 1.4 94/12/28 17:42:27"; +#else +static char rcsid[] = "$OpenBSD: hosts_ctl.c,v 1.1 1997/02/26 03:06:53 downsj Exp $"; +#endif +#endif + +#include <stdio.h> + +#include "tcpd.h" + +/* hosts_ctl - limited interface to the hosts_access() routine */ + +int hosts_ctl(daemon, name, addr, user) +char *daemon; +char *name; +char *addr; +char *user; +{ + struct request_info request; + + return (hosts_access(request_init(&request, + RQ_DAEMON, daemon, + RQ_CLIENT_NAME, name, + RQ_CLIENT_ADDR, addr, + RQ_USER, user, + 0))); +} diff --git a/lib/libwrap/hosts_options.5 b/lib/libwrap/hosts_options.5 new file mode 100644 index 00000000000..0a727c9e76e --- /dev/null +++ b/lib/libwrap/hosts_options.5 @@ -0,0 +1,173 @@ +.\" $OpenBSD: hosts_options.5,v 1.1 1997/02/26 03:06:53 downsj Exp $ +.TH HOSTS_OPTIONS 5 +.SH NAME +hosts_options \- host access control language extensions +.SH DESCRIPTION +This document describes optional extensions to the language described +in the hosts_access(5) document. The extensions are enabled at program +build time. For example, by editing the Makefile and turning on the +PROCESS_OPTIONS compile-time option. +.PP +The extensible language uses the following format: +.sp +.ti +3 +daemon_list : client_list : option : option ... +.PP +The first two fields are described in the hosts_access(5) manual page. +The remainder of the rules is a list of zero or more options. Any ":" +characters within options should be protected with a backslash. +.PP +An option is of the form "keyword" or "keyword value". Options are +processed in the specified order. Some options are subjected to +%<letter> substitutions. For the sake of backwards compatibility with +earlier versions, an "=" is permitted between keyword and value. +.SH LOGGING +.IP "severity mail.info" +.IP "severity notice" +Change the severity level at which the event will be logged. Facility +names (such as mail) are optional, and are not supported on systems +with older syslog implementations. The severity option can be used +to emphasize or to ignore specific events. +.SH ACCESS CONTROL +.IP "allow" +.IP "deny" +Grant (deny) service. These options must appear at the end of a rule. +.PP +The \fIallow\fR and \fIdeny\fR keywords make it possible to keep all +access control rules within a single file, for example in the +\fIhosts.allow\fR file. +.sp +To permit access from specific hosts only: +.sp +.ne 2 +.ti +3 +ALL: .friendly.domain: ALLOW +.ti +3 +ALL: ALL: DENY +.sp +To permit access from all hosts except a few trouble makers: +.sp +.ne 2 +.ti +3 +ALL: .bad.domain: DENY +.ti +3 +ALL: ALL: ALLOW +.sp +Notice the leading dot on the domain name patterns. +.SH RUNNING OTHER COMMANDS +.IP "spawn shell_command" +Execute, in a child process, the specified shell command, after +performing the %<letter> expansions described in the hosts_access(5) +manual page. The command is executed with stdin, stdout and stderr +connected to the null device, so that it won\'t mess up the +conversation with the client host. Example: +.sp +.nf +.ti +3 +spawn (/some/where/safe_finger -l @%h | /usr/ucb/mail root) & +.fi +.sp +executes, in a background child process, the shell command "safe_finger +-l @%h | mail root" after replacing %h by the name or address of the +remote host. +.sp +The example uses the "safe_finger" command instead of the regular +"finger" command, to limit possible damage from data sent by the finger +server. The "safe_finger" command is part of the daemon wrapper +package; it is a wrapper around the regular finger command that filters +the data sent by the remote host. +.IP "twist shell_command" +Replace the current process by an instance of the specified shell +command, after performing the %<letter> expansions described in the +hosts_access(5) manual page. Stdin, stdout and stderr are connected to +the client process. This option must appear at the end of a rule. +.sp +To send a customized bounce message to the client instead of +running the real ftp daemon: +.sp +.nf +.ti +3 +in.ftpd : ... : twist /bin/echo 421 Some bounce message +.fi +.sp +For an alternative way to talk to client processes, see the +\fIbanners\fR option below. +.sp +To run /some/other/in.telnetd without polluting its command-line +array or its process environment: +.sp +.nf +.ti +3 +in.telnetd : ... : twist PATH=/some/other; exec in.telnetd +.fi +.sp +Warning: in case of UDP services, do not twist to commands that use +the standard I/O or the read(2)/write(2) routines to communicate with +the client process; UDP requires other I/O primitives. +.SH NETWORK OPTIONS +.IP "keepalive" +Causes the server to periodically send a message to the client. The +connection is considered broken when the client does not respond. The +keepalive option can be useful when users turn off their machine while +it is still connected to a server. The keepalive option is not useful +for datagram (UDP) services. +.IP "linger number_of_seconds" +Specifies how long the kernel will try to deliver not-yet delivered +data after the server process closes a connection. +.SH USERNAME LOOKUP +.IP "rfc931 [ timeout_in_seconds ]" +Look up the client user name with the RFC 931 (TAP, IDENT, RFC 1413) +protocol. This option is silently ignored in case of services based on +transports other than TCP. It requires that the client system runs an +RFC 931 (IDENT, etc.) -compliant daemon, and may cause noticeable +delays with connections from non-UNIX clients. The timeout period is +optional. If no timeout is specified a compile-time defined default +value is taken. +.SH MISCELLANEOUS +.IP "banners /some/directory" +Look for a file in `/some/directory' with the same name as the daemon +process (for example in.telnetd for the telnet service), and copy its +contents to the client. Newline characters are replaced by +carriage-return newline, and %<letter> sequences are expanded (see +the hosts_access(5) manual page). +.sp +The tcp wrappers source code distribution provides a sample makefile +(Banners.Makefile) for convenient banner maintenance. +.sp +Warning: banners are supported for connection-oriented (TCP) network +services only. +.IP "nice [ number ]" +Change the nice value of the process (default 10). Specify a positive +value to spend more CPU resources on other processes. +.IP "setenv name value" +Place a (name, value) pair into the process environment. The value is +subjected to %<letter> expansions and may contain whitespace (but +leading and trailing blanks are stripped off). +.sp +Warning: many network daemons reset their environment before spawning a +login or shell process. +.IP "umask 022" +Like the umask command that is built into the shell. An umask of 022 +prevents the creation of files with group and world write permission. +The umask argument should be an octal number. +.IP "user nobody" +.IP "user nobody.kmem" +Assume the privileges of the "nobody" userid (or user "nobody", group +"kmem"). The first form is useful with inetd implementations that run +all services with root privilege. The second form is useful for +services that need special group privileges only. +.SH DIAGNOSTICS +When a syntax error is found in an access control rule, the error +is reported to the syslog daemon; further options will be ignored, +and service is denied. +.SH SEE ALSO +hosts_access(5), the default access control language +.SH AUTHOR +.na +.nf +Wietse Venema (wietse@wzv.win.tue.nl) +Department of Mathematics and Computing Science +Eindhoven University of Technology +Den Dolech 2, P.O. Box 513, +5600 MB Eindhoven, The Netherlands +\" @(#) hosts_options.5 1.10 94/12/28 17:42:28 diff --git a/lib/libwrap/misc.c b/lib/libwrap/misc.c new file mode 100644 index 00000000000..7819fb59309 --- /dev/null +++ b/lib/libwrap/misc.c @@ -0,0 +1,91 @@ +/* $OpenBSD: misc.c,v 1.1 1997/02/26 03:06:53 downsj Exp $ */ + + /* + * Misc routines that are used by tcpd and by tcpdchk. + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsic[] = "@(#) misc.c 1.2 96/02/11 17:01:29"; +#else +static char rcsid[] = "$OpenBSD: misc.c,v 1.1 1997/02/26 03:06:53 downsj Exp $"; +#endif +#endif + +#include <sys/types.h> +#include <sys/param.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <stdio.h> +#include <string.h> + +#include "tcpd.h" + +#ifndef INADDR_NONE +#define INADDR_NONE (-1) /* XXX should be 0xffffffff */ +#endif + +/* xgets - fgets() with backslash-newline stripping */ + +char *xgets(ptr, len, fp) +char *ptr; +int len; +FILE *fp; +{ + int got; + char *start = ptr; + + while (fgets(ptr, len, fp)) { + got = strlen(ptr); + if (got >= 1 && ptr[got - 1] == '\n') { + tcpd_context.line++; + if (got >= 2 && ptr[got - 2] == '\\') { + got -= 2; + } else { + return (start); + } + } + ptr += got; + len -= got; + ptr[0] = 0; + } + return (ptr > start ? start : 0); +} + +/* split_at - break string at delimiter or return NULL */ + +char *split_at(string, delimiter) +char *string; +int delimiter; +{ + char *cp; + + if ((cp = strchr(string, delimiter)) != 0) + *cp++ = 0; + return (cp); +} + +/* dot_quad_addr - convert dotted quad to internal form */ + +unsigned long dot_quad_addr(str) +char *str; +{ + int in_run = 0; + int runs = 0; + char *cp = str; + + /* Count the number of runs of non-dot characters. */ + + while (*cp) { + if (*cp == '.') { + in_run = 0; + } else if (in_run == 0) { + in_run = 1; + runs++; + } + cp++; + } + return (runs == 4 ? inet_addr(str) : INADDR_NONE); +} diff --git a/lib/libwrap/options.c b/lib/libwrap/options.c new file mode 100644 index 00000000000..30e456f3887 --- /dev/null +++ b/lib/libwrap/options.c @@ -0,0 +1,629 @@ +/* $OpenBSD: options.c,v 1.1 1997/02/26 03:06:54 downsj Exp $ */ + + /* + * General skeleton for adding options to the access control language. The + * features offered by this module are documented in the hosts_options(5) + * manual page (source file: hosts_options.5, "nroff -man" format). + * + * Notes and warnings for those who want to add features: + * + * In case of errors, abort options processing and deny access. There are too + * many irreversible side effects to make error recovery feasible. For + * example, it makes no sense to continue after we have already changed the + * userid. + * + * In case of errors, do not terminate the process: the routines might be + * called from a long-running daemon that should run forever. Instead, call + * tcpd_jump() which does a non-local goto back into the hosts_access() + * routine. + * + * In case of severe errors, use clean_exit() instead of directly calling + * exit(), or the inetd may loop on an UDP request. + * + * In verification mode (for example, with the "tcpdmatch" command) the + * "dry_run" flag is set. In this mode, an option function should just "say" + * what it is going to do instead of really doing it. + * + * Some option functions do not return (for example, the twist option passes + * control to another program). In verification mode (dry_run flag is set) + * such options should clear the "dry_run" flag to inform the caller of this + * course of action. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) options.c 1.17 96/02/11 17:01:31"; +#else +static char rcsid[] = "$OpenBSD: options.c,v 1.1 1997/02/26 03:06:54 downsj Exp $"; +#endif +#endif + +/* System libraries. */ + +#include <sys/types.h> +#include <sys/param.h> +#include <sys/socket.h> +#include <sys/stat.h> +#include <netinet/in.h> +#include <netdb.h> +#include <stdio.h> +#include <stdlib.h> +#include <syslog.h> +#include <pwd.h> +#include <grp.h> +#include <ctype.h> +#include <setjmp.h> +#include <string.h> +#include <unistd.h> + +#ifndef MAXPATHNAMELEN +#define MAXPATHNAMELEN BUFSIZ +#endif + +/* Local stuff. */ + +#include "tcpd.h" + +/* Options runtime support. */ + +int dry_run = 0; /* flag set in verification mode */ +extern jmp_buf tcpd_buf; /* tcpd_jump() support */ + +/* Options parser support. */ + +static char whitespace_eq[] = "= \t\r\n"; +#define whitespace (whitespace_eq + 1) + +static char *get_field(); /* chew :-delimited field off string */ +static char *chop_string(); /* strip leading and trailing blanks */ + +/* List of functions that implement the options. Add yours here. */ + +static void user_option(); /* execute "user name.group" option */ +static void group_option(); /* execute "group name" option */ +static void umask_option(); /* execute "umask mask" option */ +static void linger_option(); /* execute "linger time" option */ +static void keepalive_option(); /* execute "keepalive" option */ +static void spawn_option(); /* execute "spawn command" option */ +static void twist_option(); /* execute "twist command" option */ +static void rfc931_option(); /* execute "rfc931" option */ +static void setenv_option(); /* execute "setenv name value" */ +static void nice_option(); /* execute "nice" option */ +static void severity_option(); /* execute "severity value" */ +static void allow_option(); /* execute "allow" option */ +static void deny_option(); /* execute "deny" option */ +static void banners_option(); /* execute "banners path" option */ + +/* Structure of the options table. */ + +struct option { + char *name; /* keyword name, case is ignored */ + void (*func) (); /* function that does the real work */ + int flags; /* see below... */ +}; + +#define NEED_ARG (1<<1) /* option requires argument */ +#define USE_LAST (1<<2) /* option must be last */ +#define OPT_ARG (1<<3) /* option has optional argument */ +#define EXPAND_ARG (1<<4) /* do %x expansion on argument */ + +#define need_arg(o) ((o)->flags & NEED_ARG) +#define opt_arg(o) ((o)->flags & OPT_ARG) +#define permit_arg(o) ((o)->flags & (NEED_ARG | OPT_ARG)) +#define use_last(o) ((o)->flags & USE_LAST) +#define expand_arg(o) ((o)->flags & EXPAND_ARG) + +/* List of known keywords. Add yours here. */ + +static struct option option_table[] = { + "user", user_option, NEED_ARG, + "group", group_option, NEED_ARG, + "umask", umask_option, NEED_ARG, + "linger", linger_option, NEED_ARG, + "keepalive", keepalive_option, 0, + "spawn", spawn_option, NEED_ARG | EXPAND_ARG, + "twist", twist_option, NEED_ARG | EXPAND_ARG | USE_LAST, + "rfc931", rfc931_option, OPT_ARG, + "setenv", setenv_option, NEED_ARG | EXPAND_ARG, + "nice", nice_option, OPT_ARG, + "severity", severity_option, NEED_ARG, + "allow", allow_option, USE_LAST, + "deny", deny_option, USE_LAST, + "banners", banners_option, NEED_ARG, + 0, +}; + +/* process_options - process access control options */ + +void process_options(options, request) +char *options; +struct request_info *request; +{ + char *key; + char *value; + char *curr_opt; + char *next_opt; + struct option *op; + char bf[BUFSIZ]; + + for (curr_opt = get_field(options); curr_opt; curr_opt = next_opt) { + next_opt = get_field((char *) 0); + + /* + * Separate the option into name and value parts. For backwards + * compatibility we ignore exactly one '=' between name and value. + */ + curr_opt = chop_string(curr_opt); + if (*(value = curr_opt + strcspn(curr_opt, whitespace_eq))) { + if (*value != '=') { + *value++ = 0; + value += strspn(value, whitespace); + } + if (*value == '=') { + *value++ = 0; + value += strspn(value, whitespace); + } + } + if (*value == 0) + value = 0; + key = curr_opt; + + /* + * Disallow missing option names (and empty option fields). + */ + if (*key == 0) + tcpd_jump("missing option name"); + + /* + * Lookup the option-specific info and do some common error checks. + * Delegate option-specific processing to the specific functions. + */ + + for (op = option_table; op->name && STR_NE(op->name, key); op++) + /* VOID */ ; + if (op->name == 0) + tcpd_jump("bad option name: \"%s\"", key); + if (!value && need_arg(op)) + tcpd_jump("option \"%s\" requires value", key); + if (value && !permit_arg(op)) + tcpd_jump("option \"%s\" requires no value", key); + if (next_opt && use_last(op)) + tcpd_jump("option \"%s\" must be at end", key); + if (value && expand_arg(op)) + value = chop_string(percent_x(bf, sizeof(bf), value, request)); + if (hosts_access_verbose) + syslog(LOG_DEBUG, "option: %s %s", key, value ? value : ""); + (*(op->func)) (value, request); + } +} + +/* allow_option - grant access */ + +/* ARGSUSED */ + +static void allow_option(value, request) +char *value; +struct request_info *request; +{ + longjmp(tcpd_buf, AC_PERMIT); +} + +/* deny_option - deny access */ + +/* ARGSUSED */ + +static void deny_option(value, request) +char *value; +struct request_info *request; +{ + longjmp(tcpd_buf, AC_DENY); +} + +/* banners_option - expand %<char>, terminate each line with CRLF */ + +static void banners_option(value, request) +char *value; +struct request_info *request; +{ + char path[MAXPATHNAMELEN]; + char ibuf[BUFSIZ]; + char obuf[2 * BUFSIZ]; + struct stat st; + int ch; + FILE *fp; + + sprintf(path, "%s/%s", value, eval_daemon(request)); + if ((fp = fopen(path, "r")) != 0) { + while ((ch = fgetc(fp)) == 0) + write(request->fd, "", 1); + ungetc(ch, fp); + while (fgets(ibuf, sizeof(ibuf) - 1, fp)) { + if (split_at(ibuf, '\n')) + strcat(ibuf, "\r\n"); + percent_x(obuf, sizeof(obuf), ibuf, request); + write(request->fd, obuf, strlen(obuf)); + } + fclose(fp); + } else if (stat(value, &st) < 0) { + tcpd_warn("%s: %m", value); + } +} + +/* group_option - switch group id */ + +/* ARGSUSED */ + +static void group_option(value, request) +char *value; +struct request_info *request; +{ + struct group *grp; + struct group *getgrnam(); + + if ((grp = getgrnam(value)) == 0) + tcpd_jump("unknown group: \"%s\"", value); + endgrent(); + + if (dry_run == 0 && setgid(grp->gr_gid)) + tcpd_jump("setgid(%s): %m", value); +} + +/* user_option - switch user id */ + +/* ARGSUSED */ + +static void user_option(value, request) +char *value; +struct request_info *request; +{ + struct passwd *pwd; + struct passwd *getpwnam(); + char *group; + + if ((group = split_at(value, '.')) != 0) + group_option(group, request); + if ((pwd = getpwnam(value)) == 0) + tcpd_jump("unknown user: \"%s\"", value); + endpwent(); + + if (dry_run == 0 && setuid(pwd->pw_uid)) + tcpd_jump("setuid(%s): %m", value); +} + +/* umask_option - set file creation mask */ + +/* ARGSUSED */ + +static void umask_option(value, request) +char *value; +struct request_info *request; +{ + unsigned mask; + char junk; + + if (sscanf(value, "%o%c", &mask, &junk) != 1 || (mask & 0777) != mask) + tcpd_jump("bad umask value: \"%s\"", value); + (void) umask(mask); +} + +/* spawn_option - spawn a shell command and wait */ + +/* ARGSUSED */ + +static void spawn_option(value, request) +char *value; +struct request_info *request; +{ + if (dry_run == 0) + shell_cmd(value); +} + +/* linger_option - set the socket linger time (Marc Boucher <marc@cam.org>) */ + +/* ARGSUSED */ + +static void linger_option(value, request) +char *value; +struct request_info *request; +{ + struct linger linger; + char junk; + + if (sscanf(value, "%d%c", &linger.l_linger, &junk) != 1 + || linger.l_linger < 0) + tcpd_jump("bad linger value: \"%s\"", value); + if (dry_run == 0) { + linger.l_onoff = (linger.l_linger != 0); + if (setsockopt(request->fd, SOL_SOCKET, SO_LINGER, (char *) &linger, + sizeof(linger)) < 0) + tcpd_warn("setsockopt SO_LINGER %d: %m", linger.l_linger); + } +} + +/* keepalive_option - set the socket keepalive option */ + +/* ARGSUSED */ + +static void keepalive_option(value, request) +char *value; +struct request_info *request; +{ + static int on = 1; + + if (dry_run == 0 && setsockopt(request->fd, SOL_SOCKET, SO_KEEPALIVE, + (char *) &on, sizeof(on)) < 0) + tcpd_warn("setsockopt SO_KEEPALIVE: %m"); +} + +/* nice_option - set nice value */ + +/* ARGSUSED */ + +static void nice_option(value, request) +char *value; +struct request_info *request; +{ + int niceval = 10; + char junk; + + if (value != 0 && sscanf(value, "%d%c", &niceval, &junk) != 1) + tcpd_jump("bad nice value: \"%s\"", value); + if (dry_run == 0 && nice(niceval) < 0) + tcpd_warn("nice(%d): %m", niceval); +} + +/* twist_option - replace process by shell command */ + +static void twist_option(value, request) +char *value; +struct request_info *request; +{ + char *error; + + if (dry_run != 0) { + dry_run = 0; + } else { + if (resident > 0) + tcpd_jump("twist option in resident process"); + + syslog(deny_severity, "twist %s to %s", eval_client(request), value); + + /* Before switching to the shell, set up stdin, stdout and stderr. */ + +#define maybe_dup2(from, to) ((from == to) ? to : (close(to), dup(from))) + + if (maybe_dup2(request->fd, 0) != 0 || + maybe_dup2(request->fd, 1) != 1 || + maybe_dup2(request->fd, 2) != 2) { + error = "twist_option: dup: %m"; + } else { + if (request->fd > 2) + close(request->fd); + (void) execl("/bin/sh", "sh", "-c", value, (char *) 0); + error = "twist_option: /bin/sh: %m"; + } + + /* Something went wrong: we MUST terminate the process. */ + + tcpd_warn(error); + clean_exit(request); + } +} + +/* rfc931_option - look up remote user name */ + +static void rfc931_option(value, request) +char *value; +struct request_info *request; +{ + int timeout; + char junk; + + if (value != 0) { + if (sscanf(value, "%d%c", &timeout, &junk) != 1 || timeout <= 0) + tcpd_jump("bad rfc931 timeout: \"%s\"", value); + rfc931_timeout = timeout; + } + (void) eval_user(request); +} + +/* setenv_option - set environment variable */ + +/* ARGSUSED */ + +static void setenv_option(value, request) +char *value; +struct request_info *request; +{ + char *var_value; + + if (*(var_value = value + strcspn(value, whitespace))) + *var_value++ = 0; + if (setenv(chop_string(value), chop_string(var_value), 1)) + tcpd_jump("memory allocation failure"); +} + + /* + * The severity option goes last because it comes with a huge amount of ugly + * #ifdefs and tables. + */ + +struct syslog_names { + char *name; + int value; +}; + +static struct syslog_names log_fac[] = { +#ifdef LOG_KERN + "kern", LOG_KERN, +#endif +#ifdef LOG_USER + "user", LOG_USER, +#endif +#ifdef LOG_MAIL + "mail", LOG_MAIL, +#endif +#ifdef LOG_DAEMON + "daemon", LOG_DAEMON, +#endif +#ifdef LOG_AUTH + "auth", LOG_AUTH, +#endif +#ifdef LOG_LPR + "lpr", LOG_LPR, +#endif +#ifdef LOG_NEWS + "news", LOG_NEWS, +#endif +#ifdef LOG_UUCP + "uucp", LOG_UUCP, +#endif +#ifdef LOG_CRON + "cron", LOG_CRON, +#endif +#ifdef LOG_LOCAL0 + "local0", LOG_LOCAL0, +#endif +#ifdef LOG_LOCAL1 + "local1", LOG_LOCAL1, +#endif +#ifdef LOG_LOCAL2 + "local2", LOG_LOCAL2, +#endif +#ifdef LOG_LOCAL3 + "local3", LOG_LOCAL3, +#endif +#ifdef LOG_LOCAL4 + "local4", LOG_LOCAL4, +#endif +#ifdef LOG_LOCAL5 + "local5", LOG_LOCAL5, +#endif +#ifdef LOG_LOCAL6 + "local6", LOG_LOCAL6, +#endif +#ifdef LOG_LOCAL7 + "local7", LOG_LOCAL7, +#endif + 0, +}; + +static struct syslog_names log_sev[] = { +#ifdef LOG_EMERG + "emerg", LOG_EMERG, +#endif +#ifdef LOG_ALERT + "alert", LOG_ALERT, +#endif +#ifdef LOG_CRIT + "crit", LOG_CRIT, +#endif +#ifdef LOG_ERR + "err", LOG_ERR, +#endif +#ifdef LOG_WARNING + "warning", LOG_WARNING, +#endif +#ifdef LOG_NOTICE + "notice", LOG_NOTICE, +#endif +#ifdef LOG_INFO + "info", LOG_INFO, +#endif +#ifdef LOG_DEBUG + "debug", LOG_DEBUG, +#endif + 0, +}; + +/* severity_map - lookup facility or severity value */ + +static int severity_map(table, name) +struct syslog_names *table; +char *name; +{ + struct syslog_names *t; + + for (t = table; t->name; t++) + if (STR_EQ(t->name, name)) + return (t->value); + tcpd_jump("bad syslog facility or severity: \"%s\"", name); + /* NOTREACHED */ +} + +/* severity_option - change logging severity for this event (Dave Mitchell) */ + +/* ARGSUSED */ + +static void severity_option(value, request) +char *value; +struct request_info *request; +{ + char *level = split_at(value, '.'); + + allow_severity = deny_severity = level ? + severity_map(log_fac, value) | severity_map(log_sev, level) : + severity_map(log_sev, value); +} + +/* get_field - return pointer to next field in string */ + +static char *get_field(string) +char *string; +{ + static char *last = ""; + char *src; + char *dst; + char *ret; + int ch; + + /* + * This function returns pointers to successive fields within a given + * string. ":" is the field separator; warn if the rule ends in one. It + * replaces a "\:" sequence by ":", without treating the result of + * substitution as field terminator. A null argument means resume search + * where the previous call terminated. This function destroys its + * argument. + * + * Work from explicit source or from memory. While processing \: we + * overwrite the input. This way we do not have to maintain buffers for + * copies of input fields. + */ + + src = dst = ret = (string ? string : last); + if (src[0] == 0) + return (0); + + while ((ch = *src)) { + if (ch == ':') { + if (*++src == 0) + tcpd_warn("rule ends in \":\""); + break; + } + if (ch == '\\' && src[1] == ':') + src++; + *dst++ = *src++; + } + last = src; + *dst = 0; + return (ret); +} + +/* chop_string - strip leading and trailing blanks from string */ + +static char *chop_string(string) +register char *string; +{ + char *start = 0; + char *end; + char *cp; + + for (cp = string; *cp; cp++) { + if (!isspace(*cp)) { + if (start == 0) + start = cp; + end = cp; + } + } + return (start ? (end[1] = 0, start) : cp); +} diff --git a/lib/libwrap/percent_m.c b/lib/libwrap/percent_m.c new file mode 100644 index 00000000000..86f531619ea --- /dev/null +++ b/lib/libwrap/percent_m.c @@ -0,0 +1,49 @@ +/* $OpenBSD: percent_m.c,v 1.1 1997/02/26 03:06:54 downsj Exp $ */ + + /* + * Replace %m by system error message. + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) percent_m.c 1.1 94/12/28 17:42:37"; +#else +static char rcsid[] = "$OpenBSD: percent_m.c,v 1.1 1997/02/26 03:06:54 downsj Exp $"; +#endif +#endif + +#include <stdio.h> +#include <stdarg.h> +#include <errno.h> +#include <string.h> + +extern int errno; +#ifndef SYS_ERRLIST_DEFINED +extern char *sys_errlist[]; +extern int sys_nerr; +#endif + +char *percent_m(obuf, ibuf) +char *obuf; +char *ibuf; +{ + char *bp = obuf; + char *cp = ibuf; + + while ((*bp = *cp)) { + if (*cp == '%' && cp[1] == 'm') { + if (errno < sys_nerr && errno > 0) { + strcpy(bp, sys_errlist[errno]); + } else { + sprintf(bp, "Unknown error %d", errno); + } + bp += strlen(bp); + cp += 2; + } else { + bp++, cp++; + } + } + return (obuf); +} diff --git a/lib/libwrap/percent_x.c b/lib/libwrap/percent_x.c new file mode 100644 index 00000000000..96eb5eb8ed9 --- /dev/null +++ b/lib/libwrap/percent_x.c @@ -0,0 +1,91 @@ +/* $OpenBSD: percent_x.c,v 1.1 1997/02/26 03:06:55 downsj Exp $ */ + + /* + * percent_x() takes a string and performs %<char> expansions. It aborts the + * program when the expansion would overflow the output buffer. The result + * of %<char> expansion may be passed on to a shell process. For this + * reason, characters with a special meaning to shells are replaced by + * underscores. + * + * Diagnostics are reported through syslog(3). + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) percent_x.c 1.4 94/12/28 17:42:37"; +#else +static char rcsid[] = "$OpenBSD: percent_x.c,v 1.1 1997/02/26 03:06:55 downsj Exp $"; +#endif +#endif + +/* System libraries. */ + +#include <stdio.h> +#include <syslog.h> +#include <string.h> +#include <unistd.h> + +/* Local stuff. */ + +#include "tcpd.h" + +/* percent_x - do %<char> expansion, abort if result buffer is too small */ + +char *percent_x(result, result_len, string, request) +char *result; +int result_len; +char *string; +struct request_info *request; +{ + char *bp = result; + char *end = result + result_len - 1; /* end of result buffer */ + char *expansion; + int expansion_len; + static char ok_chars[] = "1234567890!@%-_=+:,./\ +abcdefghijklmnopqrstuvwxyz\ +ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + char *str = string; + char *cp; + int ch; + + /* + * Warning: we may be called from a child process or after pattern + * matching, so we cannot use clean_exit() or tcpd_jump(). + */ + + while (*str) { + if (*str == '%' && (ch = str[1]) != 0) { + str += 2; + expansion = + ch == 'a' ? eval_hostaddr(request->client) : + ch == 'A' ? eval_hostaddr(request->server) : + ch == 'c' ? eval_client(request) : + ch == 'd' ? eval_daemon(request) : + ch == 'h' ? eval_hostinfo(request->client) : + ch == 'H' ? eval_hostinfo(request->server) : + ch == 'n' ? eval_hostname(request->client) : + ch == 'N' ? eval_hostname(request->server) : + ch == 'p' ? eval_pid(request) : + ch == 's' ? eval_server(request) : + ch == 'u' ? eval_user(request) : + ch == '%' ? "%" : (tcpd_warn("unrecognized %%%c", ch), ""); + for (cp = expansion; *(cp += strspn(cp, ok_chars)); /* */ ) + *cp = '_'; + expansion_len = cp - expansion; + } else { + expansion = str++; + expansion_len = 1; + } + if (bp + expansion_len >= end) { + tcpd_warn("percent_x: expansion too long: %.30s...", result); + sleep(5); + exit(0); + } + memcpy(bp, expansion, expansion_len); + bp += expansion_len; + } + *bp = 0; + return (result); +} diff --git a/lib/libwrap/refuse.c b/lib/libwrap/refuse.c new file mode 100644 index 00000000000..4860986db5b --- /dev/null +++ b/lib/libwrap/refuse.c @@ -0,0 +1,38 @@ +/* $OpenBSD: refuse.c,v 1.1 1997/02/26 03:06:55 downsj Exp $ */ + + /* + * refuse() reports a refused connection, and takes the consequences: in + * case of a datagram-oriented service, the unread datagram is taken from + * the input queue (or inetd would see the same datagram again and again); + * the program is terminated. + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) refuse.c 1.5 94/12/28 17:42:39"; +#else +static char rcsid[] = "$OpenBSD: refuse.c,v 1.1 1997/02/26 03:06:55 downsj Exp $"; +#endif +#endif + +/* System libraries. */ + +#include <stdio.h> +#include <syslog.h> + +/* Local stuff. */ + +#include "tcpd.h" + +/* refuse - refuse request */ + +void refuse(request) +struct request_info *request; +{ + syslog(deny_severity, "refused connect from %s", eval_client(request)); + clean_exit(request); + /* NOTREACHED */ +} + diff --git a/lib/libwrap/rfc931.c b/lib/libwrap/rfc931.c new file mode 100644 index 00000000000..4bb94294e6c --- /dev/null +++ b/lib/libwrap/rfc931.c @@ -0,0 +1,173 @@ +/* $OpenBSD: rfc931.c,v 1.1 1997/02/26 03:06:56 downsj Exp $ */ + + /* + * rfc931() speaks a common subset of the RFC 931, AUTH, TAP, IDENT and RFC + * 1413 protocols. It queries an RFC 931 etc. compatible daemon on a remote + * host to look up the owner of a connection. The information should not be + * used for authentication purposes. This routine intercepts alarm signals. + * + * Diagnostics are reported through syslog(3). + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) rfc931.c 1.10 95/01/02 16:11:34"; +#else +static char rcsid[] = "$OpenBSD: rfc931.c,v 1.1 1997/02/26 03:06:56 downsj Exp $"; +#endif +#endif + +/* System libraries. */ + +#include <stdio.h> +#include <syslog.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <setjmp.h> +#include <signal.h> +#include <string.h> +#include <unistd.h> + +/* Local stuff. */ + +#include "tcpd.h" + +#define RFC931_PORT 113 /* Semi-well-known port */ +#define ANY_PORT 0 /* Any old port will do */ + +int rfc931_timeout = RFC931_TIMEOUT;/* Global so it can be changed */ + +static jmp_buf timebuf; + +/* fsocket - open stdio stream on top of socket */ + +static FILE *fsocket(domain, type, protocol) +int domain; +int type; +int protocol; +{ + int s; + FILE *fp; + + if ((s = socket(domain, type, protocol)) < 0) { + tcpd_warn("socket: %m"); + return (0); + } else { + if ((fp = fdopen(s, "r+")) == 0) { + tcpd_warn("fdopen: %m"); + close(s); + } + return (fp); + } +} + +/* timeout - handle timeouts */ + +static void timeout(sig) +int sig; +{ + longjmp(timebuf, sig); +} + +/* rfc931 - return remote user name, given socket structures */ + +void rfc931(rmt_sin, our_sin, dest) +struct sockaddr_in *rmt_sin; +struct sockaddr_in *our_sin; +char *dest; +{ + unsigned rmt_port; + unsigned our_port; + struct sockaddr_in rmt_query_sin; + struct sockaddr_in our_query_sin; + char user[256]; /* XXX */ + char buffer[512]; /* XXX */ + char *cp; + char *result = unknown; + FILE *fp; + + /* + * Use one unbuffered stdio stream for writing to and for reading from + * the RFC931 etc. server. This is done because of a bug in the SunOS + * 4.1.x stdio library. The bug may live in other stdio implementations, + * too. When we use a single, buffered, bidirectional stdio stream ("r+" + * or "w+" mode) we read our own output. Such behaviour would make sense + * with resources that support random-access operations, but not with + * sockets. + */ + + if ((fp = fsocket(AF_INET, SOCK_STREAM, 0)) != 0) { + setbuf(fp, (char *) 0); + + /* + * Set up a timer so we won't get stuck while waiting for the server. + */ + + if (setjmp(timebuf) == 0) { + signal(SIGALRM, timeout); + alarm(rfc931_timeout); + + /* + * Bind the local and remote ends of the query socket to the same + * IP addresses as the connection under investigation. We go + * through all this trouble because the local or remote system + * might have more than one network address. The RFC931 etc. + * client sends only port numbers; the server takes the IP + * addresses from the query socket. + */ + + our_query_sin = *our_sin; + our_query_sin.sin_port = htons(ANY_PORT); + rmt_query_sin = *rmt_sin; + rmt_query_sin.sin_port = htons(RFC931_PORT); + + if (bind(fileno(fp), (struct sockaddr *) & our_query_sin, + sizeof(our_query_sin)) >= 0 && + connect(fileno(fp), (struct sockaddr *) & rmt_query_sin, + sizeof(rmt_query_sin)) >= 0) { + + /* + * Send query to server. Neglect the risk that a 13-byte + * write would have to be fragmented by the local system and + * cause trouble with buggy System V stdio libraries. + */ + + fprintf(fp, "%u,%u\r\n", + ntohs(rmt_sin->sin_port), + ntohs(our_sin->sin_port)); + fflush(fp); + + /* + * Read response from server. Use fgets()/sscanf() so we can + * work around System V stdio libraries that incorrectly + * assume EOF when a read from a socket returns less than + * requested. + */ + + if (fgets(buffer, sizeof(buffer), fp) != 0 + && ferror(fp) == 0 && feof(fp) == 0 + && sscanf(buffer, "%u , %u : USERID :%*[^:]:%255s", + &rmt_port, &our_port, user) == 3 + && ntohs(rmt_sin->sin_port) == rmt_port + && ntohs(our_sin->sin_port) == our_port) { + + /* + * Strip trailing carriage return. It is part of the + * protocol, not part of the data. + */ + + cp = strchr(user, '\r'); + if (cp) + *cp = 0; + result = user; + } + } + alarm(0); + } + fclose(fp); + } + STRN_CPY(dest, result, STRING_LENGTH); +} diff --git a/lib/libwrap/scaffold.c b/lib/libwrap/scaffold.c new file mode 100644 index 00000000000..8fab86f24af --- /dev/null +++ b/lib/libwrap/scaffold.c @@ -0,0 +1,219 @@ +/* $OpenBSD: scaffold.c,v 1.1 1997/02/26 03:06:56 downsj Exp $ */ + + /* + * Routines for testing only. Not really industrial strength. + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccs_id[] = "@(#) scaffold.c 1.5 95/01/03 09:13:48"; +#else +static char rcsid[] = "$OpenBSD: scaffold.c,v 1.1 1997/02/26 03:06:56 downsj Exp $"; +#endif +#endif + +/* System libraries. */ + +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <stdio.h> +#include <syslog.h> +#include <setjmp.h> +#include <string.h> + +#ifndef INADDR_NONE +#define INADDR_NONE (-1) /* XXX should be 0xffffffff */ +#endif + +extern char *malloc(); + +/* Application-specific. */ + +#include "tcpd.h" +#include "scaffold.h" + + /* + * These are referenced by the options module and by rfc931.c. + */ +int allow_severity = SEVERITY; +int deny_severity = LOG_WARNING; +int rfc931_timeout = RFC931_TIMEOUT; + +/* dup_hostent - create hostent in one memory block */ + +static struct hostent *dup_hostent(hp) +struct hostent *hp; +{ + struct hostent_block { + struct hostent host; + char *addr_list[1]; + }; + struct hostent_block *hb; + int count; + char *data; + char *addr; + + for (count = 0; hp->h_addr_list[count] != 0; count++) + /* void */ ; + + if ((hb = (struct hostent_block *) malloc(sizeof(struct hostent_block) + + (hp->h_length + sizeof(char *)) * count)) == 0) { + fprintf(stderr, "Sorry, out of memory\n"); + exit(1); + } + memset((char *) &hb->host, 0, sizeof(hb->host)); + hb->host.h_length = hp->h_length; + hb->host.h_addr_list = hb->addr_list; + hb->host.h_addr_list[count] = 0; + data = (char *) (hb->host.h_addr_list + count + 1); + + for (count = 0; (addr = hp->h_addr_list[count]) != 0; count++) { + hb->host.h_addr_list[count] = data + hp->h_length * count; + memcpy(hb->host.h_addr_list[count], addr, hp->h_length); + } + return (&hb->host); +} + +/* find_inet_addr - find all addresses for this host, result to free() */ + +struct hostent *find_inet_addr(host) +char *host; +{ + struct in_addr addr; + struct hostent *hp; + static struct hostent h; + static char *addr_list[2]; + + /* + * Host address: translate it to internal form. + */ + if ((addr.s_addr = dot_quad_addr(host)) != INADDR_NONE) { + h.h_addr_list = addr_list; + h.h_addr_list[0] = (char *) &addr; + h.h_length = sizeof(addr); + return (dup_hostent(&h)); + } + + /* + * Map host name to a series of addresses. Watch out for non-internet + * forms or aliases. The NOT_INADDR() is here in case gethostbyname() has + * been "enhanced" to accept numeric addresses. Make a copy of the + * address list so that later gethostbyXXX() calls will not clobber it. + */ + if (NOT_INADDR(host) == 0) { + tcpd_warn("%s: not an internet address", host); + return (0); + } + if ((hp = gethostbyname(host)) == 0) { + tcpd_warn("%s: host not found", host); + return (0); + } + if (hp->h_addrtype != AF_INET) { + tcpd_warn("%d: not an internet host", hp->h_addrtype); + return (0); + } + if (STR_NE(host, hp->h_name)) { + tcpd_warn("%s: hostname alias", host); + tcpd_warn("(official name: %s)", hp->h_name); + } + return (dup_hostent(hp)); +} + +/* check_dns - give each address thorough workout, return address count */ + +int check_dns(host) +char *host; +{ + struct request_info request; + struct sockaddr_in sin; + struct hostent *hp; + int count; + char *addr; + + if ((hp = find_inet_addr(host)) == 0) + return (0); + request_init(&request, RQ_CLIENT_SIN, &sin, 0); + sock_methods(&request); + memset((char *) &sin, 0, sizeof(sin)); + sin.sin_family = AF_INET; + + for (count = 0; (addr = hp->h_addr_list[count]) != 0; count++) { + memcpy((char *) &sin.sin_addr, addr, sizeof(sin.sin_addr)); + + /* + * Force host name and address conversions. Use the request structure + * as a cache. Detect hostname lookup problems. Any name/name or + * name/address conflicts will be reported while eval_hostname() does + * its job. + */ + request_set(&request, RQ_CLIENT_ADDR, "", RQ_CLIENT_NAME, "", 0); + if (STR_EQ(eval_hostname(request.client), unknown)) + tcpd_warn("host address %s->name lookup failed", + eval_hostaddr(request.client)); + } + free((char *) hp); + return (count); +} + +/* dummy function to intercept the real shell_cmd() */ + +/* ARGSUSED */ + +void shell_cmd(command) +char *command; +{ + if (hosts_access_verbose) + printf("command: %s", command); +} + +/* dummy function to intercept the real clean_exit() */ + +/* ARGSUSED */ + +void clean_exit(request) +struct request_info *request; +{ + exit(0); +} + +/* dummy function to intercept the real rfc931() */ + +/* ARGSUSED */ + +void rfc931(request) +struct request_info *request; +{ + strcpy(request->user, unknown); +} + +/* check_path - examine accessibility */ + +int check_path(path, st) +char *path; +struct stat *st; +{ + struct stat stbuf; + char buf[BUFSIZ]; + + if (stat(path, st) < 0) + return (-1); +#ifdef notdef + if (st->st_uid != 0) + tcpd_warn("%s: not owned by root", path); + if (st->st_mode & 020) + tcpd_warn("%s: group writable", path); +#endif + if (st->st_mode & 002) + tcpd_warn("%s: world writable", path); + if (path[0] == '/' && path[1] != 0) { + strrchr(strcpy(buf, path), '/')[0] = 0; + (void) check_path(buf[0] ? buf : "/", &stbuf); + } + return (0); +} diff --git a/lib/libwrap/scaffold.h b/lib/libwrap/scaffold.h new file mode 100644 index 00000000000..e89a9aa7aa2 --- /dev/null +++ b/lib/libwrap/scaffold.h @@ -0,0 +1,15 @@ +/* $OpenBSD: scaffold.h,v 1.1 1997/02/26 03:06:57 downsj Exp $ */ + + /* + * @(#) scaffold.h 1.3 94/12/31 18:19:19 + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#include <sys/cdefs.h> + +__BEGIN_DECLS +extern struct hostent *find_inet_addr __P((char *)); +extern int check_dns __P((char *)); +extern int check_path __P((char *, struct stat *)); +__END_DECLS diff --git a/lib/libwrap/shell_cmd.c b/lib/libwrap/shell_cmd.c new file mode 100644 index 00000000000..b371f353616 --- /dev/null +++ b/lib/libwrap/shell_cmd.c @@ -0,0 +1,99 @@ +/* $OpenBSD: shell_cmd.c,v 1.1 1997/02/26 03:06:57 downsj Exp $ */ + + /* + * shell_cmd() takes a shell command after %<character> substitutions. The + * command is executed by a /bin/sh child process, with standard input, + * standard output and standard error connected to /dev/null. + * + * Diagnostics are reported through syslog(3). + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) shell_cmd.c 1.5 94/12/28 17:42:44"; +#else +static char rcsid[] = "$OpenBSD: shell_cmd.c,v 1.1 1997/02/26 03:06:57 downsj Exp $"; +#endif +#endif + +/* System libraries. */ + +#include <sys/types.h> +#include <sys/param.h> +#include <sys/wait.h> +#include <signal.h> +#include <stdio.h> +#include <syslog.h> +#include <string.h> +#include <unistd.h> +#include <fcntl.h> + +/* Local stuff. */ + +#include "tcpd.h" + +/* Forward declarations. */ + +static void do_child(); + +/* shell_cmd - execute shell command */ + +void shell_cmd(command) +char *command; +{ + int child_pid; + int wait_pid; + + /* + * Most of the work is done within the child process, to minimize the + * risk of damage to the parent. + */ + + switch (child_pid = fork()) { + case -1: /* error */ + tcpd_warn("cannot fork: %m"); + break; + case 00: /* child */ + do_child(command); + /* NOTREACHED */ + default: /* parent */ + while ((wait_pid = wait((int *) 0)) != -1 && wait_pid != child_pid) + /* void */ ; + } +} + +/* do_child - exec command with { stdin, stdout, stderr } to /dev/null */ + +static void do_child(command) +char *command; +{ + char *error; + int tmp_fd; + + /* + * Systems with POSIX sessions may send a SIGHUP to grandchildren if the + * child exits first. This is sick, sessions were invented for terminals. + */ + + signal(SIGHUP, SIG_IGN); + + /* Set up new stdin, stdout, stderr, and exec the shell command. */ + + for (tmp_fd = 0; tmp_fd < 3; tmp_fd++) + (void) close(tmp_fd); + if (open("/dev/null", O_RDWR) != 0) { + error = "open /dev/null: %m"; + } else if (dup(0) != 1 || dup(0) != 2) { + error = "dup: %m"; + } else { + (void) execl("/bin/sh", "sh", "-c", command, (char *) 0); + error = "execl /bin/sh: %m"; + } + + /* Something went wrong. We MUST terminate the child process. */ + + tcpd_warn(error); + _exit(0); +} diff --git a/lib/libwrap/shlib_version b/lib/libwrap/shlib_version new file mode 100644 index 00000000000..1edea46de91 --- /dev/null +++ b/lib/libwrap/shlib_version @@ -0,0 +1,2 @@ +major=1 +minor=0 diff --git a/lib/libwrap/socket.c b/lib/libwrap/socket.c new file mode 100644 index 00000000000..f1c9795a8b4 --- /dev/null +++ b/lib/libwrap/socket.c @@ -0,0 +1,240 @@ +/* $OpenBSD: socket.c,v 1.1 1997/02/26 03:06:58 downsj Exp $ */ + + /* + * This module determines the type of socket (datagram, stream), the client + * socket address and port, the server socket address and port. In addition, + * it provides methods to map a transport address to a printable host name + * or address. Socket address information results are in static memory. + * + * The result from the hostname lookup method is STRING_PARANOID when a host + * pretends to have someone elses name, or when a host name is available but + * could not be verified. + * + * When lookup or conversion fails the result is set to STRING_UNKNOWN. + * + * Diagnostics are reported through syslog(3). + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) socket.c 1.14 95/01/30 19:51:50"; +#else +static char rcsid[] = "$OpenBSD: socket.c,v 1.1 1997/02/26 03:06:58 downsj Exp $"; +#endif +#endif + +/* System libraries. */ + +#include <sys/types.h> +#include <sys/param.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <stdio.h> +#include <syslog.h> +#include <string.h> + +/* Local stuff. */ + +#include "tcpd.h" + +/* Forward declarations. */ + +static void sock_sink(); + +#ifdef APPEND_DOT + + /* + * Speed up DNS lookups by terminating the host name with a dot. Should be + * done with care. The speedup can give problems with lookups from sources + * that lack DNS-style trailing dot magic, such as local files or NIS maps. + */ + +static struct hostent *gethostbyname_dot(name) +char *name; +{ + char dot_name[MAXHOSTNAMELEN + 1]; + + /* + * Don't append dots to unqualified names. Such names are likely to come + * from local hosts files or from NIS. + */ + + if (strchr(name, '.') == 0 || strlen(name) >= MAXHOSTNAMELEN - 1) { + return (gethostbyname(name)); + } else { + sprintf(dot_name, "%s.", name); + return (gethostbyname(dot_name)); + } +} + +#define gethostbyname gethostbyname_dot +#endif + +/* sock_host - look up endpoint addresses and install conversion methods */ + +void sock_host(request) +struct request_info *request; +{ + static struct sockaddr_in client; + static struct sockaddr_in server; + int len; + char buf[BUFSIZ]; + int fd = request->fd; + + sock_methods(request); + + /* + * Look up the client host address. Hal R. Brand <BRAND@addvax.llnl.gov> + * suggested how to get the client host info in case of UDP connections: + * peek at the first message without actually looking at its contents. We + * really should verify that client.sin_family gets the value AF_INET, + * but this program has already caused too much grief on systems with + * broken library code. + */ + + len = sizeof(client); + if (getpeername(fd, (struct sockaddr *) & client, &len) < 0) { + request->sink = sock_sink; + len = sizeof(client); + if (recvfrom(fd, buf, sizeof(buf), MSG_PEEK, + (struct sockaddr *) & client, &len) < 0) { + tcpd_warn("can't get client address: %m"); + return; /* give up */ + } +#ifdef really_paranoid + memset(buf, 0 sizeof(buf)); +#endif + } + request->client->sin = &client; + + /* + * Determine the server binding. This is used for client username + * lookups, and for access control rules that trigger on the server + * address or name. + */ + + len = sizeof(server); + if (getsockname(fd, (struct sockaddr *) & server, &len) < 0) { + tcpd_warn("getsockname: %m"); + return; + } + request->server->sin = &server; +} + +/* sock_hostaddr - map endpoint address to printable form */ + +void sock_hostaddr(host) +struct host_info *host; +{ + struct sockaddr_in *sin = host->sin; + + if (sin != 0) + STRN_CPY(host->addr, inet_ntoa(sin->sin_addr), sizeof(host->addr)); +} + +/* sock_hostname - map endpoint address to host name */ + +void sock_hostname(host) +struct host_info *host; +{ + struct sockaddr_in *sin = host->sin; + struct hostent *hp; + int i; + + /* + * On some systems, for example Solaris 2.3, gethostbyaddr(0.0.0.0) does + * not fail. Instead it returns "INADDR_ANY". Unfortunately, this does + * not work the other way around: gethostbyname("INADDR_ANY") fails. We + * have to special-case 0.0.0.0, in order to avoid false alerts from the + * host name/address checking code below. + */ + if (sin != 0 && sin->sin_addr.s_addr != 0 + && (hp = gethostbyaddr((char *) &(sin->sin_addr), + sizeof(sin->sin_addr), AF_INET)) != 0) { + + STRN_CPY(host->name, hp->h_name, sizeof(host->name)); + + /* + * Verify that the address is a member of the address list returned + * by gethostbyname(hostname). + * + * Verify also that gethostbyaddr() and gethostbyname() return the same + * hostname, or rshd and rlogind may still end up being spoofed. + * + * On some sites, gethostbyname("localhost") returns "localhost.domain". + * This is a DNS artefact. We treat it as a special case. When we + * can't believe the address list from gethostbyname("localhost") + * we're in big trouble anyway. + */ + + if ((hp = gethostbyname(host->name)) == 0) { + + /* + * Unable to verify that the host name matches the address. This + * may be a transient problem or a botched name server setup. + */ + + tcpd_warn("can't verify hostname: gethostbyname(%s) failed", + host->name); + + } else if (STR_NE(host->name, hp->h_name) + && STR_NE(host->name, "localhost")) { + + /* + * The gethostbyaddr() and gethostbyname() calls did not return + * the same hostname. This could be a nameserver configuration + * problem. It could also be that someone is trying to spoof us. + */ + + tcpd_warn("host name/name mismatch: %s != %s", + host->name, hp->h_name); + + } else { + + /* + * The address should be a member of the address list returned by + * gethostbyname(). We should first verify that the h_addrtype + * field is AF_INET, but this program has already caused too much + * grief on systems with broken library code. + */ + + for (i = 0; hp->h_addr_list[i]; i++) { + if (memcmp(hp->h_addr_list[i], + (char *) &sin->sin_addr, + sizeof(sin->sin_addr)) == 0) + return; /* name is good, keep it */ + } + + /* + * The host name does not map to the initial address. Perhaps + * someone has messed up. Perhaps someone compromised a name + * server. + */ + + tcpd_warn("host name/address mismatch: %s != %s", + inet_ntoa(sin->sin_addr), hp->h_name); + } + strcpy(host->name, paranoid); /* name is bad, clobber it */ + } +} + +/* sock_sink - absorb unreceived IP datagram */ + +static void sock_sink(fd) +int fd; +{ + char buf[BUFSIZ]; + struct sockaddr_in sin; + int size = sizeof(sin); + + /* + * Eat up the not-yet received datagram. Some systems insist on a + * non-zero source address argument in the recvfrom() call below. + */ + + (void) recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *) & sin, &size); +} diff --git a/lib/libwrap/tcpd.h b/lib/libwrap/tcpd.h new file mode 100644 index 00000000000..aa6bd16d7f3 --- /dev/null +++ b/lib/libwrap/tcpd.h @@ -0,0 +1,221 @@ +/* $OpenBSD: tcpd.h,v 1.1 1997/02/26 03:06:58 downsj Exp $ */ + +/* + * Copyright (c) 1997, Jason Downs. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + /* + * @(#) tcpd.h 1.5 96/03/19 16:22:24 + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef _TCPD_H_ +#define _TCPD_H_ + +#include <sys/cdefs.h> + +/* Structure to describe one communications endpoint. */ + +#define STRING_LENGTH 128 /* hosts, users, processes */ + +struct host_info { + char name[STRING_LENGTH]; /* access via eval_hostname(host) */ + char addr[STRING_LENGTH]; /* access via eval_hostaddr(host) */ + struct sockaddr_in *sin; /* socket address or 0 */ + struct t_unitdata *unit; /* TLI transport address or 0 */ + struct request_info *request; /* for shared information */ +}; + +/* Structure to describe what we know about a service request. */ + +struct request_info { + int fd; /* socket handle */ + char user[STRING_LENGTH]; /* access via eval_user(request) */ + char daemon[STRING_LENGTH]; /* access via eval_daemon(request) */ + char pid[10]; /* access via eval_pid(request) */ + struct host_info client[1]; /* client endpoint info */ + struct host_info server[1]; /* server endpoint info */ + void (*sink) (); /* datagram sink function or 0 */ + void (*hostname) (); /* address to printable hostname */ + void (*hostaddr) (); /* address to printable address */ + void (*cleanup) (); /* cleanup function or 0 */ + struct netconfig *config; /* netdir handle */ +}; + +/* Common string operations. Less clutter should be more readable. */ + +#define STRN_CPY(d,s,l) { strncpy((d),(s),(l)); (d)[(l)-1] = 0; } + +#define STRN_EQ(x,y,l) (strncasecmp((x),(y),(l)) == 0) +#define STRN_NE(x,y,l) (strncasecmp((x),(y),(l)) != 0) +#define STR_EQ(x,y) (strcasecmp((x),(y)) == 0) +#define STR_NE(x,y) (strcasecmp((x),(y)) != 0) + + /* + * Initially, all above strings have the empty value. Information that + * cannot be determined at runtime is set to "unknown", so that we can + * distinguish between `unavailable' and `not yet looked up'. A hostname + * that we do not believe in is set to "paranoid". + */ + +#define STRING_UNKNOWN "unknown" /* lookup failed */ +#define STRING_PARANOID "paranoid" /* hostname conflict */ + +__BEGIN_DECLS +extern char unknown[]; +extern char paranoid[]; +__END_DECLS + +#define HOSTNAME_KNOWN(s) (STR_NE((s),unknown) && STR_NE((s),paranoid)) + +#define NOT_INADDR(s) (s[strspn(s,"01234567890./")] != 0) + +/* Global functions. */ + +#define fromhost sock_host /* no TLI support needed */ + +__BEGIN_DECLS +extern int hosts_access __P((struct request_info *)); +extern void shell_cmd __P((char *)); +extern char *percent_m __P((char *, char *)); +extern char *percent_x __P((char *, int, char *, struct request_info *)); +extern void rfc931 __P((struct sockaddr_in *, struct sockaddr_in *, char *)); +extern void clean_exit __P((struct request_info *)); +extern void refuse __P((struct request_info *)); +extern char *xgets __P((char *, int, FILE *)); +extern char *split_at __P((char *, int)); +extern unsigned long dot_quad_addr __P((char *)); + +/* Global variables. */ + +extern int allow_severity; /* for connection logging */ +extern int deny_severity; /* for connection logging */ +extern char *hosts_allow_table; /* for verification mode redirection */ +extern char *hosts_deny_table; /* for verification mode redirection */ +extern int hosts_access_verbose; /* for verbose matching mode */ +extern int rfc931_timeout; /* user lookup timeout */ +extern int resident; /* > 0 if resident process */ + + /* + * Routines for controlled initialization and update of request structure + * attributes. Each attribute has its own key. + */ + +extern struct request_info *request_init __P((struct request_info *, ...)); +extern struct request_info *request_set __P((struct request_info *, ...)); + +#define RQ_FILE 1 /* file descriptor */ +#define RQ_DAEMON 2 /* server process (argv[0]) */ +#define RQ_USER 3 /* client user name */ +#define RQ_CLIENT_NAME 4 /* client host name */ +#define RQ_CLIENT_ADDR 5 /* client host address */ +#define RQ_CLIENT_SIN 6 /* client endpoint (internal) */ +#define RQ_SERVER_NAME 7 /* server host name */ +#define RQ_SERVER_ADDR 8 /* server host address */ +#define RQ_SERVER_SIN 9 /* server endpoint (internal) */ + + /* + * Routines for delayed evaluation of request attributes. Each attribute + * type has its own access method. The trivial ones are implemented by + * macros. The other ones are wrappers around the transport-specific host + * name, address, and client user lookup methods. The request_info and + * host_info structures serve as caches for the lookup results. + */ + +extern char *eval_user __P((struct request_info *)); +extern char *eval_hostname __P((struct host_info *)); +extern char *eval_hostaddr __P((struct host_info *)); +extern char *eval_hostinfo __P((struct host_info *)); +extern char *eval_client __P((struct request_info *)); +extern char *eval_server __P((struct request_info *)); +#define eval_daemon(r) ((r)->daemon) /* daemon process name */ +#define eval_pid(r) ((r)->pid) /* process id */ + +/* Socket-specific methods, including DNS hostname lookups. */ + +extern void sock_host __P((struct request_info *)); +extern void sock_hostname __P((struct host_info *)); +extern void sock_hostaddr __P((struct host_info *)); +#define sock_methods(r) \ + { (r)->hostname = sock_hostname; (r)->hostaddr = sock_hostaddr; } + + /* + * Problem reporting interface. Additional file/line context is reported + * when available. The jump buffer (tcpd_buf) is not declared here, or + * everyone would have to include <setjmp.h>. + */ + +extern void tcpd_warn __P((char *, ...)); +extern void tcpd_jump __P((char *, ...)); +__END_DECLS + +struct tcpd_context { + char *file; /* current file */ + int line; /* current line */ +}; + +__BEGIN_DECLS +extern struct tcpd_context tcpd_context; + + /* + * While processing access control rules, error conditions are handled by + * jumping back into the hosts_access() routine. This is cleaner than + * checking the return value of each and every silly little function. The + * (-1) returns are here because zero is already taken by longjmp(). + */ + +#define AC_PERMIT 1 /* permit access */ +#define AC_DENY (-1) /* deny_access */ +#define AC_ERROR AC_DENY /* XXX */ + + /* + * In verification mode an option function should just say what it would do, + * instead of really doing it. An option function that would not return + * should clear the dry_run flag to inform the caller of this unusual + * behavior. + */ + +extern void process_options __P((char *, struct request_info *)); +extern int dry_run; /* verification flag */ +__END_DECLS + + + /* + * What follows is an attempt to unify varargs.h and stdarg.h. I'd rather + * have this than #ifdefs all over the code. + * + * The code using these must include the proper system header. + */ + +#ifdef __STDC__ +#define VARARGS(func,type,arg) func(type arg, ...) +#define VASTART(ap,type,name) va_start(ap,name) +#define VAEND(ap) va_end(ap) +#else +#define VARARGS(func,type,arg) func(va_alist) va_dcl +#define VASTART(ap,type,name) {type name; va_start(ap); name = va_arg(ap, type) +#define VAEND(ap) va_end(ap);} +#endif + +#endif /* _TCPD_H_ */ diff --git a/lib/libwrap/update.c b/lib/libwrap/update.c new file mode 100644 index 00000000000..d8eca07d3e0 --- /dev/null +++ b/lib/libwrap/update.c @@ -0,0 +1,126 @@ +/* $OpenBSD: update.c,v 1.1 1997/02/26 03:06:59 downsj Exp $ */ + + /* + * Routines for controlled update/initialization of request structures. + * + * request_init() initializes its argument. Pointers and string-valued members + * are initialized to zero, to indicate that no lookup has been attempted. + * + * request_set() adds information to an already initialized request structure. + * + * Both functions take a variable-length name-value list. + * + * Diagnostics are reported through syslog(3). + * + * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#) update.c 1.1 94/12/28 17:42:56"; +#else +static char rcsid[] = "$OpenBSD: update.c,v 1.1 1997/02/26 03:06:59 downsj Exp $"; +#endif +#endif + +/* System libraries */ + +#include <stdio.h> +#include <stdarg.h> +#include <syslog.h> +#include <string.h> +#include <unistd.h> + +/* Local stuff. */ + +#include "tcpd.h" + +/* request_fill - request update engine */ + +static struct request_info *request_fill(request, ap) +struct request_info *request; +va_list ap; +{ + int key; + char *ptr; + + while ((key = va_arg(ap, int)) > 0) { + switch (key) { + default: + tcpd_warn("request_fill: invalid key: %d", key); + return (request); + case RQ_FILE: + request->fd = va_arg(ap, int); + continue; + case RQ_CLIENT_SIN: + request->client->sin = va_arg(ap, struct sockaddr_in *); + continue; + case RQ_SERVER_SIN: + request->server->sin = va_arg(ap, struct sockaddr_in *); + continue; + + /* + * All other fields are strings with the same maximal length. + */ + + case RQ_DAEMON: + ptr = request->daemon; + break; + case RQ_USER: + ptr = request->user; + break; + case RQ_CLIENT_NAME: + ptr = request->client->name; + break; + case RQ_CLIENT_ADDR: + ptr = request->client->addr; + break; + case RQ_SERVER_NAME: + ptr = request->server->name; + break; + case RQ_SERVER_ADDR: + ptr = request->server->addr; + break; + } + STRN_CPY(ptr, va_arg(ap, char *), STRING_LENGTH); + } + return (request); +} + +/* request_init - initialize request structure */ + +struct request_info *VARARGS(request_init, struct request_info *, request) +{ + static struct request_info default_info; + struct request_info *r; + va_list ap; + + /* + * Initialize data members. We do not assign default function pointer + * members, to avoid pulling in the whole socket module when it is not + * really needed. + */ + VASTART(ap, struct request_info *, request); + *request = default_info; + request->fd = -1; + strcpy(request->daemon, unknown); + sprintf(request->pid, "%d", getpid()); + request->client->request = request; + request->server->request = request; + r = request_fill(request, ap); + VAEND(ap); + return (r); +} + +/* request_set - update request structure */ + +struct request_info *VARARGS(request_set, struct request_info *, request) +{ + struct request_info *r; + va_list ap; + + VASTART(ap, struct request_info *, request); + r = request_fill(request, ap); + VAEND(ap); + return (r); +} |