2 // $Id: spam.php,v 1.63 2006/12/10 02:31:18 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 tags by preg_match_all()
189 // [OK] <a href=></a>
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" 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 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
243 if (! is_array($areas) || ! is_array($array)) return;
245 $areas_keys = array_keys($areas);
246 foreach(array_keys($array) as $u_index) {
247 $offset = isset($array[$u_index][$o_key]) ?
248 intval($array[$u_index][$o_key]) : 0;
249 foreach($areas_keys as $a_index) {
250 if (isset($array[$u_index][$a_key])) {
251 $offset_s = intval($areas[$a_index][0]);
252 $offset_e = intval($areas[$a_index][1]);
253 // [Area => inside <= Area]
254 if ($offset_s < $offset && $offset < $offset_e) {
255 $array[$u_index][$a_key] += $belief;
262 // ---------------------
265 // Domain exposure callback (See spam_uri_pickup_preprocess())
266 // http://victim.example.org/?foo+site:nasty.example.com+bar
267 // => http://nasty.example.com/?refer=victim.example.org
268 // NOTE: 'refer=' is not so good for (at this time).
269 // Consider about using IP address of the victim, try to avoid that.
270 function _preg_replace_callback_domain_exposure($matches = array())
274 // Preserve the victim URI as a complicity or ...
275 if (isset($matches[5])) {
277 $matches[1] . '://' . // scheme
278 $matches[2] . '/' . // victim.example.org
279 $matches[3]; // The rest of all (before victim)
283 if (isset($matches[4])) {
285 $matches[1] . '://' . // scheme
286 $matches[4] . // nasty.example.com
287 '/?refer=' . strtolower($matches[2]) . // victim.example.org
294 // Preprocess: rawurldecode() and adding space(s) and something
295 // to detect/count some URIs _if possible_
296 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
297 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
298 // [OK] http://victim.example.org/http://nasty.example.org
299 function spam_uri_pickup_preprocess($string = '')
301 if (! is_string($string)) return '';
303 $string = rawurldecode($string);
305 // Domain exposure (See _preg_replace_callback_domain_exposure())
306 $string = preg_replace_callback(
308 // Something Google: http://www.google.com/supported_domains
309 '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
310 '([a-z0-9?=&.%_+-]+)' . // ?query=foo+
311 '\bsite:([a-z0-9.%_-]+)' . // site:nasty.example.com
312 //'()' . // Preserve or remove?
315 '_preg_replace_callback_domain_exposure',
319 // URI exposure (uriuri => uri uri)
320 $string = preg_replace(
322 '#(?<! )(?:https?|ftp):/#i',
323 // '#[a-z][a-z0-9.+-]{1,8}://#i',
324 // '#[a-z][a-z0-9.+-]{1,8}://#i'
333 // Main function of spam-uri pickup
334 function spam_uri_pickup($string = '', $area = array())
336 if (! is_array($area) || empty($area)) {
343 $string = spam_uri_pickup_preprocess($string);
345 $array = uri_pickup($string);
347 // Area elevation for '(especially external)link' intension
348 if (! empty($array)) {
349 $areas = area_pickup($string, $area);
350 if (! empty($areas)) {
351 $area_shadow = array();
352 foreach(array_keys($array) as $key){
353 $area_shadow[$key] = & $array[$key]['area'];
354 $area_shadow[$key]['anchor'] = 0;
355 $area_shadow[$key]['bbcode'] = 0;
357 if (isset($areas['anchor'])) {
358 area_measure($areas['anchor'], $area_shadow, 1, 'anchor');
360 if (isset($areas['bbcode'])) {
361 area_measure($areas['bbcode'], $area_shadow, 1, 'bbcode');
366 // Remove 'offset's for area_measure()
367 foreach(array_keys($array) as $key)
368 unset($array[$key]['area']['offset']);
374 // ---------------------
377 // Scheme normalization: Renaming the schemes
378 // snntp://example.org => nntps://example.org
379 // NOTE: Keep the static lists simple. See also port_normalize().
380 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
382 // Abbreviations considerable they don't have link intension
383 static $abbrevs = array(
388 // Alias => normalized
389 static $aliases = array(
399 $scheme = strtolower(trim($scheme));
400 if (isset($abbrevs[$scheme])) {
401 if ($considerd_harmfull) {
402 $scheme = $abbrevs[$scheme];
407 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
412 // Port normalization: Suppress the (redundant) default port
413 // HTTP://example.org:80/ => http://example.org/
414 // HTTP://example.org:8080/ => http://example.org:8080/
415 // HTTPS://example.org:443/ => https://example.org/
416 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
418 // Schemes that users _maybe_ want to add protocol-handlers
419 // to their web browsers. (and attackers _maybe_ want to use ...)
420 // Reference: http://www.iana.org/assignments/port-numbers
421 static $array = array(
422 // scheme => default port
449 if ($port === '') return $port;
451 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
452 if (isset($array[$scheme]) && $port == $array[$scheme])
453 $port = ''; // Ignore the defaults
458 // Path normalization
459 // http://example.org => http://example.org/
460 // http://example.org#hoge => http://example.org/#hoge
461 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
462 // http://example.org/path/../../a/../back => http://example.org/back
463 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
465 if (! is_string($path) || $path == '')
466 return $addroot ? $divider : '';
469 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
470 $array = explode($divider, $path);
473 foreach(array_keys($array) as $key) {
474 if ($array[$key] == '' || $array[$key] == '.')
479 foreach($array as $value) {
480 if ($value == '..') {
483 array_push($tmp, $value);
488 $path = $addroot ? $divider : '';
489 if (! empty($array)) $path .= implode($divider, $array) . $last;
494 // DirectoryIndex normalize (Destructive and rough)
495 function file_normalize($string = 'index.html.en')
497 static $array = array(
498 'index' => TRUE, // Some system can omit the suffix
500 'index.html' => TRUE,
501 'index.shtml' => TRUE,
504 'index.php3' => TRUE,
505 'index.php4' => TRUE,
506 //'index.pl' => TRUE,
507 //'index.py' => TRUE,
508 //'index.rb' => TRUE,
510 'default.htm' => TRUE,
511 'default.html' => TRUE,
512 'default.asp' => TRUE,
513 'default.aspx' => TRUE,
516 // Content-negothiation filter:
517 // Roughly removing ISO 639 -like
518 // 2-letter suffixes (See RFC3066)
520 if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
521 $_string = $matches[1];
523 $_string = & $string;
526 if (isset($array[strtolower($_string)])) {
533 // Sort query-strings if possible (Destructive and rough)
534 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
535 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
536 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
538 $array = explode('&', $string);
540 // Remove '&' paddings
541 foreach(array_keys($array) as $key) {
542 if ($array[$key] == '') {
547 // Consider '='-sepalated input and paddings
549 $equals = $not_equals = array();
550 foreach ($array as $part) {
551 if (strpos($part, '=') === FALSE) {
552 $not_equals[] = $part;
554 list($key, $value) = explode('=', $part, 2);
555 $value = ltrim($value, '=');
556 if (! $equal_cutempty || $value != '') {
557 $equals[$key] = $value;
562 $array = & $not_equals;
563 foreach ($equals as $key => $value) {
564 $array[] = $key . '=' . $value;
570 return implode('&', $array);
573 // ---------------------
574 // Part One : Checker
576 function generate_glob_regex($string = '', $divider = '/')
578 static $from = array(
581 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
597 if (is_array($string)) {
601 array_map('generate_glob_regex',
603 array_pad(array(), count($string), $divider)
608 $string = str_replace($from, $mid, $string); // Hide
609 $string = preg_quote($string, $divider);
610 $string = str_replace($mid, $to, $string); // Unhide
616 // TODO: preg_grep() ?
618 function is_badhost($hosts = '', $asap = TRUE)
622 if (! isset($regex)) {
624 $regex['badhost'] = array();
628 $blocklist['badhost'] = array(
629 //'*', // Deny all uri
630 //'10.20.*.*', // 10.20.example.com also matches
631 //'*.blogspot.com', // Blog services subdomains
632 //array('blogspot.com', '*.blogspot.com')
634 foreach ($blocklist['badhost'] as $part) {
635 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
640 if (file_exists(SPAM_INI_FILE)) {
641 $blocklist = array();
642 require(SPAM_INI_FILE);
643 foreach ($blocklist['badhost'] as $part) {
644 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
651 if (! is_array($hosts)) $hosts = array($hosts);
653 foreach($hosts as $host) {
654 if (! is_string($host)) $host = '';
657 foreach ($regex['badhost'] as $_regex) {
658 if (preg_match($_regex, $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 // TODO: Simplify $progress data structure
712 // TODO: Simplify. !empty(['is_spam']) just means $is_spam
713 // Simple/fast spam check
714 function check_uri_spam($target = '', $method = array())
717 if (! is_array($method) || empty($method)) {
718 $method = check_uri_spam_method();
720 $asap = isset($method['asap']) ? $method['asap'] : TRUE;
732 'is_spam' => array(),
733 'method' => & $method,
737 if (is_array($target)) {
739 foreach($target as $str) {
740 list($_is_spam, $_progress) = check_uri_spam($str, $method);
741 $is_spam = $is_spam || $_is_spam;
742 foreach (array_keys($_progress['sum']) as $key) {
743 $progress['sum'][$key] += $_progress['sum'][$key];
745 foreach(array_keys($_progress['is_spam']) as $key) {
746 $progress['is_spam'][$key] = TRUE;
748 if ($is_spam && $asap) break;
751 $pickups = spam_uri_pickup($target);
752 if (! empty($pickups)) {
753 $progress['sum']['quantity'] += count($pickups);
756 if ((! $is_spam || ! $asap) && isset($method['quantity']) &&
757 $progress['sum']['quantity'] > $method['quantity']) {
759 $progress['is_spam']['quantity'] = TRUE;
761 //var_dump($method['quantity'], $is_spam);
763 // Using invalid area
764 if ((! $is_spam || ! $asap) && isset($method['area'])) {
765 foreach($pickups as $pickup) {
766 foreach ($pickup['area'] as $key => $value) {
767 if ($key == 'offset') continue;
768 $p_key = 'area_' . $key;
769 $progress['sum']['area_total'] += $value;
770 $progress['sum'][$p_key] += $value;
771 if (isset($method['area']['total']) &&
772 $progress['sum']['area_total'] > $method['area']['total']) {
774 $progress['is_spam']['area_total'] = TRUE;
775 if ($is_spam && $asap) break;
777 if(isset($method['area'][$key]) &&
778 $progress['sum'][$p_key] > $method['area'][$key]) {
780 $progress['is_spam'][$p_key] = TRUE;
781 if ($is_spam && $asap) break;
784 if ($is_spam && $asap) break;
787 //var_dump($method['area'], $is_spam);
790 // URI uniqueness (and removing non-uniques)
791 if ((! $is_spam || ! $asap) && 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 $progress['sum']['non_uniq'] += $count - count($uris);
803 if ($progress['sum']['non_uniq'] > $method['non_uniq']) {
805 $progress['is_spam']['non_uniq'] = TRUE;
807 if (! $asap || ! $is_spam) {
808 foreach (array_diff(array_keys($pickups),
809 array_keys($uris)) as $remove) {
810 unset($pickups[$remove]);
815 //var_dump($method['non_uniq'], $is_spam);
819 foreach ($pickups as $pickup) {
820 $hosts[] = & $pickup['host'];
822 $hosts = array_unique($hosts);
823 $progress['sum']['uniqhost'] += count($hosts);
824 //var_dump($method['uniqhost'], $is_spam);
827 if ((! $is_spam || ! $asap) && isset($method['badhost'])) {
828 $count = is_badhost($hosts, $asap);
829 $progress['sum']['badhost'] += $count;
831 $progress['is_spam']['badhost'] = TRUE;
835 //var_dump($method['badhost'], $is_spam);
839 return array($is_spam, $progress);
842 // ---------------------
845 // TODO: Don't show unused $method!
846 // Summarize $progress (blocked only)
847 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
849 $method = $progress['method'];
850 if (isset($method['area'])) {
851 foreach(array_keys($method['area']) as $key) {
852 $method['area_' . $key] = TRUE;
857 $tmp = array_keys($progress['is_spam']);
860 foreach ($progress['sum'] as $key => $value) {
861 if (isset($method[$key])) {
862 $tmp[] = $key . '(' . $value . ')';
867 return implode(', ', $tmp);
870 // ---------------------
873 // Common bahavior for blocking
874 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
881 // ---------------------
885 // Simple/fast spam filter ($target: 'a string' or an array())
886 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array())
890 list($is_spam, $progress) = check_uri_spam($target, $method);
893 // Mail to administrator(s)
894 if ($notify) pkwk_spamnotify($action, $page, $target, $progress, $method);
900 // ---------------------
903 // Mail to administrator(s)
904 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
906 global $notify_subject;
908 $asap = isset($method['asap']) ? $method['asap'] : TRUE;
910 $footer['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
913 $footer['METRICS'] = summarize_spam_progress($progress);
915 $footer['COMMENT'] = $action;
916 $footer['PAGE'] = '[blocked] ' . $page;
917 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
918 $footer['USER_AGENT'] = TRUE;
919 $footer['REMOTE_ADDR'] = TRUE;
920 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $footer);