2 // $Id: spam.php,v 1.70 2006/12/16 01:55:15 henoheno Exp $
3 // Copyright (C) 2006 PukiWiki Developers Team
4 // License: GPL v2 or (at your option) any later version
6 // Functions for Concept-work of spam-uri metrics
8 if (! defined('SPAM_INI_FILE')) define('SPAM_INI_FILE', 'spam.ini.php');
10 // ---------------------
13 // Return an array of URIs in the $string
14 // [OK] http://nasty.example.org#nasty_string
15 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
16 // [OK] ftp://nasty.example.org:80/dfsdfs
17 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
18 function uri_pickup($string = '', $normalize = TRUE,
19 $preserve_rawuri = FALSE, $preserve_chunk = TRUE)
21 // Not available for: IDN(ignored)
24 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
25 // Refer RFC3986 (Regex below is not strict)
26 '#(\b[a-z][a-z0-9.+-]{1,8})://' . // 1: Scheme
28 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
32 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
33 '(?:[0-9]{1-3}\.){3}[0-9]{1-3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
34 '[^\s<>"\'\[\]:/\#?]+' . // FQDN: foo.example.org
36 '(?::([0-9]*))?' . // 4: Port
37 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
38 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
39 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
40 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
42 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
44 //var_dump(recursive_map('htmlspecialchars', $array));
47 static $parts = array(
48 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
49 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
52 foreach(array_keys($array) as $uri) {
53 $_uri = & $array[$uri];
54 array_rename_keys($_uri, $parts, TRUE, $default);
56 $offset = $_uri['scheme'][1]; // Scheme's offset
57 foreach(array_keys($_uri) as $part) {
58 // Remove offsets for each part
59 $_uri[$part] = & $_uri[$part][0];
63 $_uri['scheme'] = scheme_normalize($_uri['scheme']);
64 if ($_uri['scheme'] === '') {
68 $_uri['host'] = strtolower($_uri['host']);
69 $_uri['port'] = port_normalize($_uri['port'], $_uri['scheme'], FALSE);
70 $_uri['path'] = path_normalize($_uri['path']);
71 if ($preserve_rawuri) $_uri['rawuri'] = & $_uri[0];
74 //$_uri['uri'] = uri_array_implode($_uri);
76 $_uri['uri'] = & $_uri[0]; // Raw
78 unset($_uri[0]); // Matched string itself
79 if (! $preserve_chunk) {
92 // Area offset for area_measure()
93 $_uri['area']['offset'] = $offset;
99 // Destructive normalize of URI array
100 // NOTE: Give me the uri_pickup() result with chunks
101 function uri_array_normalize(& $pickups, $preserve = TRUE)
103 if (! is_array($pickups)) return $pickups;
105 foreach (array_keys($pickups) as $key) {
106 $_key = & $pickups[$key];
107 $_key['path'] = isset($_key['path']) ? strtolower($_key['path']) : '';
108 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
109 $_key['query'] = isset($_key['query']) ? query_normalize(strtolower($_key['query']), TRUE) : '';
110 $_key['fragment'] = (isset($_key['fragment']) && $preserve) ?
111 strtolower($_key['fragment']) : ''; // Just ignore
117 // An URI array => An URI (See uri_pickup())
118 function uri_array_implode($uri = array())
120 if (empty($uri) || ! is_array($uri)) return NULL;
123 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
124 $tmp[] = & $uri['scheme'];
127 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
128 $tmp[] = & $uri['userinfo'];
131 if (isset($uri['host']) && $uri['host'] !== '') {
132 $tmp[] = & $uri['host'];
134 if (isset($uri['port']) && $uri['port'] !== '') {
136 $tmp[] = & $uri['port'];
138 if (isset($uri['path']) && $uri['path'] !== '') {
139 $tmp[] = & $uri['path'];
141 if (isset($uri['file']) && $uri['file'] !== '') {
142 $tmp[] = & $uri['file'];
144 if (isset($uri['query']) && $uri['query'] !== '') {
146 $tmp[] = & $uri['query'];
148 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
150 $tmp[] = & $uri['fragment'];
153 return implode('', $tmp);
156 // $array['something'] => $array['wanted']
157 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
159 if (! is_array($array) || ! is_array($keys)) return FALSE;
161 // Nondestructive test
163 foreach(array_keys($keys) as $from)
164 if (! isset($array[$from]))
167 foreach($keys as $from => $to) {
168 if ($from === $to) continue;
169 if (! $force || isset($array[$from])) {
170 $array[$to] = & $array[$from];
171 unset($array[$from]);
173 $array[$to] = $default;
180 // ---------------------
183 // Pickup all of markup areas
184 function area_pickup($string = '', $method = array())
188 // Anchor tag pair by preg_match_all()
190 // [OK] <a href= >Good site!</a>
191 // [OK] <a href= "#" >test</a>
192 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
193 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
194 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
195 if (isset($method['area_anchor'])) {
197 preg_match_all('#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#i',
198 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
199 foreach(array_keys($areas) as $_area) {
200 $areas[$_area] = array(
201 $areas[$_area][0][1], // Area start (<a href>)
202 $areas[$_area][1][1], // Area end (</a>)
205 if (! empty($areas)) $area['area_anchor'] = $areas;
208 // phpBB's "BBCode" pair by preg_match_all()
210 // [OK] [url]http://nasty.example.com/[/url]
211 // [OK] [link]http://nasty.example.com/[/link]
212 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
213 // [OK] [link http://nasty.example.com/]buy something[/link]
214 if (isset($method['area_bbcode'])) {
216 preg_match_all('#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i',
217 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
218 foreach(array_keys($areas) as $_area) {
219 $areas[$_area] = array(
220 $areas[$_area][0][1], // Area start ([url])
221 $areas[$_area][2][1], // Area end ([/url])
224 if (! empty($areas)) $area['area_bbcode'] = $areas;
227 // Various Wiki syntax
228 // [text_or_uri>text_or_uri]
229 // [text_or_uri:text_or_uri]
230 // [text_or_uri|text_or_uri]
231 // [text_or_uri->text_or_uri]
232 // [text_or_uri text_or_uri] // MediaWiki
233 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
238 // If in doubt, it's a little doubtful
239 // if (Area => inside <= Area) $brief += -1
240 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
242 if (! is_array($areas) || ! is_array($array)) return;
244 $areas_keys = array_keys($areas);
245 foreach(array_keys($array) as $u_index) {
246 $offset = isset($array[$u_index][$o_key]) ?
247 intval($array[$u_index][$o_key]) : 0;
248 foreach($areas_keys as $a_index) {
249 if (isset($array[$u_index][$a_key])) {
250 $offset_s = intval($areas[$a_index][0]);
251 $offset_e = intval($areas[$a_index][1]);
252 // [Area => inside <= Area]
253 if ($offset_s < $offset && $offset < $offset_e) {
254 $array[$u_index][$a_key] += $belief;
261 // ---------------------
264 // Domain exposure callback (See spam_uri_pickup_preprocess())
265 // http://victim.example.org/?foo+site:nasty.example.com+bar
266 // => http://nasty.example.com/?refer=victim.example.org
267 // NOTE: 'refer=' is not so good for (at this time).
268 // Consider about using IP address of the victim, try to avoid that.
269 function _preg_replace_callback_domain_exposure($matches = array())
273 // Preserve the victim URI as a complicity or ...
274 if (isset($matches[5])) {
276 $matches[1] . '://' . // scheme
277 $matches[2] . '/' . // victim.example.org
278 $matches[3]; // The rest of all (before victim)
282 if (isset($matches[4])) {
284 $matches[1] . '://' . // scheme
285 $matches[4] . // nasty.example.com
286 '/?refer=' . strtolower($matches[2]) . // victim.example.org
293 // Preprocess: rawurldecode() and adding space(s) and something
294 // to detect/count some URIs _if possible_
295 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
296 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
297 // [OK] http://victim.example.org/http://nasty.example.org
298 function spam_uri_pickup_preprocess($string = '')
300 if (! is_string($string)) return '';
302 $string = rawurldecode($string);
304 // Domain exposure (See _preg_replace_callback_domain_exposure())
305 $string = preg_replace_callback(
307 // Something Google: http://www.google.com/supported_domains
308 '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
309 '([a-z0-9?=&.%_+-]+)' . // ?query=foo+
310 '\bsite:([a-z0-9.%_-]+)' . // site:nasty.example.com
311 //'()' . // Preserve or remove?
314 '_preg_replace_callback_domain_exposure',
318 // URI exposure (uriuri => uri uri)
319 $string = preg_replace(
321 '#(?<! )(?:https?|ftp):/#i',
322 // '#[a-z][a-z0-9.+-]{1,8}://#i',
323 // '#[a-z][a-z0-9.+-]{1,8}://#i'
332 // Main function of spam-uri pickup
333 function spam_uri_pickup($string = '', $method = array())
335 if (! is_array($method) || empty($method)) {
336 $method = check_uri_spam_method();
339 $string = spam_uri_pickup_preprocess($string);
341 $array = uri_pickup($string);
343 // Area elevation for '(especially external)link' intension
344 if (! empty($array)) {
345 $areas = area_pickup($string, $method);
346 if (! empty($areas)) {
347 $area_shadow = array();
348 foreach(array_keys($array) as $key){
349 $area_shadow[$key] = & $array[$key]['area'];
350 $area_shadow[$key]['anchor'] = 0;
351 $area_shadow[$key]['bbcode'] = 0;
353 if (isset($areas['area_anchor'])) {
354 area_measure($areas['area_anchor'], $area_shadow, 1, 'anchor');
356 if (isset($areas['area_bbcode'])) {
357 area_measure($areas['area_bbcode'], $area_shadow, 1, 'bbcode');
362 // Remove 'offset's for area_measure()
363 foreach(array_keys($array) as $key)
364 unset($array[$key]['area']['offset']);
370 // ---------------------
373 // Scheme normalization: Renaming the schemes
374 // snntp://example.org => nntps://example.org
375 // NOTE: Keep the static lists simple. See also port_normalize().
376 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
378 // Abbreviations considerable they don't have link intension
379 static $abbrevs = array(
384 // Alias => normalized
385 static $aliases = array(
395 $scheme = strtolower(trim($scheme));
396 if (isset($abbrevs[$scheme])) {
397 if ($considerd_harmfull) {
398 $scheme = $abbrevs[$scheme];
403 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
408 // Port normalization: Suppress the (redundant) default port
409 // HTTP://example.org:80/ => http://example.org/
410 // HTTP://example.org:8080/ => http://example.org:8080/
411 // HTTPS://example.org:443/ => https://example.org/
412 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
414 // Schemes that users _maybe_ want to add protocol-handlers
415 // to their web browsers. (and attackers _maybe_ want to use ...)
416 // Reference: http://www.iana.org/assignments/port-numbers
417 static $array = array(
418 // scheme => default port
445 if ($port === '') return $port;
447 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
448 if (isset($array[$scheme]) && $port == $array[$scheme])
449 $port = ''; // Ignore the defaults
454 // Path normalization
455 // http://example.org => http://example.org/
456 // http://example.org#hoge => http://example.org/#hoge
457 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
458 // http://example.org/path/../../a/../back => http://example.org/back
459 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
461 if (! is_string($path) || $path == '')
462 return $addroot ? $divider : '';
465 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
466 $array = explode($divider, $path);
469 foreach(array_keys($array) as $key) {
470 if ($array[$key] == '' || $array[$key] == '.')
475 foreach($array as $value) {
476 if ($value == '..') {
479 array_push($tmp, $value);
484 $path = $addroot ? $divider : '';
485 if (! empty($array)) $path .= implode($divider, $array) . $last;
490 // DirectoryIndex normalize (Destructive and rough)
491 function file_normalize($string = 'index.html.en')
493 static $array = array(
494 'index' => TRUE, // Some system can omit the suffix
496 'index.html' => TRUE,
497 'index.shtml' => TRUE,
500 'index.php3' => TRUE,
501 'index.php4' => TRUE,
502 //'index.pl' => TRUE,
503 //'index.py' => TRUE,
504 //'index.rb' => TRUE,
506 'default.htm' => TRUE,
507 'default.html' => TRUE,
508 'default.asp' => TRUE,
509 'default.aspx' => TRUE,
512 // Content-negothiation filter:
513 // Roughly removing ISO 639 -like
514 // 2-letter suffixes (See RFC3066)
516 if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
517 $_string = $matches[1];
519 $_string = & $string;
522 if (isset($array[strtolower($_string)])) {
529 // Sort query-strings if possible (Destructive and rough)
530 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
531 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
532 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
534 $array = explode('&', $string);
536 // Remove '&' paddings
537 foreach(array_keys($array) as $key) {
538 if ($array[$key] == '') {
543 // Consider '='-sepalated input and paddings
545 $equals = $not_equals = array();
546 foreach ($array as $part) {
547 if (strpos($part, '=') === FALSE) {
548 $not_equals[] = $part;
550 list($key, $value) = explode('=', $part, 2);
551 $value = ltrim($value, '=');
552 if (! $equal_cutempty || $value != '') {
553 $equals[$key] = $value;
558 $array = & $not_equals;
559 foreach ($equals as $key => $value) {
560 $array[] = $key . '=' . $value;
566 return implode('&', $array);
569 // ---------------------
570 // Part One : Checker
572 function generate_glob_regex($string = '', $divider = '/')
574 static $from = array(
577 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
593 if (is_array($string)) {
597 array_map('generate_glob_regex',
599 array_pad(array(), count($string), $divider)
604 $string = str_replace($from, $mid, $string); // Hide
605 $string = preg_quote($string, $divider);
606 $string = str_replace($mid, $to, $string); // Unhide
612 // TODO: preg_grep() ?
614 function is_badhost($hosts = '', $asap = TRUE)
618 if (! isset($regex)) {
620 $regex['badhost'] = array();
624 $blocklist['badhost'] = array(
625 //'*', // Deny all uri
626 //'10.20.*.*', // 10.20.example.com also matches
627 //'*.blogspot.com', // Blog services subdomains
628 //array('blogspot.com', '*.blogspot.com')
630 foreach ($blocklist['badhost'] as $part) {
631 if (is_array($part)) $part = implode(', ', $part);
632 $regex['badhost'][$part] = '/^' . generate_glob_regex($part) . '$/i';
637 if (file_exists(SPAM_INI_FILE)) {
638 $blocklist = array();
639 require(SPAM_INI_FILE);
640 foreach ($blocklist['badhost'] as $part) {
641 if (is_array($part)) $part = implode(', ', $part);
642 $regex['badhost'][$part] = '/^' . generate_glob_regex($part) . '$/i';
649 if (! is_array($hosts)) $hosts = array($hosts);
651 foreach($hosts as $host) {
652 if (! is_string($host)) $host = '';
653 foreach ($regex['badhost'] as $part => $_regex) {
654 if (preg_match($_regex, $host)) {
655 if (! isset($result[$part])) $result[$part] = array();
656 $result[$part][] = $host;
669 // Default (enabled) methods and thresholds
670 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
672 $times = intval($times);
673 $t_area = intval($t_area);
677 'quantity' => 8 * $times, // Allow N URIs
678 'non_uniq' => 3 * $times, // Allow N duped (and normalized) URIs
680 'area_anchor' => $t_area, // Inside <a href> HTML tag
681 'area_bbcode' => $t_area, // Inside [url] or [link] BBCode
686 'asap' => FALSE, // Quit As Soon As Possible
687 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
688 'badhost' => TRUE, // Check badhost
694 // Remove non-$positive values
695 foreach (array_keys($positive) as $key) {
696 if ($positive[$key] < 0) unset($positive[$key]);
699 return $positive + $bool;
702 // Simple/fast spam check
703 function check_uri_spam($target = '', $method = array())
705 if (! is_array($method) || empty($method)) {
706 $method = check_uri_spam_method();
717 'is_spam' => array(),
718 'method' => & $method,
720 $sum = & $progress['sum'];
721 $is_spam = & $progress['is_spam'];
722 $asap = isset($method['asap']) ? $method['asap'] : TRUE;
725 if (is_array($target)) {
726 foreach($target as $str) {
728 $_progress = check_uri_spam($str, $method);
729 foreach (array_keys($_progress['sum']) as $key) {
730 $sum[$key] += $_progress['sum'][$key];
732 foreach(array_keys($_progress['is_spam']) as $key) {
733 $is_spam[$key] = TRUE;
735 if ($asap && $is_spam) break;
739 $pickups = spam_uri_pickup($target, $method);
740 if (empty($pickups)) {
745 $sum['quantity'] += count($pickups);
747 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
748 $sum['quantity'] > $method['quantity']) {
749 $is_spam['quantity'] = TRUE;
752 // Using invalid area: anchor
753 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
755 $p_key = 'area_anchor';
756 foreach($pickups as $pickup) {
757 $sum[$p_key] += $pickup['area'][$key];
758 if(isset($method[$p_key]) &&
759 $sum[$p_key] > $method[$p_key]) {
760 $is_spam[$p_key] = TRUE;
761 if ($asap && $is_spam) break;
763 if ($asap && $is_spam) break;
767 // Using invalid area: bbcode
768 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
770 $p_key = 'area_bbcode';
771 foreach($pickups as $pickup) {
772 $sum[$p_key] += $pickup['area'][$key];
773 if(isset($method[$p_key]) &&
774 $sum[$p_key] > $method[$p_key]) {
775 $is_spam[$p_key] = TRUE;
776 if ($asap && $is_spam) break;
778 if ($asap && $is_spam) break;
782 // URI uniqueness (and removing non-uniques)
783 if ((! $asap || ! $is_spam) && isset($method['non_uniq'])) {
785 // Destructive normalize of URIs
786 uri_array_normalize($pickups);
789 foreach (array_keys($pickups) as $key) {
790 $uris[$key] = uri_array_implode($pickups[$key]);
792 $count = count($uris);
793 $uris = array_unique($uris);
794 $sum['non_uniq'] += $count - count($uris);
795 if ($sum['non_uniq'] > $method['non_uniq']) {
796 $is_spam['non_uniq'] = TRUE;
798 if (! $asap || ! $is_spam) {
799 foreach (array_diff(array_keys($pickups),
800 array_keys($uris)) as $remove) {
801 unset($pickups[$remove]);
809 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
810 $hosts = array_unique($hosts);
811 $sum['uniqhost'] += count($hosts);
814 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
815 $count = array_count_leaves(is_badhost($hosts, $asap));
816 $sum['badhost'] += $count;
817 if ($count != 0) $is_spam['badhost'] = TRUE;
824 function array_count_leaves($array = array(), $count_empty_array = FALSE)
826 if (! is_array($array) || (empty($array) && $count_empty_array))
831 foreach ($array as $part) {
832 $result += array_count_leaves($part, $count_empty_array);
837 // ---------------------
840 // TODO: Don't show unused $method!
841 // Summarize $progress (blocked only)
842 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
845 $tmp = array_keys($progress['is_spam']);
848 $method = & $progress['method'];
849 if (isset($progress['sum'])) {
850 foreach ($progress['sum'] as $key => $value) {
851 if (isset($method[$key])) {
852 $tmp[] = $key . '(' . $value . ')';
858 return implode(', ', $tmp);
861 // ---------------------
864 // Common bahavior for blocking
865 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
872 // ---------------------
876 // Simple/fast spam filter ($target: 'a string' or an array())
877 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array())
881 $progress = check_uri_spam($target, $method);
883 if (! empty($progress['is_spam'])) {
884 // Mail to administrator(s)
885 if ($notify) pkwk_spamnotify($action, $page, $target, $progress, $method);
891 // ---------------------
894 // Mail to administrator(s)
895 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
897 global $notify_subject;
899 $asap = isset($method['asap']) ? $method['asap'] : TRUE;
901 $footer['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
904 $footer['METRICS'] = summarize_spam_progress($progress);
906 $footer['COMMENT'] = $action;
907 $footer['PAGE'] = '[blocked] ' . $page;
908 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
909 $footer['USER_AGENT'] = TRUE;
910 $footer['REMOTE_ADDR'] = TRUE;
911 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $footer);