2 // $Id: spam.php,v 1.66 2006/12/10 05:56:32 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['anchor'])) {
197 preg_match_all('#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#i',
198 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
199 //var_dump(recursive_map('htmlspecialchars', $areas));
200 foreach(array_keys($areas) as $_area) {
201 $areas[$_area] = array(
202 $areas[$_area][0][1], // Area start (<a href>)
203 $areas[$_area][1][1], // Area end (</a>)
206 if (! empty($areas)) $area['anchor'] = $areas;
209 // phpBB's "BBCode" pair by preg_match_all()
211 // [OK] [url]http://nasty.example.com/[/url]
212 // [OK] [link]http://nasty.example.com/[/link]
213 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
214 // [OK] [link http://nasty.example.com/]buy something[/link]
215 if (isset($method['bbcode'])) {
217 preg_match_all('#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i',
218 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
219 //var_dump(recursive_map('htmlspecialchars', $areas));
220 foreach(array_keys($areas) as $_area) {
221 $areas[$_area] = array(
222 $areas[$_area][0][1], // Area start ([url])
223 $areas[$_area][2][1], // Area end ([/url])
226 if (! empty($areas)) $area['bbcode'] = $areas;
229 // Various Wiki syntax
230 // [text_or_uri>text_or_uri]
231 // [text_or_uri:text_or_uri]
232 // [text_or_uri|text_or_uri]
233 // [text_or_uri->text_or_uri]
234 // [text_or_uri text_or_uri] // MediaWiki
235 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
240 // If in doubt, it's a little doubtful
241 // if (Area => inside <= Area) $brief += -1
242 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
244 if (! is_array($areas) || ! is_array($array)) return;
246 $areas_keys = array_keys($areas);
247 foreach(array_keys($array) as $u_index) {
248 $offset = isset($array[$u_index][$o_key]) ?
249 intval($array[$u_index][$o_key]) : 0;
250 foreach($areas_keys as $a_index) {
251 if (isset($array[$u_index][$a_key])) {
252 $offset_s = intval($areas[$a_index][0]);
253 $offset_e = intval($areas[$a_index][1]);
254 // [Area => inside <= Area]
255 if ($offset_s < $offset && $offset < $offset_e) {
256 $array[$u_index][$a_key] += $belief;
263 // ---------------------
266 // Domain exposure callback (See spam_uri_pickup_preprocess())
267 // http://victim.example.org/?foo+site:nasty.example.com+bar
268 // => http://nasty.example.com/?refer=victim.example.org
269 // NOTE: 'refer=' is not so good for (at this time).
270 // Consider about using IP address of the victim, try to avoid that.
271 function _preg_replace_callback_domain_exposure($matches = array())
275 // Preserve the victim URI as a complicity or ...
276 if (isset($matches[5])) {
278 $matches[1] . '://' . // scheme
279 $matches[2] . '/' . // victim.example.org
280 $matches[3]; // The rest of all (before victim)
284 if (isset($matches[4])) {
286 $matches[1] . '://' . // scheme
287 $matches[4] . // nasty.example.com
288 '/?refer=' . strtolower($matches[2]) . // victim.example.org
295 // Preprocess: rawurldecode() and adding space(s) and something
296 // to detect/count some URIs _if possible_
297 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
298 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
299 // [OK] http://victim.example.org/http://nasty.example.org
300 function spam_uri_pickup_preprocess($string = '')
302 if (! is_string($string)) return '';
304 $string = rawurldecode($string);
306 // Domain exposure (See _preg_replace_callback_domain_exposure())
307 $string = preg_replace_callback(
309 // Something Google: http://www.google.com/supported_domains
310 '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
311 '([a-z0-9?=&.%_+-]+)' . // ?query=foo+
312 '\bsite:([a-z0-9.%_-]+)' . // site:nasty.example.com
313 //'()' . // Preserve or remove?
316 '_preg_replace_callback_domain_exposure',
320 // URI exposure (uriuri => uri uri)
321 $string = preg_replace(
323 '#(?<! )(?:https?|ftp):/#i',
324 // '#[a-z][a-z0-9.+-]{1,8}://#i',
325 // '#[a-z][a-z0-9.+-]{1,8}://#i'
334 // Main function of spam-uri pickup
335 function spam_uri_pickup($string = '', $area = array())
337 if (! is_array($area) || empty($area)) {
344 $string = spam_uri_pickup_preprocess($string);
346 $array = uri_pickup($string);
348 // Area elevation for '(especially external)link' intension
349 if (! empty($array)) {
350 $areas = area_pickup($string, $area);
351 if (! empty($areas)) {
352 $area_shadow = array();
353 foreach(array_keys($array) as $key){
354 $area_shadow[$key] = & $array[$key]['area'];
355 $area_shadow[$key]['anchor'] = 0;
356 $area_shadow[$key]['bbcode'] = 0;
358 if (isset($areas['anchor'])) {
359 area_measure($areas['anchor'], $area_shadow, 1, 'anchor');
361 if (isset($areas['bbcode'])) {
362 area_measure($areas['bbcode'], $area_shadow, 1, 'bbcode');
367 // Remove 'offset's for area_measure()
368 foreach(array_keys($array) as $key)
369 unset($array[$key]['area']['offset']);
375 // ---------------------
378 // Scheme normalization: Renaming the schemes
379 // snntp://example.org => nntps://example.org
380 // NOTE: Keep the static lists simple. See also port_normalize().
381 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
383 // Abbreviations considerable they don't have link intension
384 static $abbrevs = array(
389 // Alias => normalized
390 static $aliases = array(
400 $scheme = strtolower(trim($scheme));
401 if (isset($abbrevs[$scheme])) {
402 if ($considerd_harmfull) {
403 $scheme = $abbrevs[$scheme];
408 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
413 // Port normalization: Suppress the (redundant) default port
414 // HTTP://example.org:80/ => http://example.org/
415 // HTTP://example.org:8080/ => http://example.org:8080/
416 // HTTPS://example.org:443/ => https://example.org/
417 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
419 // Schemes that users _maybe_ want to add protocol-handlers
420 // to their web browsers. (and attackers _maybe_ want to use ...)
421 // Reference: http://www.iana.org/assignments/port-numbers
422 static $array = array(
423 // scheme => default port
450 if ($port === '') return $port;
452 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
453 if (isset($array[$scheme]) && $port == $array[$scheme])
454 $port = ''; // Ignore the defaults
459 // Path normalization
460 // http://example.org => http://example.org/
461 // http://example.org#hoge => http://example.org/#hoge
462 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
463 // http://example.org/path/../../a/../back => http://example.org/back
464 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
466 if (! is_string($path) || $path == '')
467 return $addroot ? $divider : '';
470 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
471 $array = explode($divider, $path);
474 foreach(array_keys($array) as $key) {
475 if ($array[$key] == '' || $array[$key] == '.')
480 foreach($array as $value) {
481 if ($value == '..') {
484 array_push($tmp, $value);
489 $path = $addroot ? $divider : '';
490 if (! empty($array)) $path .= implode($divider, $array) . $last;
495 // DirectoryIndex normalize (Destructive and rough)
496 function file_normalize($string = 'index.html.en')
498 static $array = array(
499 'index' => TRUE, // Some system can omit the suffix
501 'index.html' => TRUE,
502 'index.shtml' => TRUE,
505 'index.php3' => TRUE,
506 'index.php4' => TRUE,
507 //'index.pl' => TRUE,
508 //'index.py' => TRUE,
509 //'index.rb' => TRUE,
511 'default.htm' => TRUE,
512 'default.html' => TRUE,
513 'default.asp' => TRUE,
514 'default.aspx' => TRUE,
517 // Content-negothiation filter:
518 // Roughly removing ISO 639 -like
519 // 2-letter suffixes (See RFC3066)
521 if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
522 $_string = $matches[1];
524 $_string = & $string;
527 if (isset($array[strtolower($_string)])) {
534 // Sort query-strings if possible (Destructive and rough)
535 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
536 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
537 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
539 $array = explode('&', $string);
541 // Remove '&' paddings
542 foreach(array_keys($array) as $key) {
543 if ($array[$key] == '') {
548 // Consider '='-sepalated input and paddings
550 $equals = $not_equals = array();
551 foreach ($array as $part) {
552 if (strpos($part, '=') === FALSE) {
553 $not_equals[] = $part;
555 list($key, $value) = explode('=', $part, 2);
556 $value = ltrim($value, '=');
557 if (! $equal_cutempty || $value != '') {
558 $equals[$key] = $value;
563 $array = & $not_equals;
564 foreach ($equals as $key => $value) {
565 $array[] = $key . '=' . $value;
571 return implode('&', $array);
574 // ---------------------
575 // Part One : Checker
577 function generate_glob_regex($string = '', $divider = '/')
579 static $from = array(
582 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
598 if (is_array($string)) {
602 array_map('generate_glob_regex',
604 array_pad(array(), count($string), $divider)
609 $string = str_replace($from, $mid, $string); // Hide
610 $string = preg_quote($string, $divider);
611 $string = str_replace($mid, $to, $string); // Unhide
617 // TODO: preg_grep() ?
619 function is_badhost($hosts = '', $asap = TRUE)
623 if (! isset($regex)) {
625 $regex['badhost'] = array();
629 $blocklist['badhost'] = array(
630 //'*', // Deny all uri
631 //'10.20.*.*', // 10.20.example.com also matches
632 //'*.blogspot.com', // Blog services subdomains
633 //array('blogspot.com', '*.blogspot.com')
635 foreach ($blocklist['badhost'] as $part) {
636 $regex['badhost'][$part] = '/^' . generate_glob_regex($part) . '$/i';
641 if (file_exists(SPAM_INI_FILE)) {
642 $blocklist = array();
643 require(SPAM_INI_FILE);
644 foreach ($blocklist['badhost'] as $part) {
645 $regex['badhost'][$part] = '/^' . generate_glob_regex($part) . '$/i';
652 if (! is_array($hosts)) $hosts = array($hosts);
654 foreach($hosts as $host) {
655 if (! is_string($host)) $host = '';
656 foreach ($regex['badhost'] as $part => $_regex) {
657 if (preg_match($_regex, $host)) {
658 if (! isset($result[$part])) $result[$part] = array();
659 $result[$part][] = $host;
672 // Default (enabled) methods and thresholds
673 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
675 $times = intval($times);
676 $t_area = intval($t_area);
680 'quantity' => 8 * $times, // Allow N URIs
681 'non_uniq' => 3 * $times, // Allow N duped (and normalized) URIs
686 //'total' => $t_area, // Allow N areas total, enabled below
687 'anchor' => $t_area, // Inside <a href> HTML tag
688 'bbcode' => $t_area, // Inside [url] or [link] BBCode
693 'asap' => FALSE, // Quit As Soon As Possible
694 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
695 'badhost' => TRUE, // Check badhost
699 foreach (array_keys($method) as $key) {
700 if ($method[$key] < 0) unset($method[$key]);
702 foreach (array_keys($area) as $key) {
703 if ($area[$key] < 0) unset($area[$key]);
705 $area = empty($area) ? array() : array('area' => $area);
706 $rules = $rule ? $rules : array();
708 return $method + $area + $rules;
711 // Simple/fast spam check
712 function check_uri_spam($target = '', $method = array())
715 if (! is_array($method) || empty($method)) {
716 $method = check_uri_spam_method();
728 'is_spam' => array(),
729 'method' => & $method,
731 $sum = & $progress['sum'];
732 $is_spam = & $progress['is_spam'];
733 $asap = isset($method['asap']) ? $method['asap'] : TRUE;
736 if (is_array($target)) {
737 foreach($target as $str) {
739 $_progress = check_uri_spam($str, $method);
740 foreach (array_keys($_progress['sum']) as $key) {
741 $sum[$key] += $_progress['sum'][$key];
743 foreach(array_keys($_progress['is_spam']) as $key) {
744 $is_spam[$key] = TRUE;
746 if ($asap && $is_spam) break;
750 $pickups = spam_uri_pickup($target);
751 if (empty($pickups)) {
756 $sum['quantity'] += count($pickups);
758 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
759 $sum['quantity'] > $method['quantity']) {
760 $is_spam['quantity'] = TRUE;
762 //var_dump($method['quantity'], $is_spam);
764 // Using invalid area
765 if ((! $asap || ! $is_spam) && isset($method['area'])) {
766 foreach($pickups as $pickup) {
767 foreach ($pickup['area'] as $key => $value) {
768 if ($key == 'offset') continue;
770 $sum['area_total'] += $value;
771 if (isset($method['area']['total']) &&
772 $sum['area_total'] > $method['area']['total']) {
773 $is_spam['area_total'] = TRUE;
774 if ($asap && $is_spam) break;
777 $p_key = 'area_' . $key;
778 $sum[$p_key] += $value;
779 if(isset($method['area'][$key]) &&
780 $sum[$p_key] > $method['area'][$key]) {
781 $is_spam[$p_key] = TRUE;
782 if ($asap && $is_spam) break;
785 if ($asap && $is_spam) break;
788 //var_dump($method['area'], $is_spam);
790 // URI uniqueness (and removing non-uniques)
791 if ((! $asap || ! $is_spam) && isset($method['non_uniq'])) {
793 // Destructive normalize of URIs
794 uri_array_normalize($pickups);
797 foreach (array_keys($pickups) as $key) {
798 $uris[$key] = uri_array_implode($pickups[$key]);
800 $count = count($uris);
801 $uris = array_unique($uris);
802 $sum['non_uniq'] += $count - count($uris);
803 if ($sum['non_uniq'] > $method['non_uniq']) {
804 $is_spam['non_uniq'] = TRUE;
806 if (! $asap || ! $is_spam) {
807 foreach (array_diff(array_keys($pickups),
808 array_keys($uris)) as $remove) {
809 unset($pickups[$remove]);
814 //var_dump($method['non_uniq'], $is_spam);
818 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
819 $hosts = array_unique($hosts);
820 $sum['uniqhost'] += count($hosts);
821 //var_dump($method['uniqhost'], $is_spam);
824 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
825 $count = array_count_leaves(is_badhost($hosts, $asap));
826 $sum['badhost'] += $count;
827 if ($count != 0) $is_spam['badhost'] = TRUE;
829 //var_dump($method['badhost'], $is_spam);
835 function array_count_leaves($array = array(), $count_empty_array = FALSE)
837 if (! is_array($array) || (empty($array) && $count_empty_array))
842 foreach ($array as $part) {
843 $result += array_count_leaves($part, $count_empty_array);
848 // ---------------------
851 // TODO: Don't show unused $method!
852 // Summarize $progress (blocked only)
853 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
855 $method = $progress['method'];
856 if (isset($method['area'])) {
857 foreach(array_keys($method['area']) as $key) {
858 $method['area_' . $key] = TRUE;
863 $tmp = array_keys($progress['is_spam']);
866 foreach ($progress['sum'] as $key => $value) {
867 if (isset($method[$key])) {
868 $tmp[] = $key . '(' . $value . ')';
873 return implode(', ', $tmp);
876 // ---------------------
879 // Common bahavior for blocking
880 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
887 // ---------------------
891 // Simple/fast spam filter ($target: 'a string' or an array())
892 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array())
896 $progress = check_uri_spam($target, $method);
898 if (! empty($progress['is_spam'])) {
899 // Mail to administrator(s)
900 if ($notify) pkwk_spamnotify($action, $page, $target, $progress, $method);
906 // ---------------------
909 // Mail to administrator(s)
910 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
912 global $notify_subject;
914 $asap = isset($method['asap']) ? $method['asap'] : TRUE;
916 $footer['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
919 $footer['METRICS'] = summarize_spam_progress($progress);
921 $footer['COMMENT'] = $action;
922 $footer['PAGE'] = '[blocked] ' . $page;
923 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
924 $footer['USER_AGENT'] = TRUE;
925 $footer['REMOTE_ADDR'] = TRUE;
926 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $footer);