2 // $Id: spam.php,v 1.62 2006/12/09 12:18:52 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 // Domain exposure callback (See spam_uri_pickup_preprocess())
184 // http://victim.example.org/?foo+site:nasty.example.com+bar
185 // => http://nasty.example.com/?refer=victim.example.org
186 // NOTE: 'refer=' is not so good for (at this time).
187 // Consider about using IP address of the victim, try to avoid that.
188 function _preg_replace_callback_domain_exposure($matches = array())
192 // Preserve the victim URI as a complicity or ...
193 if (isset($matches[5])) {
195 $matches[1] . '://' . // scheme
196 $matches[2] . '/' . // victim.example.org
197 $matches[3]; // The rest of all (before victim)
201 if (isset($matches[4])) {
203 $matches[1] . '://' . // scheme
204 $matches[4] . // nasty.example.com
205 '/?refer=' . strtolower($matches[2]) . // victim.example.org
212 // Preprocess: rawurldecode() and adding space(s) and something
213 // to detect/count some URIs _if possible_
214 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
215 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
216 // [OK] http://victim.example.org/http://nasty.example.org
217 function spam_uri_pickup_preprocess($string = '')
219 if (! is_string($string)) return '';
221 $string = rawurldecode($string);
223 // Domain exposure (See _preg_replace_callback_domain_exposure())
224 $string = preg_replace_callback(
226 // Something Google: http://www.google.com/supported_domains
227 '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
228 '([a-z0-9?=&.%_+-]+)' . // ?query=foo+
229 '\bsite:([a-z0-9.%_-]+)' . // site:nasty.example.com
230 //'()' . // Preserve or remove?
233 '_preg_replace_callback_domain_exposure',
237 // URI exposure (uriuri => uri uri)
238 $string = preg_replace(
240 '#(?<! )(?:https?|ftp):/#i',
241 // '#[a-z][a-z0-9.+-]{1,8}://#i',
242 // '#[a-z][a-z0-9.+-]{1,8}://#i'
251 // Main function of spam-uri pickup
252 function spam_uri_pickup($string = '', $area = array())
254 if (! is_array($area) || empty($area)) {
261 $string = spam_uri_pickup_preprocess($string);
263 $array = uri_pickup($string);
265 // Area elevation for '(especially external)link' intension
266 if (! empty($array)) {
268 $area_shadow = array();
269 foreach(array_keys($array) as $key){
270 $area_shadow[$key] = & $array[$key]['area'];
271 $area_shadow[$key]['anchor'] = 0;
272 $area_shadow[$key]['bbcode'] = 0;
275 // Anchor tags by preg_match_all()
276 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
277 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
278 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
279 // [NG] <a href= >Good site!</a> <a href= "#" >test</a>
280 if (isset($area['anchor'])) {
282 preg_match_all('#<a\b[^>]*href[^>]*>.*?</a\b[^>]*(>)#i',
283 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
284 //var_dump(recursive_map('htmlspecialchars', $areas));
285 foreach(array_keys($areas) as $_area) {
286 $areas[$_area] = array(
287 $areas[$_area][0][1], // Area start (<a href>)
288 $areas[$_area][1][1], // Area end (</a>)
291 area_measure($areas, $area_shadow, 1, 'anchor');
294 // phpBB's "BBCode" by preg_match_all()
295 // [url]http://nasty.example.com/[/url]
296 // [link]http://nasty.example.com/[/link]
297 // [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
298 // [link http://nasty.example.com/]buy something[/link]
300 if (isset($area['bbcode'])) {
302 preg_match_all('#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i',
303 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
304 //var_dump(recursive_map('htmlspecialchars', $areas));
305 foreach(array_keys($areas) as $_area) {
306 $areas[$_area] = array(
307 $areas[$_area][0][1], // Area start ([url])
308 $areas[$_area][2][1], // Area end ([/url])
311 area_measure($areas, $area_shadow, 1, 'bbcode');
314 // Various Wiki syntax
315 // [text_or_uri>text_or_uri]
316 // [text_or_uri:text_or_uri]
317 // [text_or_uri|text_or_uri]
318 // [text_or_uri->text_or_uri]
319 // [text_or_uri text_or_uri] // MediaWiki
320 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
322 // Remove 'offset's for area_measure()
323 foreach(array_keys($array) as $key)
324 unset($array[$key]['area']['offset']);
330 // If in doubt, it's a little doubtful
331 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
333 if (! is_array($areas) || ! is_array($array)) return;
335 $areas_keys = array_keys($areas);
336 foreach(array_keys($array) as $u_index) {
337 $offset = isset($array[$u_index][$o_key]) ?
338 intval($array[$u_index][$o_key]) : 0;
339 foreach($areas_keys as $a_index) {
340 if (isset($array[$u_index][$a_key])) {
341 $offset_s = intval($areas[$a_index][0]);
342 $offset_e = intval($areas[$a_index][1]);
343 // [Area => inside <= Area]
344 if ($offset_s < $offset && $offset < $offset_e) {
345 $array[$u_index][$a_key] += $belief;
352 // ---------------------
355 // Scheme normalization: Renaming the schemes
356 // snntp://example.org => nntps://example.org
357 // NOTE: Keep the static lists simple. See also port_normalize().
358 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
360 // Abbreviations considerable they don't have link intension
361 static $abbrevs = array(
366 // Alias => normalized
367 static $aliases = array(
377 $scheme = strtolower(trim($scheme));
378 if (isset($abbrevs[$scheme])) {
379 if ($considerd_harmfull) {
380 $scheme = $abbrevs[$scheme];
385 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
390 // Port normalization: Suppress the (redundant) default port
391 // HTTP://example.org:80/ => http://example.org/
392 // HTTP://example.org:8080/ => http://example.org:8080/
393 // HTTPS://example.org:443/ => https://example.org/
394 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
396 // Schemes that users _maybe_ want to add protocol-handlers
397 // to their web browsers. (and attackers _maybe_ want to use ...)
398 // Reference: http://www.iana.org/assignments/port-numbers
399 static $array = array(
400 // scheme => default port
427 if ($port === '') return $port;
429 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
430 if (isset($array[$scheme]) && $port == $array[$scheme])
431 $port = ''; // Ignore the defaults
436 // Path normalization
437 // http://example.org => http://example.org/
438 // http://example.org#hoge => http://example.org/#hoge
439 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
440 // http://example.org/path/../../a/../back => http://example.org/back
441 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
443 if (! is_string($path) || $path == '')
444 return $addroot ? $divider : '';
447 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
448 $array = explode($divider, $path);
451 foreach(array_keys($array) as $key) {
452 if ($array[$key] == '' || $array[$key] == '.')
457 foreach($array as $value) {
458 if ($value == '..') {
461 array_push($tmp, $value);
466 $path = $addroot ? $divider : '';
467 if (! empty($array)) $path .= implode($divider, $array) . $last;
472 // DirectoryIndex normalize (Destructive and rough)
473 function file_normalize($string = 'index.html.en')
475 static $array = array(
476 'index' => TRUE, // Some system can omit the suffix
478 'index.html' => TRUE,
479 'index.shtml' => TRUE,
482 'index.php3' => TRUE,
483 'index.php4' => TRUE,
484 //'index.pl' => TRUE,
485 //'index.py' => TRUE,
486 //'index.rb' => TRUE,
488 'default.htm' => TRUE,
489 'default.html' => TRUE,
490 'default.asp' => TRUE,
491 'default.aspx' => TRUE,
494 // Content-negothiation filter:
495 // Roughly removing ISO 639 -like
496 // 2-letter suffixes (See RFC3066)
498 if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
499 $_string = $matches[1];
501 $_string = & $string;
504 if (isset($array[strtolower($_string)])) {
511 // Sort query-strings if possible (Destructive and rough)
512 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
513 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
514 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
516 $array = explode('&', $string);
518 // Remove '&' paddings
519 foreach(array_keys($array) as $key) {
520 if ($array[$key] == '') {
525 // Consider '='-sepalated input and paddings
527 $equals = $not_equals = array();
528 foreach ($array as $part) {
529 if (strpos($part, '=') === FALSE) {
530 $not_equals[] = $part;
532 list($key, $value) = explode('=', $part, 2);
533 $value = ltrim($value, '=');
534 if (! $equal_cutempty || $value != '') {
535 $equals[$key] = $value;
540 $array = & $not_equals;
541 foreach ($equals as $key => $value) {
542 $array[] = $key . '=' . $value;
548 return implode('&', $array);
551 // ---------------------
552 // Part One : Checker
554 function generate_glob_regex($string = '', $divider = '/')
556 static $from = array(
559 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
575 if (is_array($string)) {
579 array_map('generate_glob_regex',
581 array_pad(array(), count($string), $divider)
586 $string = str_replace($from, $mid, $string); // Hide
587 $string = preg_quote($string, $divider);
588 $string = str_replace($mid, $to, $string); // Unhide
594 // TODO: preg_grep() ?
596 function is_badhost($hosts = '', $asap = TRUE)
600 if (! isset($regex)) {
602 $regex['badhost'] = array();
606 $blocklist['badhost'] = array(
607 //'*', // Deny all uri
608 //'10.20.*.*', // 10.20.example.com also matches
609 //'*.blogspot.com', // Blog services subdomains
610 //array('blogspot.com', '*.blogspot.com')
612 foreach ($blocklist['badhost'] as $part) {
613 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
618 if (file_exists(SPAM_INI_FILE)) {
619 $blocklist = array();
620 require(SPAM_INI_FILE);
621 foreach ($blocklist['badhost'] as $part) {
622 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
629 if (! is_array($hosts)) $hosts = array($hosts);
631 foreach($hosts as $host) {
632 if (! is_string($host)) $host = '';
635 foreach ($regex['badhost'] as $_regex) {
636 if (preg_match($_regex, $host)) {
650 // Default (enabled) methods and thresholds
651 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
653 $times = intval($times);
654 $t_area = intval($t_area);
658 'quantity' => 8 * $times, // Allow N URIs
659 'non_uniq' => 3 * $times, // Allow N duped (and normalized) URIs
664 //'total' => $t_area, // Allow N areas total, enabled below
665 'anchor' => $t_area, // Inside <a href> HTML tag
666 'bbcode' => $t_area, // Inside [url] or [link] BBCode
671 'asap' => FALSE, // Quit As Soon As Possible
672 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
673 'badhost' => TRUE, // Check badhost
677 foreach (array_keys($method) as $key) {
678 if ($method[$key] < 0) unset($method[$key]);
680 foreach (array_keys($area) as $key) {
681 if ($area[$key] < 0) unset($area[$key]);
683 $area = empty($area) ? array() : array('area' => $area);
684 $rules = $rule ? $rules : array();
686 return $method + $area + $rules;
689 // TODO: Simplify $progress data structure
690 // TODO: Simplify. !empty(['is_spam']) just means $is_spam
691 // Simple/fast spam check
692 function check_uri_spam($target = '', $method = array())
695 if (! is_array($method) || empty($method)) {
696 $method = check_uri_spam_method();
698 $asap = isset($method['asap']) ? $method['asap'] : TRUE;
710 'is_spam' => array(),
711 'method' => & $method,
715 if (is_array($target)) {
717 foreach($target as $str) {
718 list($_is_spam, $_progress) = check_uri_spam($str, $method);
719 $is_spam = $is_spam || $_is_spam;
720 foreach (array_keys($_progress['sum']) as $key) {
721 $progress['sum'][$key] += $_progress['sum'][$key];
723 foreach(array_keys($_progress['is_spam']) as $key) {
724 $progress['is_spam'][$key] = TRUE;
726 if ($is_spam && $asap) break;
729 $pickups = spam_uri_pickup($target);
730 if (! empty($pickups)) {
731 $progress['sum']['quantity'] += count($pickups);
734 if ((! $is_spam || ! $asap) && isset($method['quantity']) &&
735 $progress['sum']['quantity'] > $method['quantity']) {
737 $progress['is_spam']['quantity'] = TRUE;
739 //var_dump($method['quantity'], $is_spam);
741 // Using invalid area
742 if ((! $is_spam || ! $asap) && isset($method['area'])) {
743 foreach($pickups as $pickup) {
744 foreach ($pickup['area'] as $key => $value) {
745 if ($key == 'offset') continue;
746 $p_key = 'area_' . $key;
747 $progress['sum']['area_total'] += $value;
748 $progress['sum'][$p_key] += $value;
749 if (isset($method['area']['total']) &&
750 $progress['sum']['area_total'] > $method['area']['total']) {
752 $progress['is_spam']['area_total'] = TRUE;
753 if ($is_spam && $asap) break;
755 if(isset($method['area'][$key]) &&
756 $progress['sum'][$p_key] > $method['area'][$key]) {
758 $progress['is_spam'][$p_key] = TRUE;
759 if ($is_spam && $asap) break;
762 if ($is_spam && $asap) break;
765 //var_dump($method['area'], $is_spam);
768 // URI uniqueness (and removing non-uniques)
769 if ((! $is_spam || ! $asap) && isset($method['non_uniq'])) {
771 // Destructive normalize of URIs
772 uri_array_normalize($pickups);
775 foreach (array_keys($pickups) as $key) {
776 $uris[$key] = uri_array_implode($pickups[$key]);
778 $count = count($uris);
779 $uris = array_unique($uris);
780 $progress['sum']['non_uniq'] += $count - count($uris);
781 if ($progress['sum']['non_uniq'] > $method['non_uniq']) {
783 $progress['is_spam']['non_uniq'] = TRUE;
785 if (! $asap || ! $is_spam) {
786 foreach (array_diff(array_keys($pickups),
787 array_keys($uris)) as $remove) {
788 unset($pickups[$remove]);
793 //var_dump($method['non_uniq'], $is_spam);
797 foreach ($pickups as $pickup) {
798 $hosts[] = & $pickup['host'];
800 $hosts = array_unique($hosts);
801 $progress['sum']['uniqhost'] += count($hosts);
802 //var_dump($method['uniqhost'], $is_spam);
805 if ((! $is_spam || ! $asap) && isset($method['badhost'])) {
806 $count = is_badhost($hosts, $asap);
807 $progress['sum']['badhost'] += $count;
809 $progress['is_spam']['badhost'] = TRUE;
813 //var_dump($method['badhost'], $is_spam);
817 return array($is_spam, $progress);
820 // ---------------------
823 // TODO: Don't show unused $method!
824 // Summarize $progress (blocked only)
825 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
827 $method = $progress['method'];
828 if (isset($method['area'])) {
829 foreach(array_keys($method['area']) as $key) {
830 $method['area_' . $key] = TRUE;
835 $tmp = array_keys($progress['is_spam']);
838 foreach ($progress['sum'] as $key => $value) {
839 if (isset($method[$key])) {
840 $tmp[] = $key . '(' . $value . ')';
845 return implode(', ', $tmp);
848 // ---------------------
851 // Common bahavior for blocking
852 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
859 // ---------------------
863 // Simple/fast spam filter ($target: 'a string' or an array())
864 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array())
868 list($is_spam, $progress) = check_uri_spam($target, $method);
871 // Mail to administrator(s)
872 if ($notify) pkwk_spamnotify($action, $page, $target, $progress, $method);
878 // ---------------------
881 // Mail to administrator(s)
882 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
884 global $notify_subject;
886 $asap = isset($method['asap']) ? $method['asap'] : TRUE;
888 $footer['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
891 $footer['METRICS'] = summarize_spam_progress($progress);
893 $footer['COMMENT'] = $action;
894 $footer['PAGE'] = '[blocked] ' . $page;
895 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
896 $footer['USER_AGENT'] = TRUE;
897 $footer['REMOTE_ADDR'] = TRUE;
898 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $footer);