2 // $Id: spam.php,v 1.51 2006/12/02 09:19:51 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)
108 $matches[1] . '://' . // scheme
109 $matches[4] . // nasty.example.com
110 '/?refer=' . strtolower($matches[2]) . // victim.example.org
116 // Preprocess: rawurldecode() and adding space(s) and something
117 // to detect/count some URIs _if possible_
118 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
119 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
120 // [OK] http://victim.example.org/http://nasty.example.org
121 function spam_uri_pickup_preprocess($string = '')
123 if (! is_string($string)) return '';
125 $string = rawurldecode($string);
127 // Domain exposure (See _preg_replace_callback_domain_exposure())
128 $string = preg_replace_callback(
130 // Something Google: http://www.google.com/supported_domains
131 '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
132 '([a-z0-9?=&.%_+-]+)' . // ?query=foo+
133 '\bsite:([a-z0-9.%_-]+)' . // site:nasty.example.com
137 '_preg_replace_callback_domain_exposure',
141 // URI exposure (uriuri => uri uri)
142 $string = preg_replace(
144 '#(?<! )(?:https?|ftp):/#i',
145 // '#[a-z][a-z0-9.+-]{1,8}://#i',
146 // '#[a-z][a-z0-9.+-]{1,8}://#i'
155 // Main function of spam-uri pickup
156 function spam_uri_pickup($string = '', $area = array())
158 if (! is_array($area) || empty($area)) {
165 $string = spam_uri_pickup_preprocess($string);
167 $array = uri_pickup($string);
169 // Area elevation for '(especially external)link' intension
170 if (! empty($array)) {
172 $area_shadow = array();
173 foreach(array_keys($array) as $key){
174 $area_shadow[$key] = & $array[$key]['area'];
175 $area_shadow[$key]['anchor'] = 0;
176 $area_shadow[$key]['bbcode'] = 0;
179 // Anchor tags by preg_match_all()
180 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
181 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
182 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
183 // [NG] <a href= >Good site!</a> <a href= "#" >test</a>
184 if (isset($area['anchor'])) {
186 preg_match_all('#<a\b[^>]*href[^>]*>.*?</a\b[^>]*(>)#i',
187 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
188 //var_dump(recursive_map('htmlspecialchars', $areas));
189 foreach(array_keys($areas) as $_area) {
190 $areas[$_area] = array(
191 $areas[$_area][0][1], // Area start (<a href>)
192 $areas[$_area][1][1], // Area end (</a>)
195 area_measure($areas, $area_shadow, 1, 'anchor');
198 // phpBB's "BBCode" by preg_match_all()
199 // [url]http://nasty.example.com/[/url]
200 // [link]http://nasty.example.com/[/link]
201 // [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
202 // [link http://nasty.example.com/]buy something[/link]
204 if (isset($area['bbcode'])) {
206 preg_match_all('#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i',
207 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
208 //var_dump(recursive_map('htmlspecialchars', $areas));
209 foreach(array_keys($areas) as $_area) {
210 $areas[$_area] = array(
211 $areas[$_area][0][1], // Area start ([url])
212 $areas[$_area][2][1], // Area end ([/url])
215 area_measure($areas, $area_shadow, 1, 'bbcode');
218 // Various Wiki syntax
219 // [text_or_uri>text_or_uri]
220 // [text_or_uri:text_or_uri]
221 // [text_or_uri|text_or_uri]
222 // [text_or_uri->text_or_uri]
223 // [text_or_uri text_or_uri] // MediaWiki
224 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
226 // Remove 'offset's for area_measure()
227 foreach(array_keys($array) as $key)
228 unset($array[$key]['area']['offset']);
234 // $array['something'] => $array['wanted']
235 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
237 if (! is_array($array) || ! is_array($keys)) return FALSE;
239 // Nondestructive test
241 foreach(array_keys($keys) as $from)
242 if (! isset($array[$from]))
245 foreach($keys as $from => $to) {
246 if ($from === $to) continue;
247 if (! $force || isset($array[$from])) {
248 $array[$to] = & $array[$from];
249 unset($array[$from]);
251 $array[$to] = $default;
258 // If in doubt, it's a little doubtful
259 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
261 if (! is_array($areas) || ! is_array($array)) return;
263 $areas_keys = array_keys($areas);
264 foreach(array_keys($array) as $u_index) {
265 $offset = isset($array[$u_index][$o_key]) ?
266 intval($array[$u_index][$o_key]) : 0;
267 foreach($areas_keys as $a_index) {
268 if (isset($array[$u_index][$a_key])) {
269 $offset_s = intval($areas[$a_index][0]);
270 $offset_e = intval($areas[$a_index][1]);
271 // [Area => inside <= Area]
272 if ($offset_s < $offset && $offset < $offset_e) {
273 $array[$u_index][$a_key] += $belief;
281 // ---------------------
284 // Scheme normalization: Renaming the schemes
285 // snntp://example.org => nntps://example.org
286 // NOTE: Keep the static lists simple. See also port_normalize().
287 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
289 // Abbreviations considerable they don't have link intension
290 static $abbrevs = array(
295 // Alias => normalized
296 static $aliases = array(
306 $scheme = strtolower(trim($scheme));
307 if (isset($abbrevs[$scheme])) {
308 if ($considerd_harmfull) {
309 $scheme = $abbrevs[$scheme];
314 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
319 // Port normalization: Suppress the (redundant) default port
320 // HTTP://example.org:80/ => http://example.org/
321 // HTTP://example.org:8080/ => http://example.org:8080/
322 // HTTPS://example.org:443/ => https://example.org/
323 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
325 // Schemes that users _maybe_ want to add protocol-handlers
326 // to their web browsers. (and attackers _maybe_ want to use ...)
327 // Reference: http://www.iana.org/assignments/port-numbers
328 static $array = array(
329 // scheme => default port
356 if ($port === '') return $port;
358 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
359 if (isset($array[$scheme]) && $port == $array[$scheme])
360 $port = ''; // Ignore the defaults
365 // Path normalization
366 // http://example.org => http://example.org/
367 // http://example.org#hoge => http://example.org/#hoge
368 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
369 // http://example.org/path/../../a/../back => http://example.org/back
370 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
372 if (! is_string($path) || $path == '') {
373 $path = $addroot ? $divider : '';
376 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
377 $array = explode($divider, $path);
380 foreach(array_keys($array) as $key) {
381 if ($array[$key] == '' || $array[$key] == '.')
386 foreach($array as $value) {
387 if ($value == '..') {
390 array_push($tmp, $value);
395 $path = $addroot ? $divider : '';
396 if (! empty($array)) $path .= implode($divider, $array) . $last;
402 // An URI array => An URI (See uri_pickup())
403 function uri_array_implode($uri = array())
405 if (empty($uri) || ! is_array($uri)) return NULL;
408 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
409 $tmp[] = & $uri['scheme'];
412 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
413 $tmp[] = & $uri['userinfo'];
416 if (isset($uri['host']) && $uri['host'] !== '') {
417 $tmp[] = & $uri['host'];
419 if (isset($uri['port']) && $uri['port'] !== '') {
421 $tmp[] = & $uri['port'];
423 if (isset($uri['path']) && $uri['path'] !== '') {
424 $tmp[] = & $uri['path'];
426 if (isset($uri['file']) && $uri['file'] !== '') {
427 $tmp[] = & $uri['file'];
429 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
431 $tmp[] = & $uri['fragment'];
434 return implode('', $tmp);
437 // ---------------------
438 // Part One : Checker
440 function generate_glob_regex($string = '', $divider = '/')
442 static $from = array(
445 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
461 if (is_array($string)) {
465 array_map('generate_glob_regex',
467 array_pad(array(), count($string), $divider)
472 $string = str_replace($from, $mid, $string); // Hide
473 $string = preg_quote($string, $divider);
474 $string = str_replace($mid, $to, $string); // Unhide
480 // TODO: preg_grep() ?
482 function is_badhost($hosts = '', $asap = TRUE)
486 if (! isset($regex)) {
488 $regex['badhost'] = array();
492 $blocklist['badhost'] = array(
493 //'*', // Deny all uri
494 //'10.20.*.*', // 10.20.example.com also matches
495 //'*.blogspot.com', // Blog services subdomains
496 //array('blogspot.com', '*.blogspot.com')
498 foreach ($blocklist['badhost'] as $part) {
499 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
504 if (file_exists(SPAM_INI_FILE)) {
505 $blocklist = array();
506 require(SPAM_INI_FILE);
507 foreach ($blocklist['badhost'] as $part) {
508 $regex['badhost'][] = '/^' . generate_glob_regex($part) . '$/i';
515 if (! is_array($hosts)) $hosts = array($hosts);
517 foreach($hosts as $host) {
518 if (! is_string($host)) $host = '';
521 foreach ($regex['badhost'] as $_regex) {
522 if (preg_match($_regex, $host)) {
536 // Default (enabled) methods and thresholds
537 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
539 $times = intval($times);
540 $t_area = intval($t_area);
544 'quantity' => 8 * $times, // Allow N URIs
545 'non_uniq' => 3 * $times, // Allow N duped (and normalized) URIs
550 //'total' => $t_area, // Allow N areas total, enabled below
551 'anchor' => $t_area, // Inside <a href> HTML tag
552 'bbcode' => $t_area, // Inside [url] or [link] BBCode
557 'badhost' => TRUE, // Check badhost
561 foreach (array_keys($method) as $key) {
562 if ($method[$key] < 0) unset($method[$key]);
564 foreach (array_keys($area) as $key) {
565 if ($area[$key] < 0) unset($area[$key]);
567 $area = empty($area) ? array() : array('area' => $area);
568 $rules = $rule ? $rules : array();
570 return $method + $area + $rules;
574 // TODO return TRUE or FALSE!
575 // Simple/fast spam check
576 function check_uri_spam($target = '', $method = array(), $asap = TRUE)
589 '_action' => array(),
592 if (! is_array($method) || empty($method)) {
593 $method = check_uri_spam_method();
596 if (is_array($target)) {
598 foreach($target as $str) {
599 list($_is_spam, $_progress) = check_uri_spam($str, $method, $asap);
600 $is_spam = $is_spam || $_is_spam;
601 $progress['quantity'] += $_progress['quantity'];
602 $progress['area']['total'] += $_progress['area']['total'];
603 $progress['area']['anchor'] += $_progress['area']['anchor'];
604 $progress['area']['bbcode'] += $_progress['area']['bbcode'];
605 $progress['non_uniq'] += $_progress['non_uniq'];
606 $progress['uniqhost'] += $_progress['uniqhost'];
607 $progress['badhost'] += $_progress['badhost'];
608 foreach($_progress['_action'] as $key => $value) {
609 if (is_array($value)) {
610 foreach(array_keys($value) as $_key) {
611 $progress['_action'][$key][$_key] = TRUE;
614 $progress['_action'][$key] = TRUE;
617 if ($is_spam && $asap) break;
620 $pickups = spam_uri_pickup($target);
621 if (! empty($pickups)) {
622 $progress['quantity'] += count($pickups);
625 if ((! $is_spam || ! $asap) && isset($method['quantity']) &&
626 $progress['quantity'] > $method['quantity']) {
628 $progress['_action']['quantity'] = TRUE;
630 //var_dump($method['quantity'], $is_spam);
632 // Using invalid area
633 if ((! $is_spam || ! $asap) && isset($method['area'])) {
634 foreach($pickups as $pickup) {
635 foreach ($pickup['area'] as $key => $value) {
636 if ($key == 'offset') continue;
637 $progress['area']['total'] += $value;
638 $progress['area'][$key] += $value;
639 if (isset($method['area']['total']) &&
640 $progress['area']['total'] > $method['area']['total']) {
642 $progress['_action']['area']['total'] = TRUE;
643 if ($is_spam && $asap) break;
645 if(isset($method['area'][$key]) &&
646 $progress['area'][$key] > $method['area'][$key]) {
648 $progress['_action']['area'][$key] = TRUE;
649 if ($is_spam && $asap) break;
652 if ($is_spam && $asap) break;
655 //var_dump($method['area'], $is_spam);
657 // URI uniqueness (and removing non-uniques)
658 if ((! $is_spam || ! $asap) && isset($method['non_uniq'])) {
660 foreach ($pickups as $key => $pickup) {
661 $uris[$key] = uri_array_implode($pickup);
663 $count = count($uris);
664 $uris = array_unique($uris);
665 $progress['non_uniq'] += $count - count($uris);
666 if ($progress['non_uniq'] > $method['non_uniq']) {
668 $progress['_action']['non_uniq'] = TRUE;
670 if (! $asap || ! $is_spam) {
671 foreach (array_diff(array_keys($pickups),
672 array_keys($uris)) as $remove) {
673 unset($pickups[$remove]);
678 //var_dump($method['non_uniq'], $is_spam);
682 foreach ($pickups as $pickup) {
683 $hosts[] = & $pickup['host'];
685 $hosts = array_unique($hosts);
686 $progress['uniqhost'] += count($hosts);
687 //var_dump($method['uniqhost'], $is_spam);
690 if ((! $is_spam || ! $asap) && isset($method['badhost'])) {
691 $count = is_badhost($hosts, $asap);
692 $progress['badhost'] += $count;
694 $progress['_action']['badhost'] = TRUE;
698 //var_dump($method['badhost'], $is_spam);
702 return array($is_spam, $progress);
705 // ---------------------
709 // Summarize $progress (blocked only)
710 function summarize_check_uri_spam_progress($progress = array(), $shownum = TRUE)
712 //$list = check_uri_spam_method();
715 foreach (array_keys($progress['_action']) as $_action) {
716 if (is_array($progress['_action'][$_action])) {
717 foreach (array_keys($progress['_action'][$_action]) as $_area) {
718 $tmp[] = $_action . '=>' . $_area .
719 ($shownum ? '(' . $progress[$_action][$_area] . ')' : '');
723 ($shownum ? '(' . $progress[$_action] . ')' : '');
727 return implode(', ', $tmp);
730 // ---------------------
733 // Common bahavior for blocking
734 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
741 // ---------------------
744 // Simple/fast spam filter ($target: 'a string' or an array())
745 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $asap = FALSE)
749 list($is_spam, $progress) = check_uri_spam($target, $method, $asap);
751 // Mail to administrator(s)
754 pkwk_spamnotify($action, $page, $target, $progress);
760 // ---------------------
763 // Mail to administrator(s)
764 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array())
766 global $notify_subject;
768 $footer['BLOCKED'] = 'Blocked by: ' .
769 summarize_check_uri_spam_progress($progress);
770 $footer['ACTION'] = 'Blocked: ' . $action;
771 $footer['PAGE'] = '[blocked] ' . $page;
772 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
773 $footer['USER_AGENT'] = TRUE;
774 $footer['REMOTE_ADDR'] = TRUE;
775 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $footer);