2 // $Id: spam.php,v 1.40 2006/11/26 02:57:26 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 // Return an array of URIs in the $string
9 // [OK] http://nasty.example.org#nasty_string
10 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
11 // [OK] ftp://nasty.example.org:80/dfsdfs
12 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
13 function uri_pickup($string = '', $normalize = TRUE,
14 $preserve_rawuri = FALSE, $preserve_chunk = TRUE)
16 // Not available for: IDN(ignored)
19 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
20 // Refer RFC3986 (Regex below is not strict)
21 '#(\b[a-z][a-z0-9.+-]{1,8})://' . // 1: Scheme
23 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
27 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
28 '(?:[0-9]{1-3}\.){3}[0-9]{1-3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
29 '[^\s<>"\'\[\]:/\#?]+' . // FQDN: foo.example.org
31 '(?::([0-9]*))?' . // 4: Port
32 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
33 '([^\s<>"\'\[\]\#]+)?' . // 6: File and query string
34 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 7: Fragment
36 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
38 //var_dump(recursive_map('htmlspecialchars', $array));
41 static $parts = array(
42 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
43 5 => 'path', 6 => 'file', 7 => 'fragment'
46 foreach(array_keys($array) as $uri) {
47 array_rename_keys($array[$uri], $parts, TRUE, $default);
48 $offset = $array[$uri]['scheme'][1]; // Scheme's offset
50 foreach(array_keys($array[$uri]) as $part) {
51 // Remove offsets for each part
52 $array[$uri][$part] = & $array[$uri][$part][0];
56 $array[$uri]['scheme'] = scheme_normalize($array[$uri]['scheme']);
57 //if ($array[$uri]['scheme'] === '') {
59 // unset ($array[$uri]);
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 //$array[$uri]['uri'] = uri_array_implode($array[$uri]);
67 if ($preserve_rawuri) $array[$uri]['rawuri'] = & $array[$uri][0];
69 $array[$uri]['uri'] = & $array[$uri][0]; // Raw
71 unset($array[$uri][0]); // Matched string itself
72 if (! $preserve_chunk) {
74 $array[$uri]['scheme'],
75 $array[$uri]['userinfo'],
80 $array[$uri]['fragment']
84 $array[$uri]['area']['offset'] = $offset;
90 // Domain exposure callback (See spam_uri_pickup_preprocess())
91 // http://victim.example.org/?foo+site:nasty.example.com+bar
92 // => http://nasty.example.com/?refer=victim.example.org
93 // NOTE: 'refer=' is not so good for (at this time).
94 // Consider about using IP address of the victim, try to avoid that.
95 function _preg_replace_callback_domain_exposure($matches = array())
99 // Preserve the victim URI as a complicity or ...
100 if (isset($matches[5])) {
102 $matches[1] . '://' . // scheme
103 $matches[2] . '/' . // victim.example.org
104 $matches[3]; // The rest of all (before victim)
109 $matches[1] . '://' . // scheme
110 $matches[4] . // nasty.example.com
111 '/?refer=' . strtolower($matches[2]) . // victim.example.org
117 // Preprocess: rawurldecode() and adding space(s) 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):/#',
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]['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))
240 // Nondestructive test
242 foreach(array_keys($keys) as $from)
243 if (! isset($array[$from]))
246 foreach($keys as $from => $to) {
247 if ($from === $to) continue;
248 if (! $force || isset($array[$from])) {
249 $array[$to] = & $array[$from];
250 unset($array[$from]);
252 $array[$to] = $default;
259 // If in doubt, it's a little doubtful
260 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
262 if (! is_array($areas) || ! is_array($array)) return;
264 $areas_keys = array_keys($areas);
265 foreach(array_keys($array) as $u_index) {
266 $offset = isset($array[$u_index][$o_key]) ?
267 intval($array[$u_index][$o_key]) : 0;
268 foreach($areas_keys as $a_index) {
269 if (isset($array[$u_index][$a_key])) {
270 $offset_s = intval($areas[$a_index][0]);
271 $offset_e = intval($areas[$a_index][1]);
272 // [Area => inside <= Area]
273 if ($offset_s < $offset && $offset < $offset_e) {
274 $array[$u_index][$a_key] += $belief;
282 // ---------------------
285 // Scheme normalization: Renaming the schemes
286 // snntp://example.org => nntps://example.org
287 // NOTE: Keep the static lists simple. See also port_normalize().
288 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
290 // Abbreviations considerable they don't have link intension
291 static $abbrevs = array(
296 // Alias => normalized
297 static $aliases = array(
307 $scheme = strtolower(trim($scheme));
308 if (isset($abbrevs[$scheme])) {
309 if ($considerd_harmfull) {
310 $scheme = $abbrevs[$scheme];
315 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
320 // Port normalization: Suppress the (redundant) default port
321 // HTTP://example.org:80/ => http://example.org/
322 // HTTP://example.org:8080/ => http://example.org:8080/
323 // HTTPS://example.org:443/ => https://example.org/
324 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
326 // Schemes that users _maybe_ want to add protocol-handlers
327 // to their web browsers. (and attackers _maybe_ want to use ...)
328 // Reference: http://www.iana.org/assignments/port-numbers
329 static $array = array(
330 // scheme => default port
357 if ($port === '') return $port;
359 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
360 if (isset($array[$scheme]) && $port == $array[$scheme])
361 $port = ''; // Ignore the defaults
366 // Path normalization
367 // http://example.org => http://example.org/
368 // http://example.org#hoge => http://example.org/#hoge
369 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
370 // http://example.org/path/../../a/../back => http://example.org/back
371 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
373 if (! is_string($path) || $path == '') {
374 $path = $addroot ? $divider : '';
377 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
378 $array = explode($divider, $path);
381 foreach(array_keys($array) as $key) {
382 if ($array[$key] == '' || $array[$key] == '.')
387 foreach($array as $value) {
388 if ($value == '..') {
391 array_push($tmp, $value);
396 $path = $addroot ? $divider : '';
397 if (! empty($array)) $path .= implode($divider, $array) . $last;
403 // An URI array => An URI (See uri_pickup())
404 function uri_array_implode($uri = array())
406 if (empty($uri) || ! is_array($uri)) return NULL;
409 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
410 $tmp[] = & $uri['scheme'];
413 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
414 $tmp[] = & $uri['userinfo'];
417 if (isset($uri['host']) && $uri['host'] !== '') {
418 $tmp[] = & $uri['host'];
420 if (isset($uri['port']) && $uri['port'] !== '') {
422 $tmp[] = & $uri['port'];
424 if (isset($uri['path']) && $uri['path'] !== '') {
425 $tmp[] = & $uri['path'];
427 if (isset($uri['file']) && $uri['file'] !== '') {
428 $tmp[] = & $uri['file'];
430 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
432 $tmp[] = & $uri['fragment'];
435 return implode('', $tmp);
438 // ---------------------
439 // Part One : Checker
441 function generate_glob_regex($string = '', $divider = '/')
443 static $from = array(
468 $string = str_replace($from, $mid, $string); // Hide
469 $string = preg_quote($string, $divider);
470 $string = str_replace($mid, $to, $string); // Unhide
476 // TODO: require_or_include_once(another file)
477 function is_badhost($hosts = '', $asap = TRUE)
479 static $blocklist_regex;
481 if (! isset($blocklist_regex)) {
482 $blocklist_regex = array();
488 //'10.20.*.*', // 10.20.example.com also matches
491 // Too much malicious sub-domains
500 // 2006/11/19 17:50 dev
501 //'*.google0site.org',
502 //'*.bigpricesearch.org',
506 foreach ($blocklist as $part) {
507 $blocklist_regex[] = '#^' . generate_glob_regex($part, '#') . '$#i';
512 if (! is_array($hosts)) $hosts = array($hosts);
513 foreach($hosts as $host) {
514 if (! is_string($host)) $host = '';
515 foreach ($blocklist_regex as $regex) {
516 if (preg_match($regex, $host)) {
521 break; // Check next host
530 // Default method and threshold
531 function check_uri_spam_method()
534 'quantity' => 8, // Allow N URIs
536 'total' => 0, // Allow N areas
537 'anchor' => 0, // <a href> HTML tag
538 'bbcode' => 0, // [url] or [link] BBCode
540 'non_uniq' => 3, // Allow N duped (and normalized) URIs
545 // TODO return TRUE or FALSE!
546 // Simple/fast spam check
547 function check_uri_spam($target = '', $method = array(), $asap = TRUE)
562 if (! is_array($method) || empty($method)) {
563 $method = check_uri_spam_method();
566 if (is_array($target)) {
567 foreach($target as $str) {
569 list($is_spam, $_progress) = check_uri_spam($str, $method);
570 $progress['quantity'] += $_progress['quantity'];
571 $progress['area']['total'] += $_progress['area']['total'];
572 $progress['area']['anchor'] += $_progress['area']['anchor'];
573 $progress['area']['bbcode'] += $_progress['area']['bbcode'];
574 $progress['non_uniq'] += $_progress['non_uniq'];
575 $progress['uniqhost'] += $_progress['uniqhost'];
576 $progress['badhost'] += $_progress['badhost'];
577 if ($asap || $is_spam) break;
580 $pickups = spam_uri_pickup($target);
581 $progress['quantity'] += count($pickups);
583 if (! empty($pickups)) {
586 if ((! $is_spam || ! $asap) && isset($method['quantity']) &&
587 $progress['quantity'] > $method['quantity']) {
590 //var_dump($method['quantity'], $is_spam);
592 // Using invalid area
593 if ((! $is_spam || ! $asap) && isset($method['area'])) {
594 foreach($pickups as $pickup) {
597 foreach ($pickup['area'] as $key => $value) {
598 if ($key == 'offset') continue;
599 $progress['area']['total'] += $value;
600 $progress['area'][$key] += $value;
603 if ($is_spam && $asap) break;
609 //var_dump($method['area'], $is_spam);
611 // URI uniqueness (and removing non-uniques)
612 if ((! $is_spam || ! $asap) && isset($method['non_uniq'])) {
614 foreach ($pickups as $key => $pickup) {
615 $uris[$key] = uri_array_implode($pickup);
617 $count = count($uris);
618 $uris = array_unique($uris);
619 $progress['non_uniq'] += $count - count($uris);
620 if ($progress['non_uniq'] > $method['non_uniq']) {
623 if (! $asap || ! $is_spam) {
624 foreach (array_diff(array_keys($pickups),
625 array_keys($uris)) as $remove) {
626 unset($pickups[$remove]);
630 //var_dump($uris, $pickups);
632 //var_dump($method['non_uniq'], $is_spam);
636 foreach ($pickups as $pickup) {
637 $hosts[] = & $pickup['host'];
639 $hosts = array_unique($hosts);
640 $progress['uniqhost'] += count($hosts);
641 //var_dump($method['uniqhost'], $is_spam);
644 if ((! $is_spam || ! $asap) && isset($method['badhost'])) {
645 $count = is_badhost($hosts, $asap);
646 $progress['badhost'] += $count;
647 if ($count !== 0) $is_spam = TRUE;
649 //var_dump($method['badhost'], $is_spam);
653 return array($is_spam, $progress);
656 // ---------------------
658 // Check User-Agent (not testing yet)
659 function is_invalid_useragent($ua_name = '' /*, $ua_vars = ''*/ )
661 return $ua_name === '';
664 // ---------------------
666 // TODO: Separate check-part(s) and mail part
667 // TODO: Mail to administrator with more measurement data?
668 // Simple/fast spam filter ($target: 'a string' or an array())
669 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array())
673 //$is_spam = is_invalid_useragent('NOTYET');
675 $action .= ' (Invalid User-Agent)';
677 list($is_spam) = check_uri_spam($target, $method);
681 // Mail to administrator(s)
682 global $notify, $notify_subject;
684 $footer['ACTION'] = $action;
685 $footer['PAGE'] = '[blocked] ' . $page;
686 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
687 $footer['USER_AGENT'] = TRUE;
688 $footer['REMOTE_ADDR'] = TRUE;
689 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $footer);
694 if ($is_spam) spam_exit();
697 // ---------------------
699 // Common bahavior for blocking
700 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'