2 // $Id: spam.php,v 1.60 2006/12/04 13:34:17 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) {
91 $_uri['area']['offset'] = $offset;
97 // Destructive normalize of URI array
98 // NOTE: Give me the uri_pickup() result with chunks
99 function uri_array_normalize(& $pickups, $preserve = TRUE)
101 if (! is_array($pickups)) return $pickups;
103 foreach (array_keys($pickups) as $key) {
104 $_key = & $pickups[$key];
105 $_key['path'] = isset($_key['path']) ? strtolower($_key['path']) : '';
106 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
107 $_key['query'] = isset($_key['query']) ? query_normalize(strtolower($_key['query']), TRUE) : '';
108 $_key['fragment'] = (isset($_key['fragment']) && $preserve) ?
109 strtolower($_key['fragment']) : ''; // Just ignore
115 // An URI array => An URI (See uri_pickup())
116 function uri_array_implode($uri = array())
118 if (empty($uri) || ! is_array($uri)) return NULL;
121 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
122 $tmp[] = & $uri['scheme'];
125 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
126 $tmp[] = & $uri['userinfo'];
129 if (isset($uri['host']) && $uri['host'] !== '') {
130 $tmp[] = & $uri['host'];
132 if (isset($uri['port']) && $uri['port'] !== '') {
134 $tmp[] = & $uri['port'];
136 if (isset($uri['path']) && $uri['path'] !== '') {
137 $tmp[] = & $uri['path'];
139 if (isset($uri['file']) && $uri['file'] !== '') {
140 $tmp[] = & $uri['file'];
142 if (isset($uri['query']) && $uri['query'] !== '') {
144 $tmp[] = & $uri['query'];
146 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
148 $tmp[] = & $uri['fragment'];
151 return implode('', $tmp);
154 // $array['something'] => $array['wanted']
155 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
157 if (! is_array($array) || ! is_array($keys)) return FALSE;
159 // Nondestructive test
161 foreach(array_keys($keys) as $from)
162 if (! isset($array[$from]))
165 foreach($keys as $from => $to) {
166 if ($from === $to) continue;
167 if (! $force || isset($array[$from])) {
168 $array[$to] = & $array[$from];
169 unset($array[$from]);
171 $array[$to] = $default;
178 // ---------------------
181 // Domain exposure callback (See spam_uri_pickup_preprocess())
182 // http://victim.example.org/?foo+site:nasty.example.com+bar
183 // => http://nasty.example.com/?refer=victim.example.org
184 // NOTE: 'refer=' is not so good for (at this time).
185 // Consider about using IP address of the victim, try to avoid that.
186 function _preg_replace_callback_domain_exposure($matches = array())
190 // Preserve the victim URI as a complicity or ...
191 if (isset($matches[5])) {
193 $matches[1] . '://' . // scheme
194 $matches[2] . '/' . // victim.example.org
195 $matches[3]; // The rest of all (before victim)
199 if (isset($matches[4])) {
201 $matches[1] . '://' . // scheme
202 $matches[4] . // nasty.example.com
203 '/?refer=' . strtolower($matches[2]) . // victim.example.org
210 // Preprocess: rawurldecode() and adding space(s) and something
211 // to detect/count some URIs _if possible_
212 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
213 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
214 // [OK] http://victim.example.org/http://nasty.example.org
215 function spam_uri_pickup_preprocess($string = '')
217 if (! is_string($string)) return '';
219 $string = rawurldecode($string);
221 // Domain exposure (See _preg_replace_callback_domain_exposure())
222 $string = preg_replace_callback(
224 // Something Google: http://www.google.com/supported_domains
225 '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
226 '([a-z0-9?=&.%_+-]+)' . // ?query=foo+
227 '\bsite:([a-z0-9.%_-]+)' . // site:nasty.example.com
228 //'()' . // Preserve or remove?
231 '_preg_replace_callback_domain_exposure',
235 // URI exposure (uriuri => uri uri)
236 $string = preg_replace(
238 '#(?<! )(?:https?|ftp):/#i',
239 // '#[a-z][a-z0-9.+-]{1,8}://#i',
240 // '#[a-z][a-z0-9.+-]{1,8}://#i'
249 // Main function of spam-uri pickup
250 function spam_uri_pickup($string = '', $area = array())
252 if (! is_array($area) || empty($area)) {
259 $string = spam_uri_pickup_preprocess($string);
261 $array = uri_pickup($string);
263 // Area elevation for '(especially external)link' intension
264 if (! empty($array)) {
266 $area_shadow = array();
267 foreach(array_keys($array) as $key){
268 $area_shadow[$key] = & $array[$key]['area'];
269 $area_shadow[$key]['anchor'] = 0;
270 $area_shadow[$key]['bbcode'] = 0;
273 // Anchor tags by preg_match_all()
274 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
275 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
276 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
277 // [NG] <a href= >Good site!</a> <a href= "#" >test</a>
278 if (isset($area['anchor'])) {
280 preg_match_all('#<a\b[^>]*href[^>]*>.*?</a\b[^>]*(>)#i',
281 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
282 //var_dump(recursive_map('htmlspecialchars', $areas));
283 foreach(array_keys($areas) as $_area) {
284 $areas[$_area] = array(
285 $areas[$_area][0][1], // Area start (<a href>)
286 $areas[$_area][1][1], // Area end (</a>)
289 area_measure($areas, $area_shadow, 1, 'anchor');
292 // phpBB's "BBCode" by preg_match_all()
293 // [url]http://nasty.example.com/[/url]
294 // [link]http://nasty.example.com/[/link]
295 // [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
296 // [link http://nasty.example.com/]buy something[/link]
298 if (isset($area['bbcode'])) {
300 preg_match_all('#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i',
301 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
302 //var_dump(recursive_map('htmlspecialchars', $areas));
303 foreach(array_keys($areas) as $_area) {
304 $areas[$_area] = array(
305 $areas[$_area][0][1], // Area start ([url])
306 $areas[$_area][2][1], // Area end ([/url])
309 area_measure($areas, $area_shadow, 1, 'bbcode');
312 // Various Wiki syntax
313 // [text_or_uri>text_or_uri]
314 // [text_or_uri:text_or_uri]
315 // [text_or_uri|text_or_uri]
316 // [text_or_uri->text_or_uri]
317 // [text_or_uri text_or_uri] // MediaWiki
318 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
320 // Remove 'offset's for area_measure()
321 foreach(array_keys($array) as $key)
322 unset($array[$key]['area']['offset']);
328 // If in doubt, it's a little doubtful
329 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
331 if (! is_array($areas) || ! is_array($array)) return;
333 $areas_keys = array_keys($areas);
334 foreach(array_keys($array) as $u_index) {
335 $offset = isset($array[$u_index][$o_key]) ?
336 intval($array[$u_index][$o_key]) : 0;
337 foreach($areas_keys as $a_index) {
338 if (isset($array[$u_index][$a_key])) {
339 $offset_s = intval($areas[$a_index][0]);
340 $offset_e = intval($areas[$a_index][1]);
341 // [Area => inside <= Area]
342 if ($offset_s < $offset && $offset < $offset_e) {
343 $array[$u_index][$a_key] += $belief;
350 // ---------------------
353 // Scheme normalization: Renaming the schemes
354 // snntp://example.org => nntps://example.org
355 // NOTE: Keep the static lists simple. See also port_normalize().
356 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
358 // Abbreviations considerable they don't have link intension
359 static $abbrevs = array(
364 // Alias => normalized
365 static $aliases = array(
375 $scheme = strtolower(trim($scheme));
376 if (isset($abbrevs[$scheme])) {
377 if ($considerd_harmfull) {
378 $scheme = $abbrevs[$scheme];
383 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
388 // Port normalization: Suppress the (redundant) default port
389 // HTTP://example.org:80/ => http://example.org/
390 // HTTP://example.org:8080/ => http://example.org:8080/
391 // HTTPS://example.org:443/ => https://example.org/
392 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
394 // Schemes that users _maybe_ want to add protocol-handlers
395 // to their web browsers. (and attackers _maybe_ want to use ...)
396 // Reference: http://www.iana.org/assignments/port-numbers
397 static $array = array(
398 // scheme => default port
425 if ($port === '') return $port;
427 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
428 if (isset($array[$scheme]) && $port == $array[$scheme])
429 $port = ''; // Ignore the defaults
434 // Path normalization
435 // http://example.org => http://example.org/
436 // http://example.org#hoge => http://example.org/#hoge
437 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
438 // http://example.org/path/../../a/../back => http://example.org/back
439 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
441 if (! is_string($path) || $path == '')
442 return $addroot ? $divider : '';
445 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
446 $array = explode($divider, $path);
449 foreach(array_keys($array) as $key) {
450 if ($array[$key] == '' || $array[$key] == '.')
455 foreach($array as $value) {
456 if ($value == '..') {
459 array_push($tmp, $value);
464 $path = $addroot ? $divider : '';
465 if (! empty($array)) $path .= implode($divider, $array) . $last;
470 // DirectoryIndex normalize (Destructive and rough)
471 function file_normalize($string = 'index.html.en')
473 static $array = array(
474 'index' => TRUE, // Some system can omit the suffix
476 'index.html' => TRUE,
477 'index.shtml' => TRUE,
480 'index.php3' => TRUE,
481 'index.php4' => TRUE,
482 //'index.pl' => TRUE,
483 //'index.py' => TRUE,
484 //'index.rb' => TRUE,
486 'default.htm' => TRUE,
487 'default.html' => TRUE,
488 'default.asp' => TRUE,
489 'default.aspx' => TRUE,
492 // Content-negothiation filter:
493 // Roughly removing ISO 639 -like
494 // 2-letter suffixes (See RFC3066)
496 if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
497 $_string = $matches[1];
499 $_string = & $string;
502 if (isset($array[strtolower($_string)])) {
509 // Sort query-strings if possible (Destructive and rough)
510 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
511 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
512 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
514 $array = explode('&', $string);
516 // Remove '&' paddings
517 foreach(array_keys($array) as $key) {
518 if ($array[$key] == '') {
523 // Consider '='-sepalated input and paddings
525 $equals = $not_equals = array();
526 foreach ($array as $part) {
527 if (strpos($part, '=') === FALSE) {
528 $not_equals[] = $part;
530 list($key, $value) = explode('=', $part, 2);
531 $value = ltrim($value, '=');
532 if (! $equal_cutempty || $value != '') {
533 $equals[$key] = $value;
538 $array = & $not_equals;
539 foreach ($equals as $key => $value) {
540 $array[] = $key . '=' . $value;
546 return implode('&', $array);
549 // ---------------------
550 // Part One : Checker
552 function generate_glob_regex($string = '', $divider = '/')
554 static $from = array(
557 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
573 if (is_array($string)) {
577 array_map('generate_glob_regex',
579 array_pad(array(), count($string), $divider)
584 $string = str_replace($from, $mid, $string); // Hide
585 $string = preg_quote($string, $divider);
586 $string = str_replace($mid, $to, $string); // Unhide
592 // TODO: preg_grep() ?
594 function is_badhost($hosts = '', $asap = TRUE)
598 if (! isset($regex)) {
600 $regex['badhost'] = array();
604 $blocklist['badhost'] = array(
605 //'*', // Deny all uri
606 //'10.20.*.*', // 10.20.example.com also matches
607 //'*.blogspot.com', // Blog services subdomains
608 //array('blogspot.com', '*.blogspot.com')
610 foreach ($blocklist['badhost'] as $part) {
611 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
616 if (file_exists(SPAM_INI_FILE)) {
617 $blocklist = array();
618 require(SPAM_INI_FILE);
619 foreach ($blocklist['badhost'] as $part) {
620 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
627 if (! is_array($hosts)) $hosts = array($hosts);
629 foreach($hosts as $host) {
630 if (! is_string($host)) $host = '';
633 foreach ($regex['badhost'] as $_regex) {
634 if (preg_match($_regex, $host)) {
648 // Default (enabled) methods and thresholds
649 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
651 $times = intval($times);
652 $t_area = intval($t_area);
656 'quantity' => 8 * $times, // Allow N URIs
657 'non_uniq' => 3 * $times, // Allow N duped (and normalized) URIs
662 //'total' => $t_area, // Allow N areas total, enabled below
663 'anchor' => $t_area, // Inside <a href> HTML tag
664 'bbcode' => $t_area, // Inside [url] or [link] BBCode
669 'badhost' => TRUE, // Check badhost
673 foreach (array_keys($method) as $key) {
674 if ($method[$key] < 0) unset($method[$key]);
676 foreach (array_keys($area) as $key) {
677 if ($area[$key] < 0) unset($area[$key]);
679 $area = empty($area) ? array() : array('area' => $area);
680 $rules = $rule ? $rules : array();
682 return $method + $area + $rules;
685 // TODO: Simplify $progress data structure
686 // TODO: Simplify. !empty(['_action']) just means $is_spam
687 // Simple/fast spam check
688 function check_uri_spam($target = '', $method = array(), $asap = TRUE)
701 '_action' => array(),
704 if (! is_array($method) || empty($method)) {
705 $method = check_uri_spam_method();
708 if (is_array($target)) {
710 foreach($target as $str) {
711 list($_is_spam, $_progress) = check_uri_spam($str, $method, $asap);
712 $is_spam = $is_spam || $_is_spam;
713 $progress['quantity'] += $_progress['quantity'];
714 $progress['area']['total'] += $_progress['area']['total'];
715 $progress['area']['anchor'] += $_progress['area']['anchor'];
716 $progress['area']['bbcode'] += $_progress['area']['bbcode'];
717 $progress['non_uniq'] += $_progress['non_uniq'];
718 $progress['uniqhost'] += $_progress['uniqhost'];
719 $progress['badhost'] += $_progress['badhost'];
720 foreach($_progress['_action'] as $key => $value) {
721 if (is_array($value)) {
722 foreach(array_keys($value) as $_key) {
723 $progress['_action'][$key][$_key] = TRUE;
726 $progress['_action'][$key] = TRUE;
729 if ($is_spam && $asap) break;
732 $pickups = spam_uri_pickup($target);
733 if (! empty($pickups)) {
734 $progress['quantity'] += count($pickups);
737 if ((! $is_spam || ! $asap) && isset($method['quantity']) &&
738 $progress['quantity'] > $method['quantity']) {
740 $progress['_action']['quantity'] = TRUE;
742 //var_dump($method['quantity'], $is_spam);
744 // Using invalid area
745 if ((! $is_spam || ! $asap) && isset($method['area'])) {
746 foreach($pickups as $pickup) {
747 foreach ($pickup['area'] as $key => $value) {
748 if ($key == 'offset') continue;
749 $progress['area']['total'] += $value;
750 $progress['area'][$key] += $value;
751 if (isset($method['area']['total']) &&
752 $progress['area']['total'] > $method['area']['total']) {
754 $progress['_action']['area']['total'] = TRUE;
755 if ($is_spam && $asap) break;
757 if(isset($method['area'][$key]) &&
758 $progress['area'][$key] > $method['area'][$key]) {
760 $progress['_action']['area'][$key] = TRUE;
761 if ($is_spam && $asap) break;
764 if ($is_spam && $asap) break;
767 //var_dump($method['area'], $is_spam);
770 // URI uniqueness (and removing non-uniques)
771 if ((! $is_spam || ! $asap) && isset($method['non_uniq'])) {
773 // Destructive normalize of URIs
774 uri_array_normalize($pickups);
777 foreach (array_keys($pickups) as $key) {
778 $uris[$key] = uri_array_implode($pickups[$key]);
780 $count = count($uris);
781 $uris = array_unique($uris);
782 $progress['non_uniq'] += $count - count($uris);
783 if ($progress['non_uniq'] > $method['non_uniq']) {
785 $progress['_action']['non_uniq'] = TRUE;
787 if (! $asap || ! $is_spam) {
788 foreach (array_diff(array_keys($pickups),
789 array_keys($uris)) as $remove) {
790 unset($pickups[$remove]);
795 //var_dump($method['non_uniq'], $is_spam);
799 foreach ($pickups as $pickup) {
800 $hosts[] = & $pickup['host'];
802 $hosts = array_unique($hosts);
803 $progress['uniqhost'] += count($hosts);
804 //var_dump($method['uniqhost'], $is_spam);
807 if ((! $is_spam || ! $asap) && isset($method['badhost'])) {
808 $count = is_badhost($hosts, $asap);
809 $progress['badhost'] += $count;
811 $progress['_action']['badhost'] = TRUE;
815 //var_dump($method['badhost'], $is_spam);
819 return array($is_spam, $progress);
822 // ---------------------
826 // Summarize $progress (blocked only)
827 function summarize_check_uri_spam_progress($progress = array(), $shownum = TRUE)
829 //$list = check_uri_spam_method();
832 foreach (array_keys($progress['_action']) as $_action) {
833 if (is_array($progress['_action'][$_action])) {
834 foreach (array_keys($progress['_action'][$_action]) as $_area) {
835 $tmp[] = $_action . '=>' . $_area .
836 ($shownum ? '(' . $progress[$_action][$_area] . ')' : '');
840 ($shownum ? '(' . $progress[$_action] . ')' : '');
844 return implode(', ', $tmp);
847 // ---------------------
850 // Common bahavior for blocking
851 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
858 // ---------------------
862 // Simple/fast spam filter ($target: 'a string' or an array())
863 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $asap = FALSE)
867 list($is_spam, $progress) = check_uri_spam($target, $method, $asap);
870 // Mail to administrator(s)
871 if ($notify) pkwk_spamnotify($action, $page, $target, $progress);
877 // ---------------------
880 // Mail to administrator(s)
881 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array())
883 global $notify_subject;
885 $footer['ACTION'] = 'Blocked by: ' . summarize_check_uri_spam_progress($progress);
886 $footer['COMMENT'] = $action;
887 $footer['PAGE'] = '[blocked] ' . $page;
888 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
889 $footer['USER_AGENT'] = TRUE;
890 $footer['REMOTE_ADDR'] = TRUE;
891 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $footer);