1 const char filters_rcs[] = "$Id: filters.c,v 1.16 2001/06/07 23:10:26 jongfoster Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/filters.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `acl_addr', `add_stats', `block_acl', `block_imageurl',
9 * `block_url', `url_actions', `domaincmp', `dsplit',
10 * `filter_popups', `forward_url', 'redirect_url',
11 * `ij_untrusted_url', `intercept_url', `re_process_buffer',
12 * `show_proxy_args', 'ijb_send_banner', and `trust_url'
14 * Copyright : Written by and Copyright (C) 2001 the SourceForge
15 * IJBSWA team. http://ijbswa.sourceforge.net
17 * Based on the Internet Junkbuster originally written
18 * by and Copyright (C) 1997 Anonymous Coders and
19 * Junkbusters Corporation. http://www.junkbusters.com
21 * This program is free software; you can redistribute it
22 * and/or modify it under the terms of the GNU General
23 * Public License as published by the Free Software
24 * Foundation; either version 2 of the License, or (at
25 * your option) any later version.
27 * This program is distributed in the hope that it will
28 * be useful, but WITHOUT ANY WARRANTY; without even the
29 * implied warranty of MERCHANTABILITY or FITNESS FOR A
30 * PARTICULAR PURPOSE. See the GNU General Public
31 * License for more details.
33 * The GNU General Public License should be included with
34 * this file. If not, you can view it at
35 * http://www.gnu.org/copyleft/gpl.html
36 * or write to the Free Software Foundation, Inc., 59
37 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
41 * Revision 1.16 2001/06/07 23:10:26 jongfoster
42 * Allowing unanchored domain patterns to back off and retry
43 * if they partially match. Optimized right-anchored patterns.
44 * Moving ACL and forward files into config file.
45 * Replacing struct gateway with struct forward_spec
47 * Revision 1.15 2001/06/03 19:12:00 oes
48 * extracted-CGI relevant stuff
50 * Revision 1.15 2001/06/03 11:03:48 oes
57 * adapted to new enlist_unique arg format
61 * introduced confdir option
63 * filters.c filtrers.h
65 * extracted-CGI relevant stuff
73 * support for new cgi mechansim
77 * functions for new list type: "map"
78 * extended enlist_unique
85 * deleted const struct interceptors
93 * added struct http_response
94 * changes struct interceptors to struct cgi_dispatcher
95 * moved HTML stuff to cgi.h
104 * Revision 1.14 2001/06/01 10:30:55 oes
105 * Added optional left-anchoring to domaincmp
107 * Revision 1.13 2001/05/31 21:21:30 jongfoster
108 * Permissionsfile / actions file changes:
109 * - Changed "permission" to "action" throughout
110 * - changes to file format to allow string parameters
111 * - Moved helper functions to actions.c
113 * Revision 1.12 2001/05/31 17:35:20 oes
115 * - Enhanced domain part globbing with infix and prefix asterisk
116 * matching and optional unanchored operation
118 * Revision 1.11 2001/05/29 11:53:23 oes
119 * "See why" link added to "blocked" page
121 * Revision 1.10 2001/05/29 09:50:24 jongfoster
122 * Unified blocklist/imagelist/permissionslist.
123 * File format is still under discussion, but the internal changes
126 * Also modified interceptor behaviour:
127 * - We now intercept all URLs beginning with one of the following
128 * prefixes (and *only* these prefixes):
130 * * http://ijbswa.sf.net/config/
131 * * http://ijbswa.sourceforge.net/config/
132 * - New interceptors "home page" - go to http://i.j.b/ to see it.
133 * - Internal changes so that intercepted and fast redirect pages
134 * are not replaced with an image.
135 * - Interceptors now have the option to send a binary page direct
136 * to the client. (i.e. ijb-send-banner uses this)
137 * - Implemented show-url-info interceptor. (Which is why I needed
138 * the above interceptors changes - a typical URL is
139 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
140 * The previous mechanism would not have intercepted that, and
141 * if it had been intercepted then it then it would have replaced
144 * Revision 1.9 2001/05/27 22:17:04 oes
146 * - re_process_buffer no longer writes the modified buffer
147 * to the client, which was very ugly. It now returns the
148 * buffer, which it is then written by chat.
150 * - content_length now adjusts the Content-Length: header
151 * for modified documents rather than crunch()ing it.
152 * (Length info in csp->content_length, which is 0 for
153 * unmodified documents)
155 * - For this to work, sed() is called twice when filtering.
157 * Revision 1.8 2001/05/26 17:13:28 jongfoster
158 * Filled in a function comment.
160 * Revision 1.7 2001/05/26 15:26:15 jongfoster
161 * ACL feature now provides more security by immediately dropping
162 * connections from untrusted hosts.
164 * Revision 1.6 2001/05/26 00:28:36 jongfoster
165 * Automatic reloading of config file.
166 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
167 * Most of the global variables have been moved to a new
168 * struct configuration_spec, accessed through csp->config->globalname
169 * Most of the globals remaining are used by the Win32 GUI.
171 * Revision 1.5 2001/05/25 22:34:30 jongfoster
174 * Revision 1.4 2001/05/22 18:46:04 oes
176 * - Enabled filtering banners by size rather than URL
177 * by adding patterns that replace all standard banner
178 * sizes with the "Junkbuster" gif to the re_filterfile
180 * - Enabled filtering WebBugs by providing a pattern
181 * which kills all 1x1 images
183 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
184 * which is selected by the (nonstandard and therefore
185 * capital) letter 'U' in the option string.
186 * It causes the quantifiers to be ungreedy by default.
187 * Appending a ? turns back to greedy (!).
189 * - Added a new interceptor ijb-send-banner, which
190 * sends back the "Junkbuster" gif. Without imagelist or
191 * MSIE detection support, or if tinygif = 1, or the
192 * URL isn't recognized as an imageurl, a lame HTML
193 * explanation is sent instead.
195 * - Added new feature, which permits blocking remote
196 * script redirects and firing back a local redirect
198 * The feature is conditionally compiled, i.e. it
199 * can be disabled with --disable-fast-redirects,
200 * plus it must be activated by a "fast-redirects"
201 * line in the config file, has its own log level
202 * and of course wants to be displayed by show-proxy-args
203 * Note: Boy, all the #ifdefs in 1001 locations and
204 * all the fumbling with configure.in and acconfig.h
205 * were *way* more work than the feature itself :-(
207 * - Because a generic redirect template was needed for
208 * this, tinygif = 3 now uses the same.
210 * - Moved GIFs, and other static HTTP response templates
215 * - Removed some >400 CRs again (Jon, you really worked
218 * Revision 1.3 2001/05/20 16:44:47 jongfoster
219 * Removing last hardcoded JunkBusters.com URLs.
221 * Revision 1.2 2001/05/20 01:21:20 jongfoster
222 * Version 2.9.4 checkin.
223 * - Merged popupfile and cookiefile, and added control over PCRS
224 * filtering, in new "permissionsfile".
225 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
226 * file error you now get a message box (in the Win32 GUI) rather
227 * than the program exiting with no explanation.
228 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
230 * - Removed tabs from "config"
231 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
232 * - Bumped up version number.
234 * Revision 1.1.1.1 2001/05/15 13:58:52 oes
235 * Initial import of version 2.9.3 source tree
238 *********************************************************************/
244 #include <sys/types.h>
251 #include <netinet/in.h>
253 #include <winsock2.h>
260 #include "showargs.h"
264 #include "jbsockets.h"
266 #include "jbsockets.h"
267 #include "miscutil.h"
275 const char filters_h_rcs[] = FILTERS_H_VERSION;
277 /* Fix a problem with Solaris. There should be no effect on other
279 * Solaris's isspace() is a macro which uses it's argument directly
280 * as an array index. Therefore we need to make sure that high-bit
281 * characters generate +ve values, and ideally we also want to make
282 * the argument match the declared parameter type of "int".
284 #define ijb_isdigit(__X) isdigit((int)(unsigned char)(__X))
288 /*********************************************************************
290 * Function : block_acl
292 * Description : Block this request?
293 * Decide yes or no based on ACL file.
296 * 1 : dst = The proxy or gateway address this is going to.
297 * Or NULL to check all possible targets.
298 * 2 : csp = Current client state (buffers, headers, etc...)
299 * Also includes the client IP address.
301 * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
303 *********************************************************************/
304 int block_acl(struct access_control_addr *dst,
305 struct client_state *csp)
307 struct access_control_list *acl = csp->config->acl;
309 /* if not using an access control list, then permit the connection */
315 /* search the list */
318 if ((csp->ip_addr_long & acl->src->mask) == acl->src->addr)
322 /* Just want to check if they have any access */
323 if (acl->action == ACL_PERMIT)
328 else if ( ((dst->addr & acl->dst->mask) == acl->dst->addr)
329 && ((dst->port == acl->dst->port) || (acl->dst->port == 0)))
331 if (acl->action == ACL_PERMIT)
349 /*********************************************************************
351 * Function : acl_addr
353 * Description : Called from `load_aclfile' to parse an ACL address.
356 * 1 : aspec = String specifying ACL address.
357 * 2 : aca = struct access_control_addr to fill in.
359 * Returns : 0 => Ok, everything else is an error.
361 *********************************************************************/
362 int acl_addr(char *aspec, struct access_control_addr *aca)
364 int i, masklength, port;
370 if ((p = strchr(aspec, '/')))
374 if (ijb_isdigit(*p) == 0)
378 masklength = atoi(p);
381 if ((masklength < 0) || (masklength > 32))
386 if ((p = strchr(aspec, ':')))
390 if (ijb_isdigit(*p) == 0)
399 aca->addr = ntohl(resolve_hostname_to_ip(aspec));
403 log_error(LOG_LEVEL_ERROR, "can't resolve address for %s", aspec);
407 /* build the netmask */
409 for (i=1; i <= masklength ; i++)
411 aca->mask |= (1 << (32 - i));
414 /* now mask off the host portion of the ip address
415 * (i.e. save on the network portion of the address).
417 aca->addr = aca->addr & aca->mask;
422 #endif /* def ACL_FILES */
425 /*********************************************************************
427 * Function : block_url
429 * Description : Called from `chat'. Check to see if we need to block this.
432 * 1 : http = http_request request to "check" for blocked
433 * 2 : csp = Current client state (buffers, headers, etc...)
435 * Returns : NULL => unblocked, else string to HTML block description.
437 *********************************************************************/
438 char *block_url(struct http_request *http, struct client_state *csp)
444 if ((csp->action->flags & ACTION_BLOCK) == 0)
452 #endif /* def FORCE_LOAD */
455 n += factor * strlen(http->hostport);
456 n += factor * strlen(http->path);
458 p = (char *)malloc(n);
461 sprintf(p, CBLOCK, http->hostport, http->path, http->hostport, http->path,
462 http->hostport, http->path);
464 sprintf(p, CBLOCK, http->hostport, http->path, http->hostport, http->path);
465 #endif /* def FORCE_LOAD */
472 #ifdef IMAGE_BLOCKING
473 /*********************************************************************
475 * Function : block_imageurl
477 * Description : Given a URL which is blocked, decide whether to
478 * send the "blocked" image or HTML.
481 * 1 : http = URL to check.
482 * 2 : csp = Current client state (buffers, headers, etc...)
484 * Returns : True (nonzero) if URL is in image list, false (0)
487 *********************************************************************/
488 int block_imageurl(struct http_request *http, struct client_state *csp)
490 #ifdef DETECT_MSIE_IMAGES
491 if ((csp->accept_types
492 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
493 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE))
497 else if ((csp->accept_types
498 & (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_IMAGE|ACCEPT_TYPE_MSIE_HTML))
499 == (ACCEPT_TYPE_IS_MSIE|ACCEPT_TYPE_MSIE_HTML))
505 return ((csp->action->flags & ACTION_IMAGE) != 0);
507 #endif /* def IMAGE_BLOCKING */
511 /*********************************************************************
513 * Function : trust_url
515 * Description : Should we "trust" this URL? See "trustfile" line in config.
518 * 1 : http = http_request request for requested URL
519 * 2 : csp = Current client state (buffers, headers, etc...)
521 * Returns : NULL => trusted, else string to HTML "untrusted" description.
523 *********************************************************************/
524 char *trust_url(struct http_request *http, struct client_state *csp)
526 struct file_list *fl;
527 struct block_spec *b;
528 struct url_spec url[1], **tl, *t;
530 char *hostport, *path, *refer;
531 struct http_request rhttp[1];
534 if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
539 *url = dsplit(http->host);
541 /* if splitting the domain fails, punt */
542 if (url->dbuf == NULL) return(NULL);
544 memset(rhttp, '\0', sizeof(*rhttp));
546 for (b = b->next; b ; b = b->next)
548 if ((b->url->port == 0) || (b->url->port == http->port))
550 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
552 if ((b->url->path == NULL) ||
554 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
556 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
563 if (b->reject == 0) return(NULL);
565 hostport = url_encode(http->hostport);
566 path = url_encode(http->path);
570 refer = url_encode(csp->referrer);
574 refer = url_encode("undefined");
578 n += strlen(hostport);
582 p = (char *)malloc(n);
584 sprintf(p, CTRUST, hostport, path, refer);
599 if ((csp->referrer == NULL)|| (strlen(csp->referrer) <= 9))
601 /* no referrer was supplied */
602 goto trust_url_not_trusted;
605 /* forge a URL from the referrer so we can use
606 * convert_url() to parse it into its components.
610 p = strsav(p, "GET ");
611 p = strsav(p, csp->referrer + 9); /* skip over "Referer: " */
612 p = strsav(p, " HTTP/1.0");
614 parse_http_request(p, rhttp, csp);
616 if (rhttp->cmd == NULL)
619 goto trust_url_not_trusted;
624 *url = dsplit(rhttp->host);
626 /* if splitting the domain fails, punt */
627 if (url->dbuf == NULL) goto trust_url_not_trusted;
629 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
631 if ((t->port == 0) || (t->port == rhttp->port))
633 if ((t->domain[0] == '\0') || domaincmp(t, url) == 0)
635 if ((t->path == NULL) ||
637 (regexec(t->preg, rhttp->path, 0, NULL, 0) == 0)
639 (strncmp(t->path, rhttp->path, t->pathlen) == 0)
643 /* if the URL's referrer is from a trusted referrer, then
644 * add the target spec to the trustfile as an unblocked
645 * domain and return NULL (which means it's OK).
653 if ((fp = fopen(csp->config->trustfile, "a")))
658 h = strsav(h, http->hostport);
664 /* since this path points into a user's home space
665 * be sure to include this spec in the trustfile.
667 if ((p = strchr(p, '/')))
670 h = strsav(h, http->path);
675 free_http_request(rhttp);
677 fprintf(fp, "%s\n", h);
687 trust_url_not_trusted:
688 free_http_request(rhttp);
690 hostport = url_encode(http->hostport);
691 path = url_encode(http->path);
695 refer = url_encode(csp->referrer);
699 refer = url_encode("undefined");
703 n += strlen(hostport);
707 p = (char *)malloc(n);
708 sprintf(p, CTRUST, hostport, path, refer);
717 #endif /* def TRUST_FILES */
721 /*********************************************************************
723 * Function : re_process_buffer
725 * Description : Apply all jobs from the joblist (aka. Perl regexp's) to
726 * the text buffer that's been accumulated in csp->iob->buf
727 * and set csp->content_length to the modified size.
730 * 1 : csp = Current client state (buffers, headers, etc...)
732 * Returns : a pointer to the (newly allocated) modified buffer.
735 *********************************************************************/
736 char *re_process_buffer(struct client_state *csp)
739 int size = csp->iob->eod - csp->iob->cur;
740 char *old=csp->iob->cur, *new = NULL;
741 pcrs_job *job, *joblist;
743 struct file_list *fl;
744 struct re_filterfile_spec *b;
746 /* Sanity first ;-) */
752 if ( ( NULL == (fl = csp->rlist) ) || ( NULL == (b = fl->f) ) )
754 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
758 joblist = b->joblist;
761 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s%s (size %d) ...",
762 csp->http->hostport, csp->http->path, size);
764 /* Apply all jobs from the joblist */
765 for (job = joblist; NULL != job; job = job->next)
767 hits += pcrs_exec_substitution(job, old, size, &new, &size);
768 if (old != csp->iob->cur) free(old);
772 log_error(LOG_LEVEL_RE_FILTER, " produced %d hits (new size %d).", hits, size);
774 csp->content_length = size;
776 /* fwiw, reset the iob */
781 #endif /* def PCRS */
784 /*********************************************************************
786 * Function : url_actions
788 * Description : Gets the actions for this URL.
791 * 1 : http = http_request request for blocked URLs
792 * 2 : csp = Current client state (buffers, headers, etc...)
796 *********************************************************************/
797 void url_actions(struct http_request *http,
798 struct client_state *csp)
800 struct file_list *fl;
801 struct url_actions *b;
803 init_current_action(csp->action);
805 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
810 apply_url_actions(csp->action, http, b);
814 /*********************************************************************
816 * Function : apply_url_actions
818 * Description : Applies a list of URL actions.
821 * 1 : action = Destination.
822 * 2 : http = Current URL
823 * 3 : b = list of URL actions to apply
827 *********************************************************************/
828 void apply_url_actions(struct current_action_spec *action,
829 struct http_request *http,
830 struct url_actions *b)
832 struct url_spec url[1];
836 /* Should never happen */
840 *url = dsplit(http->host);
842 /* if splitting the domain fails, punt */
843 if (url->dbuf == NULL)
848 for (b = b->next; NULL != b; b = b->next)
850 if ((b->url->port == 0) || (b->url->port == http->port))
852 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
854 if ((b->url->path == NULL) ||
856 (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
858 (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
862 merge_current_action(action, b->action);
873 /*********************************************************************
875 * Function : forward_url
877 * Description : Should we forward this to another proxy?
880 * 1 : http = http_request request for current URL
881 * 2 : csp = Current client state (buffers, headers, etc...)
883 * Returns : Pointer to forwarding information.
885 *********************************************************************/
886 const struct forward_spec * forward_url(struct http_request *http,
887 struct client_state *csp)
889 static const struct forward_spec fwd_default[1] = { 0 }; /* All zeroes */
890 struct forward_spec *fwd = csp->config->forward;
891 struct url_spec url[1];
898 *url = dsplit(http->host);
900 /* if splitting the domain fails, punt */
901 if (url->dbuf == NULL)
908 if ((fwd->url->port == 0) || (fwd->url->port == http->port))
910 if ((fwd->url->domain[0] == '\0') || (domaincmp(fwd->url, url) == 0))
912 if ((fwd->url->path == NULL) ||
914 (regexec(fwd->url->preg, http->path, 0, NULL, 0) == 0)
916 (strncmp(fwd->url->path, http->path, fwd->url->pathlen) == 0)
936 /*********************************************************************
940 * Description : Takes a domain and returns a pointer to a url_spec
941 * structure populated with dbuf, dcnt and dvec. The
942 * other fields in the structure that is returned are zero.
945 * 1 : domain = a URL address
947 * Returns : url_spec structure populated with dbuf, dcnt and dvec.
949 *********************************************************************/
950 struct url_spec dsplit(char *domain)
952 struct url_spec ret[1];
953 char *v[BUFFER_SIZE];
957 memset(ret, '\0', sizeof(*ret));
959 if (domain[strlen(domain) - 1] == '.')
961 ret->unanchored |= ANCHOR_RIGHT;
963 if (domain[0] == '.')
965 ret->unanchored |= ANCHOR_LEFT;
968 ret->dbuf = strdup(domain);
970 /* map to lower case */
971 for (p = ret->dbuf; *p ; p++) *p = tolower(*p);
973 /* split the domain name into components */
974 ret->dcnt = ssplit(ret->dbuf, ".", v, SZ(v), 1, 1);
978 memset(ret, '\0', sizeof(ret));
982 /* save a copy of the pointers in dvec */
983 size = ret->dcnt * sizeof(*ret->dvec);
985 if ((ret->dvec = (char **)malloc(size)))
987 memcpy(ret->dvec, v, size);
996 /*********************************************************************
998 * Function : simple_domaincmp
1000 * Description : Domain-wise Compare fqdn's. The comparison is
1001 * both left- and right-anchored. The individual
1002 * domain names are compared with trivialmatch().
1003 * This is only used by domaincmp.
1006 * 1 : pv = array of patterns to compare
1007 * 2 : fv = array of domain components to compare
1008 * 3 : len = length of the arrays (both arrays are the
1009 * same length - if they weren't, it couldn't
1010 * possibly be a match).
1012 * Returns : 0 => domains are equivalent, else no match.
1014 *********************************************************************/
1015 static int simple_domaincmp(char **pv, char **fv, int len)
1019 for (n = 0; n < len; n++)
1021 if (simplematch(pv[n], fv[n]))
1031 /*********************************************************************
1033 * Function : domaincmp
1035 * Description : Domain-wise Compare fqdn's. Governed by the bimap in
1036 * pattern->unachored, the comparison is un-, left-,
1037 * right-anchored, or both.
1038 * The individual domain names are compared with
1042 * 1 : pattern = a domain that may contain a '*' as a wildcard.
1043 * 2 : fqdn = domain name against which the patterns are compared.
1045 * Returns : 0 => domains are equivalent, else no match.
1047 *********************************************************************/
1048 int domaincmp(struct url_spec *pattern, struct url_spec *fqdn)
1050 char **pv, **fv; /* vectors */
1052 int unanchored = pattern->unanchored & (ANCHOR_RIGHT | ANCHOR_LEFT);
1054 plen = pattern->dcnt;
1059 /* fqdn is too short to match this pattern */
1066 if (unanchored == ANCHOR_LEFT)
1071 * Convert this into a fully anchored pattern with
1072 * the fqdn and pattern the same length
1074 fv += (flen - plen); /* flen - plen >= 0 due to check above */
1075 return simple_domaincmp(pv, fv, plen);
1077 else if (unanchored == 0)
1079 /* Fully anchored, check length */
1084 return simple_domaincmp(pv, fv, plen);
1086 else if (unanchored == ANCHOR_RIGHT)
1088 /* Left anchored, ignore all extra in fqdn */
1089 return simple_domaincmp(pv, fv, plen);
1095 int maxn = flen - plen;
1096 for (n = 0; n <= maxn; n++)
1098 if (!simple_domaincmp(pv, fv, plen))
1103 * Doesn't match from start of fqdn
1104 * Try skipping first part of fqdn