2 // $Id: spam.php,v 1.54 2006/12/03 03:23:54 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 // Return an array of URIs in the $string
11 // [OK] http://nasty.example.org#nasty_string
12 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
13 // [OK] ftp://nasty.example.org:80/dfsdfs
14 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
15 function uri_pickup($string = '', $normalize = TRUE,
16 $preserve_rawuri = FALSE, $preserve_chunk = TRUE)
18 // Not available for: IDN(ignored)
21 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
22 // Refer RFC3986 (Regex below is not strict)
23 '#(\b[a-z][a-z0-9.+-]{1,8})://' . // 1: Scheme
25 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
29 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
30 '(?:[0-9]{1-3}\.){3}[0-9]{1-3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
31 '[^\s<>"\'\[\]:/\#?]+' . // FQDN: foo.example.org
33 '(?::([0-9]*))?' . // 4: Port
34 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
35 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
36 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
37 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
39 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
41 //var_dump(recursive_map('htmlspecialchars', $array));
44 static $parts = array(
45 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
46 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
49 foreach(array_keys($array) as $uri) {
50 $_uri = & $array[$uri];
51 array_rename_keys($_uri, $parts, TRUE, $default);
53 $offset = $_uri['scheme'][1]; // Scheme's offset
54 foreach(array_keys($_uri) as $part) {
55 // Remove offsets for each part
56 $_uri[$part] = & $_uri[$part][0];
60 $_uri['scheme'] = scheme_normalize($_uri['scheme']);
61 if ($_uri['scheme'] === '') {
65 $_uri['host'] = strtolower($_uri['host']);
66 $_uri['port'] = port_normalize($_uri['port'], $_uri['scheme'], FALSE);
67 $_uri['path'] = path_normalize($_uri['path']);
68 $_uri['query'] = query_normalize($_uri['query']);
69 if ($preserve_rawuri) $_uri['rawuri'] = & $_uri[0];
72 //$_uri['uri'] = uri_array_implode($_uri);
74 $_uri['uri'] = & $_uri[0]; // Raw
76 unset($_uri[0]); // Matched string itself
77 if (! $preserve_chunk) {
89 $_uri['area']['offset'] = $offset;
95 // Domain exposure callback (See spam_uri_pickup_preprocess())
96 // http://victim.example.org/?foo+site:nasty.example.com+bar
97 // => http://nasty.example.com/?refer=victim.example.org
98 // NOTE: 'refer=' is not so good for (at this time).
99 // Consider about using IP address of the victim, try to avoid that.
100 function _preg_replace_callback_domain_exposure($matches = array())
104 // Preserve the victim URI as a complicity or ...
105 if (isset($matches[5])) {
107 $matches[1] . '://' . // scheme
108 $matches[2] . '/' . // victim.example.org
109 $matches[3]; // The rest of all (before victim)
113 if (isset($matches[4])) {
115 $matches[1] . '://' . // scheme
116 $matches[4] . // nasty.example.com
117 '/?refer=' . strtolower($matches[2]) . // victim.example.org
124 // Preprocess: rawurldecode() and adding space(s) and something
125 // to detect/count some URIs _if possible_
126 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
127 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
128 // [OK] http://victim.example.org/http://nasty.example.org
129 function spam_uri_pickup_preprocess($string = '')
131 if (! is_string($string)) return '';
133 $string = rawurldecode($string);
135 // Domain exposure (See _preg_replace_callback_domain_exposure())
136 $string = preg_replace_callback(
138 // Something Google: http://www.google.com/supported_domains
139 '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
140 '([a-z0-9?=&.%_+-]+)' . // ?query=foo+
141 '\bsite:([a-z0-9.%_-]+)' . // site:nasty.example.com
142 //'()' . // Preserve or remove?
145 '_preg_replace_callback_domain_exposure',
149 // URI exposure (uriuri => uri uri)
150 $string = preg_replace(
152 '#(?<! )(?:https?|ftp):/#i',
153 // '#[a-z][a-z0-9.+-]{1,8}://#i',
154 // '#[a-z][a-z0-9.+-]{1,8}://#i'
163 // Main function of spam-uri pickup
164 function spam_uri_pickup($string = '', $area = array())
166 if (! is_array($area) || empty($area)) {
173 $string = spam_uri_pickup_preprocess($string);
175 $array = uri_pickup($string);
177 // Area elevation for '(especially external)link' intension
178 if (! empty($array)) {
180 $area_shadow = array();
181 foreach(array_keys($array) as $key){
182 $area_shadow[$key] = & $array[$key]['area'];
183 $area_shadow[$key]['anchor'] = 0;
184 $area_shadow[$key]['bbcode'] = 0;
187 // Anchor tags by preg_match_all()
188 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
189 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
190 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
191 // [NG] <a href= >Good site!</a> <a href= "#" >test</a>
192 if (isset($area['anchor'])) {
194 preg_match_all('#<a\b[^>]*href[^>]*>.*?</a\b[^>]*(>)#i',
195 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
196 //var_dump(recursive_map('htmlspecialchars', $areas));
197 foreach(array_keys($areas) as $_area) {
198 $areas[$_area] = array(
199 $areas[$_area][0][1], // Area start (<a href>)
200 $areas[$_area][1][1], // Area end (</a>)
203 area_measure($areas, $area_shadow, 1, 'anchor');
206 // phpBB's "BBCode" by preg_match_all()
207 // [url]http://nasty.example.com/[/url]
208 // [link]http://nasty.example.com/[/link]
209 // [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
210 // [link http://nasty.example.com/]buy something[/link]
212 if (isset($area['bbcode'])) {
214 preg_match_all('#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i',
215 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
216 //var_dump(recursive_map('htmlspecialchars', $areas));
217 foreach(array_keys($areas) as $_area) {
218 $areas[$_area] = array(
219 $areas[$_area][0][1], // Area start ([url])
220 $areas[$_area][2][1], // Area end ([/url])
223 area_measure($areas, $area_shadow, 1, 'bbcode');
226 // Various Wiki syntax
227 // [text_or_uri>text_or_uri]
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] // MediaWiki
232 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
234 // Remove 'offset's for area_measure()
235 foreach(array_keys($array) as $key)
236 unset($array[$key]['area']['offset']);
242 // $array['something'] => $array['wanted']
243 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
245 if (! is_array($array) || ! is_array($keys)) return FALSE;
247 // Nondestructive test
249 foreach(array_keys($keys) as $from)
250 if (! isset($array[$from]))
253 foreach($keys as $from => $to) {
254 if ($from === $to) continue;
255 if (! $force || isset($array[$from])) {
256 $array[$to] = & $array[$from];
257 unset($array[$from]);
259 $array[$to] = $default;
266 // If in doubt, it's a little doubtful
267 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
269 if (! is_array($areas) || ! is_array($array)) return;
271 $areas_keys = array_keys($areas);
272 foreach(array_keys($array) as $u_index) {
273 $offset = isset($array[$u_index][$o_key]) ?
274 intval($array[$u_index][$o_key]) : 0;
275 foreach($areas_keys as $a_index) {
276 if (isset($array[$u_index][$a_key])) {
277 $offset_s = intval($areas[$a_index][0]);
278 $offset_e = intval($areas[$a_index][1]);
279 // [Area => inside <= Area]
280 if ($offset_s < $offset && $offset < $offset_e) {
281 $array[$u_index][$a_key] += $belief;
289 // ---------------------
292 // Scheme normalization: Renaming the schemes
293 // snntp://example.org => nntps://example.org
294 // NOTE: Keep the static lists simple. See also port_normalize().
295 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
297 // Abbreviations considerable they don't have link intension
298 static $abbrevs = array(
303 // Alias => normalized
304 static $aliases = array(
314 $scheme = strtolower(trim($scheme));
315 if (isset($abbrevs[$scheme])) {
316 if ($considerd_harmfull) {
317 $scheme = $abbrevs[$scheme];
322 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
327 // Port normalization: Suppress the (redundant) default port
328 // HTTP://example.org:80/ => http://example.org/
329 // HTTP://example.org:8080/ => http://example.org:8080/
330 // HTTPS://example.org:443/ => https://example.org/
331 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
333 // Schemes that users _maybe_ want to add protocol-handlers
334 // to their web browsers. (and attackers _maybe_ want to use ...)
335 // Reference: http://www.iana.org/assignments/port-numbers
336 static $array = array(
337 // scheme => default port
364 if ($port === '') return $port;
366 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
367 if (isset($array[$scheme]) && $port == $array[$scheme])
368 $port = ''; // Ignore the defaults
373 // Path normalization
374 // http://example.org => http://example.org/
375 // http://example.org#hoge => http://example.org/#hoge
376 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
377 // http://example.org/path/../../a/../back => http://example.org/back
378 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
380 if (! is_string($path) || $path == '') {
381 $path = $addroot ? $divider : '';
384 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
385 $array = explode($divider, $path);
388 foreach(array_keys($array) as $key) {
389 if ($array[$key] == '' || $array[$key] == '.')
394 foreach($array as $value) {
395 if ($value == '..') {
398 array_push($tmp, $value);
403 $path = $addroot ? $divider : '';
404 if (! empty($array)) $path .= implode($divider, $array) . $last;
410 // Sort query-strings if possible
411 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
412 function query_normalize($string = '')
414 $array = explode('&', $string);
417 foreach(array_keys($array) as $key) {
418 if ($array[$key] == '') {
424 return implode('&', $array);
427 // An URI array => An URI (See uri_pickup())
428 function uri_array_implode($uri = array())
430 if (empty($uri) || ! is_array($uri)) return NULL;
433 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
434 $tmp[] = & $uri['scheme'];
437 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
438 $tmp[] = & $uri['userinfo'];
441 if (isset($uri['host']) && $uri['host'] !== '') {
442 $tmp[] = & $uri['host'];
444 if (isset($uri['port']) && $uri['port'] !== '') {
446 $tmp[] = & $uri['port'];
448 if (isset($uri['path']) && $uri['path'] !== '') {
449 $tmp[] = & $uri['path'];
451 if (isset($uri['file']) && $uri['file'] !== '') {
452 $tmp[] = & $uri['file'];
454 if (isset($uri['query']) && $uri['query'] !== '') {
456 $tmp[] = & $uri['query'];
458 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
460 $tmp[] = & $uri['fragment'];
463 return implode('', $tmp);
466 // ---------------------
467 // Part One : Checker
469 function generate_glob_regex($string = '', $divider = '/')
471 static $from = array(
474 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
490 if (is_array($string)) {
494 array_map('generate_glob_regex',
496 array_pad(array(), count($string), $divider)
501 $string = str_replace($from, $mid, $string); // Hide
502 $string = preg_quote($string, $divider);
503 $string = str_replace($mid, $to, $string); // Unhide
509 // TODO: preg_grep() ?
511 function is_badhost($hosts = '', $asap = TRUE)
515 if (! isset($regex)) {
517 $regex['badhost'] = array();
521 $blocklist['badhost'] = array(
522 //'*', // Deny all uri
523 //'10.20.*.*', // 10.20.example.com also matches
524 //'*.blogspot.com', // Blog services subdomains
525 //array('blogspot.com', '*.blogspot.com')
527 foreach ($blocklist['badhost'] as $part) {
528 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
533 if (file_exists(SPAM_INI_FILE)) {
534 $blocklist = array();
535 require(SPAM_INI_FILE);
536 foreach ($blocklist['badhost'] as $part) {
537 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
544 if (! is_array($hosts)) $hosts = array($hosts);
546 foreach($hosts as $host) {
547 if (! is_string($host)) $host = '';
550 foreach ($regex['badhost'] as $_regex) {
551 if (preg_match($_regex, $host)) {
565 // Default (enabled) methods and thresholds
566 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
568 $times = intval($times);
569 $t_area = intval($t_area);
573 'quantity' => 8 * $times, // Allow N URIs
574 'non_uniq' => 3 * $times, // Allow N duped (and normalized) URIs
579 //'total' => $t_area, // Allow N areas total, enabled below
580 'anchor' => $t_area, // Inside <a href> HTML tag
581 'bbcode' => $t_area, // Inside [url] or [link] BBCode
586 'badhost' => TRUE, // Check badhost
590 foreach (array_keys($method) as $key) {
591 if ($method[$key] < 0) unset($method[$key]);
593 foreach (array_keys($area) as $key) {
594 if ($area[$key] < 0) unset($area[$key]);
596 $area = empty($area) ? array() : array('area' => $area);
597 $rules = $rule ? $rules : array();
599 return $method + $area + $rules;
603 // TODO: Simplify. !empty(['_action']) just means $is_spam
604 // Simple/fast spam check
605 function check_uri_spam($target = '', $method = array(), $asap = TRUE)
618 '_action' => array(),
621 if (! is_array($method) || empty($method)) {
622 $method = check_uri_spam_method();
625 if (is_array($target)) {
627 foreach($target as $str) {
628 list($_is_spam, $_progress) = check_uri_spam($str, $method, $asap);
629 $is_spam = $is_spam || $_is_spam;
630 $progress['quantity'] += $_progress['quantity'];
631 $progress['area']['total'] += $_progress['area']['total'];
632 $progress['area']['anchor'] += $_progress['area']['anchor'];
633 $progress['area']['bbcode'] += $_progress['area']['bbcode'];
634 $progress['non_uniq'] += $_progress['non_uniq'];
635 $progress['uniqhost'] += $_progress['uniqhost'];
636 $progress['badhost'] += $_progress['badhost'];
637 foreach($_progress['_action'] as $key => $value) {
638 if (is_array($value)) {
639 foreach(array_keys($value) as $_key) {
640 $progress['_action'][$key][$_key] = TRUE;
643 $progress['_action'][$key] = TRUE;
646 if ($is_spam && $asap) break;
649 $pickups = spam_uri_pickup($target);
650 if (! empty($pickups)) {
651 $progress['quantity'] += count($pickups);
654 if ((! $is_spam || ! $asap) && isset($method['quantity']) &&
655 $progress['quantity'] > $method['quantity']) {
657 $progress['_action']['quantity'] = TRUE;
659 //var_dump($method['quantity'], $is_spam);
661 // Using invalid area
662 if ((! $is_spam || ! $asap) && isset($method['area'])) {
663 foreach($pickups as $pickup) {
664 foreach ($pickup['area'] as $key => $value) {
665 if ($key == 'offset') continue;
666 $progress['area']['total'] += $value;
667 $progress['area'][$key] += $value;
668 if (isset($method['area']['total']) &&
669 $progress['area']['total'] > $method['area']['total']) {
671 $progress['_action']['area']['total'] = TRUE;
672 if ($is_spam && $asap) break;
674 if(isset($method['area'][$key]) &&
675 $progress['area'][$key] > $method['area'][$key]) {
677 $progress['_action']['area'][$key] = TRUE;
678 if ($is_spam && $asap) break;
681 if ($is_spam && $asap) break;
684 //var_dump($method['area'], $is_spam);
686 // URI uniqueness (and removing non-uniques)
687 if ((! $is_spam || ! $asap) && isset($method['non_uniq'])) {
689 foreach ($pickups as $key => $pickup) {
690 $uris[$key] = uri_array_implode($pickup);
692 $count = count($uris);
693 $uris = array_unique($uris);
694 $progress['non_uniq'] += $count - count($uris);
695 if ($progress['non_uniq'] > $method['non_uniq']) {
697 $progress['_action']['non_uniq'] = TRUE;
699 if (! $asap || ! $is_spam) {
700 foreach (array_diff(array_keys($pickups),
701 array_keys($uris)) as $remove) {
702 unset($pickups[$remove]);
707 //var_dump($method['non_uniq'], $is_spam);
711 foreach ($pickups as $pickup) {
712 $hosts[] = & $pickup['host'];
714 $hosts = array_unique($hosts);
715 $progress['uniqhost'] += count($hosts);
716 //var_dump($method['uniqhost'], $is_spam);
719 if ((! $is_spam || ! $asap) && isset($method['badhost'])) {
720 $count = is_badhost($hosts, $asap);
721 $progress['badhost'] += $count;
723 $progress['_action']['badhost'] = TRUE;
727 //var_dump($method['badhost'], $is_spam);
731 return array($is_spam, $progress);
734 // ---------------------
738 // Summarize $progress (blocked only)
739 function summarize_check_uri_spam_progress($progress = array(), $shownum = TRUE)
741 //$list = check_uri_spam_method();
744 foreach (array_keys($progress['_action']) as $_action) {
745 if (is_array($progress['_action'][$_action])) {
746 foreach (array_keys($progress['_action'][$_action]) as $_area) {
747 $tmp[] = $_action . '=>' . $_area .
748 ($shownum ? '(' . $progress[$_action][$_area] . ')' : '');
752 ($shownum ? '(' . $progress[$_action] . ')' : '');
756 return implode(', ', $tmp);
759 // ---------------------
762 // Common bahavior for blocking
763 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
770 // ---------------------
773 // Simple/fast spam filter ($target: 'a string' or an array())
774 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $asap = FALSE)
778 list($is_spam, $progress) = check_uri_spam($target, $method, $asap);
781 // Mail to administrator(s)
782 if ($notify) pkwk_spamnotify($action, $page, $target, $progress);
788 // ---------------------
791 // Mail to administrator(s)
792 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array())
794 global $notify_subject;
796 $footer['ACTION'] = 'Blocked by: ' . summarize_check_uri_spam_progress($progress);
797 $footer['COMMENT'] = $action;
798 $footer['PAGE'] = '[blocked] ' . $page;
799 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
800 $footer['USER_AGENT'] = TRUE;
801 $footer['REMOTE_ADDR'] = TRUE;
802 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $footer);