2 // $Id: spam.php,v 1.52 2006/12/02 09:22:37 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 and query string
36 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 7: Fragment
38 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
40 //var_dump(recursive_map('htmlspecialchars', $array));
43 static $parts = array(
44 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
45 5 => 'path', 6 => 'file', 7 => 'fragment'
48 foreach(array_keys($array) as $uri) {
49 array_rename_keys($array[$uri], $parts, TRUE, $default);
50 $offset = $array[$uri]['scheme'][1]; // Scheme's offset
52 foreach(array_keys($array[$uri]) as $part) {
53 // Remove offsets for each part
54 $array[$uri][$part] = & $array[$uri][$part][0];
58 $array[$uri]['scheme'] = scheme_normalize($array[$uri]['scheme']);
59 if ($array[$uri]['scheme'] === '') {
63 $array[$uri]['host'] = strtolower($array[$uri]['host']);
64 $array[$uri]['port'] = port_normalize($array[$uri]['port'], $array[$uri]['scheme'], FALSE);
65 $array[$uri]['path'] = path_normalize($array[$uri]['path']);
66 if ($preserve_rawuri) $array[$uri]['rawuri'] = & $array[$uri][0];
68 $array[$uri]['uri'] = & $array[$uri][0]; // Raw
70 unset($array[$uri][0]); // Matched string itself
71 if (! $preserve_chunk) {
73 $array[$uri]['scheme'],
74 $array[$uri]['userinfo'],
79 $array[$uri]['fragment']
83 $array[$uri]['area']['offset'] = $offset;
89 // Domain exposure callback (See spam_uri_pickup_preprocess())
90 // http://victim.example.org/?foo+site:nasty.example.com+bar
91 // => http://nasty.example.com/?refer=victim.example.org
92 // NOTE: 'refer=' is not so good for (at this time).
93 // Consider about using IP address of the victim, try to avoid that.
94 function _preg_replace_callback_domain_exposure($matches = array())
98 // Preserve the victim URI as a complicity or ...
99 if (isset($matches[5])) {
101 $matches[1] . '://' . // scheme
102 $matches[2] . '/' . // victim.example.org
103 $matches[3]; // The rest of all (before victim)
107 if (isset($matches[4])) {
109 $matches[1] . '://' . // scheme
110 $matches[4] . // nasty.example.com
111 '/?refer=' . strtolower($matches[2]) . // victim.example.org
118 // Preprocess: rawurldecode() and adding space(s) and something
119 // to detect/count some URIs _if possible_
120 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
121 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
122 // [OK] http://victim.example.org/http://nasty.example.org
123 function spam_uri_pickup_preprocess($string = '')
125 if (! is_string($string)) return '';
127 $string = rawurldecode($string);
129 // Domain exposure (See _preg_replace_callback_domain_exposure())
130 $string = preg_replace_callback(
132 // Something Google: http://www.google.com/supported_domains
133 '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
134 '([a-z0-9?=&.%_+-]+)' . // ?query=foo+
135 '\bsite:([a-z0-9.%_-]+)' . // site:nasty.example.com
136 //'()' . // Preserve or remove?
139 '_preg_replace_callback_domain_exposure',
143 // URI exposure (uriuri => uri uri)
144 $string = preg_replace(
146 '#(?<! )(?:https?|ftp):/#i',
147 // '#[a-z][a-z0-9.+-]{1,8}://#i',
148 // '#[a-z][a-z0-9.+-]{1,8}://#i'
157 // Main function of spam-uri pickup
158 function spam_uri_pickup($string = '', $area = array())
160 if (! is_array($area) || empty($area)) {
167 $string = spam_uri_pickup_preprocess($string);
169 $array = uri_pickup($string);
171 // Area elevation for '(especially external)link' intension
172 if (! empty($array)) {
174 $area_shadow = array();
175 foreach(array_keys($array) as $key){
176 $area_shadow[$key] = & $array[$key]['area'];
177 $area_shadow[$key]['anchor'] = 0;
178 $area_shadow[$key]['bbcode'] = 0;
181 // Anchor tags by preg_match_all()
182 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
183 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
184 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
185 // [NG] <a href= >Good site!</a> <a href= "#" >test</a>
186 if (isset($area['anchor'])) {
188 preg_match_all('#<a\b[^>]*href[^>]*>.*?</a\b[^>]*(>)#i',
189 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
190 //var_dump(recursive_map('htmlspecialchars', $areas));
191 foreach(array_keys($areas) as $_area) {
192 $areas[$_area] = array(
193 $areas[$_area][0][1], // Area start (<a href>)
194 $areas[$_area][1][1], // Area end (</a>)
197 area_measure($areas, $area_shadow, 1, 'anchor');
200 // phpBB's "BBCode" by preg_match_all()
201 // [url]http://nasty.example.com/[/url]
202 // [link]http://nasty.example.com/[/link]
203 // [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
204 // [link http://nasty.example.com/]buy something[/link]
206 if (isset($area['bbcode'])) {
208 preg_match_all('#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i',
209 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
210 //var_dump(recursive_map('htmlspecialchars', $areas));
211 foreach(array_keys($areas) as $_area) {
212 $areas[$_area] = array(
213 $areas[$_area][0][1], // Area start ([url])
214 $areas[$_area][2][1], // Area end ([/url])
217 area_measure($areas, $area_shadow, 1, 'bbcode');
220 // Various Wiki syntax
221 // [text_or_uri>text_or_uri]
222 // [text_or_uri:text_or_uri]
223 // [text_or_uri|text_or_uri]
224 // [text_or_uri->text_or_uri]
225 // [text_or_uri text_or_uri] // MediaWiki
226 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
228 // Remove 'offset's for area_measure()
229 foreach(array_keys($array) as $key)
230 unset($array[$key]['area']['offset']);
236 // $array['something'] => $array['wanted']
237 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
239 if (! is_array($array) || ! is_array($keys)) return FALSE;
241 // Nondestructive test
243 foreach(array_keys($keys) as $from)
244 if (! isset($array[$from]))
247 foreach($keys as $from => $to) {
248 if ($from === $to) continue;
249 if (! $force || isset($array[$from])) {
250 $array[$to] = & $array[$from];
251 unset($array[$from]);
253 $array[$to] = $default;
260 // If in doubt, it's a little doubtful
261 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
263 if (! is_array($areas) || ! is_array($array)) return;
265 $areas_keys = array_keys($areas);
266 foreach(array_keys($array) as $u_index) {
267 $offset = isset($array[$u_index][$o_key]) ?
268 intval($array[$u_index][$o_key]) : 0;
269 foreach($areas_keys as $a_index) {
270 if (isset($array[$u_index][$a_key])) {
271 $offset_s = intval($areas[$a_index][0]);
272 $offset_e = intval($areas[$a_index][1]);
273 // [Area => inside <= Area]
274 if ($offset_s < $offset && $offset < $offset_e) {
275 $array[$u_index][$a_key] += $belief;
283 // ---------------------
286 // Scheme normalization: Renaming the schemes
287 // snntp://example.org => nntps://example.org
288 // NOTE: Keep the static lists simple. See also port_normalize().
289 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
291 // Abbreviations considerable they don't have link intension
292 static $abbrevs = array(
297 // Alias => normalized
298 static $aliases = array(
308 $scheme = strtolower(trim($scheme));
309 if (isset($abbrevs[$scheme])) {
310 if ($considerd_harmfull) {
311 $scheme = $abbrevs[$scheme];
316 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
321 // Port normalization: Suppress the (redundant) default port
322 // HTTP://example.org:80/ => http://example.org/
323 // HTTP://example.org:8080/ => http://example.org:8080/
324 // HTTPS://example.org:443/ => https://example.org/
325 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
327 // Schemes that users _maybe_ want to add protocol-handlers
328 // to their web browsers. (and attackers _maybe_ want to use ...)
329 // Reference: http://www.iana.org/assignments/port-numbers
330 static $array = array(
331 // scheme => default port
358 if ($port === '') return $port;
360 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
361 if (isset($array[$scheme]) && $port == $array[$scheme])
362 $port = ''; // Ignore the defaults
367 // Path normalization
368 // http://example.org => http://example.org/
369 // http://example.org#hoge => http://example.org/#hoge
370 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
371 // http://example.org/path/../../a/../back => http://example.org/back
372 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
374 if (! is_string($path) || $path == '') {
375 $path = $addroot ? $divider : '';
378 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
379 $array = explode($divider, $path);
382 foreach(array_keys($array) as $key) {
383 if ($array[$key] == '' || $array[$key] == '.')
388 foreach($array as $value) {
389 if ($value == '..') {
392 array_push($tmp, $value);
397 $path = $addroot ? $divider : '';
398 if (! empty($array)) $path .= implode($divider, $array) . $last;
404 // An URI array => An URI (See uri_pickup())
405 function uri_array_implode($uri = array())
407 if (empty($uri) || ! is_array($uri)) return NULL;
410 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
411 $tmp[] = & $uri['scheme'];
414 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
415 $tmp[] = & $uri['userinfo'];
418 if (isset($uri['host']) && $uri['host'] !== '') {
419 $tmp[] = & $uri['host'];
421 if (isset($uri['port']) && $uri['port'] !== '') {
423 $tmp[] = & $uri['port'];
425 if (isset($uri['path']) && $uri['path'] !== '') {
426 $tmp[] = & $uri['path'];
428 if (isset($uri['file']) && $uri['file'] !== '') {
429 $tmp[] = & $uri['file'];
431 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
433 $tmp[] = & $uri['fragment'];
436 return implode('', $tmp);
439 // ---------------------
440 // Part One : Checker
442 function generate_glob_regex($string = '', $divider = '/')
444 static $from = array(
447 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
463 if (is_array($string)) {
467 array_map('generate_glob_regex',
469 array_pad(array(), count($string), $divider)
474 $string = str_replace($from, $mid, $string); // Hide
475 $string = preg_quote($string, $divider);
476 $string = str_replace($mid, $to, $string); // Unhide
482 // TODO: preg_grep() ?
484 function is_badhost($hosts = '', $asap = TRUE)
488 if (! isset($regex)) {
490 $regex['badhost'] = array();
494 $blocklist['badhost'] = array(
495 //'*', // Deny all uri
496 //'10.20.*.*', // 10.20.example.com also matches
497 //'*.blogspot.com', // Blog services subdomains
498 //array('blogspot.com', '*.blogspot.com')
500 foreach ($blocklist['badhost'] as $part) {
501 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
506 if (file_exists(SPAM_INI_FILE)) {
507 $blocklist = array();
508 require(SPAM_INI_FILE);
509 foreach ($blocklist['badhost'] as $part) {
510 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
517 if (! is_array($hosts)) $hosts = array($hosts);
519 foreach($hosts as $host) {
520 if (! is_string($host)) $host = '';
523 foreach ($regex['badhost'] as $_regex) {
524 if (preg_match($_regex, $host)) {
538 // Default (enabled) methods and thresholds
539 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
541 $times = intval($times);
542 $t_area = intval($t_area);
546 'quantity' => 8 * $times, // Allow N URIs
547 'non_uniq' => 3 * $times, // Allow N duped (and normalized) URIs
552 //'total' => $t_area, // Allow N areas total, enabled below
553 'anchor' => $t_area, // Inside <a href> HTML tag
554 'bbcode' => $t_area, // Inside [url] or [link] BBCode
559 'badhost' => TRUE, // Check badhost
563 foreach (array_keys($method) as $key) {
564 if ($method[$key] < 0) unset($method[$key]);
566 foreach (array_keys($area) as $key) {
567 if ($area[$key] < 0) unset($area[$key]);
569 $area = empty($area) ? array() : array('area' => $area);
570 $rules = $rule ? $rules : array();
572 return $method + $area + $rules;
576 // TODO return TRUE or FALSE!
577 // Simple/fast spam check
578 function check_uri_spam($target = '', $method = array(), $asap = TRUE)
591 '_action' => array(),
594 if (! is_array($method) || empty($method)) {
595 $method = check_uri_spam_method();
598 if (is_array($target)) {
600 foreach($target as $str) {
601 list($_is_spam, $_progress) = check_uri_spam($str, $method, $asap);
602 $is_spam = $is_spam || $_is_spam;
603 $progress['quantity'] += $_progress['quantity'];
604 $progress['area']['total'] += $_progress['area']['total'];
605 $progress['area']['anchor'] += $_progress['area']['anchor'];
606 $progress['area']['bbcode'] += $_progress['area']['bbcode'];
607 $progress['non_uniq'] += $_progress['non_uniq'];
608 $progress['uniqhost'] += $_progress['uniqhost'];
609 $progress['badhost'] += $_progress['badhost'];
610 foreach($_progress['_action'] as $key => $value) {
611 if (is_array($value)) {
612 foreach(array_keys($value) as $_key) {
613 $progress['_action'][$key][$_key] = TRUE;
616 $progress['_action'][$key] = TRUE;
619 if ($is_spam && $asap) break;
622 $pickups = spam_uri_pickup($target);
623 if (! empty($pickups)) {
624 $progress['quantity'] += count($pickups);
627 if ((! $is_spam || ! $asap) && isset($method['quantity']) &&
628 $progress['quantity'] > $method['quantity']) {
630 $progress['_action']['quantity'] = TRUE;
632 //var_dump($method['quantity'], $is_spam);
634 // Using invalid area
635 if ((! $is_spam || ! $asap) && isset($method['area'])) {
636 foreach($pickups as $pickup) {
637 foreach ($pickup['area'] as $key => $value) {
638 if ($key == 'offset') continue;
639 $progress['area']['total'] += $value;
640 $progress['area'][$key] += $value;
641 if (isset($method['area']['total']) &&
642 $progress['area']['total'] > $method['area']['total']) {
644 $progress['_action']['area']['total'] = TRUE;
645 if ($is_spam && $asap) break;
647 if(isset($method['area'][$key]) &&
648 $progress['area'][$key] > $method['area'][$key]) {
650 $progress['_action']['area'][$key] = TRUE;
651 if ($is_spam && $asap) break;
654 if ($is_spam && $asap) break;
657 //var_dump($method['area'], $is_spam);
659 // URI uniqueness (and removing non-uniques)
660 if ((! $is_spam || ! $asap) && isset($method['non_uniq'])) {
662 foreach ($pickups as $key => $pickup) {
663 $uris[$key] = uri_array_implode($pickup);
665 $count = count($uris);
666 $uris = array_unique($uris);
667 $progress['non_uniq'] += $count - count($uris);
668 if ($progress['non_uniq'] > $method['non_uniq']) {
670 $progress['_action']['non_uniq'] = TRUE;
672 if (! $asap || ! $is_spam) {
673 foreach (array_diff(array_keys($pickups),
674 array_keys($uris)) as $remove) {
675 unset($pickups[$remove]);
680 //var_dump($method['non_uniq'], $is_spam);
684 foreach ($pickups as $pickup) {
685 $hosts[] = & $pickup['host'];
687 $hosts = array_unique($hosts);
688 $progress['uniqhost'] += count($hosts);
689 //var_dump($method['uniqhost'], $is_spam);
692 if ((! $is_spam || ! $asap) && isset($method['badhost'])) {
693 $count = is_badhost($hosts, $asap);
694 $progress['badhost'] += $count;
696 $progress['_action']['badhost'] = TRUE;
700 //var_dump($method['badhost'], $is_spam);
704 return array($is_spam, $progress);
707 // ---------------------
711 // Summarize $progress (blocked only)
712 function summarize_check_uri_spam_progress($progress = array(), $shownum = TRUE)
714 //$list = check_uri_spam_method();
717 foreach (array_keys($progress['_action']) as $_action) {
718 if (is_array($progress['_action'][$_action])) {
719 foreach (array_keys($progress['_action'][$_action]) as $_area) {
720 $tmp[] = $_action . '=>' . $_area .
721 ($shownum ? '(' . $progress[$_action][$_area] . ')' : '');
725 ($shownum ? '(' . $progress[$_action] . ')' : '');
729 return implode(', ', $tmp);
732 // ---------------------
735 // Common bahavior for blocking
736 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
743 // ---------------------
746 // Simple/fast spam filter ($target: 'a string' or an array())
747 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $asap = FALSE)
751 list($is_spam, $progress) = check_uri_spam($target, $method, $asap);
753 // Mail to administrator(s)
756 pkwk_spamnotify($action, $page, $target, $progress);
762 // ---------------------
765 // Mail to administrator(s)
766 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array())
768 global $notify_subject;
770 $footer['BLOCKED'] = 'Blocked by: ' .
771 summarize_check_uri_spam_progress($progress);
772 $footer['ACTION'] = 'Blocked: ' . $action;
773 $footer['PAGE'] = '[blocked] ' . $page;
774 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
775 $footer['USER_AGENT'] = TRUE;
776 $footer['REMOTE_ADDR'] = TRUE;
777 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $footer);