2 // $Id: spam.php,v 1.45 2006/11/26 08:55:15 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'] === '') {
61 $array[$uri]['host'] = strtolower($array[$uri]['host']);
62 $array[$uri]['port'] = port_normalize($array[$uri]['port'], $array[$uri]['scheme'], FALSE);
63 $array[$uri]['path'] = path_normalize($array[$uri]['path']);
64 if ($preserve_rawuri) $array[$uri]['rawuri'] = & $array[$uri][0];
66 $array[$uri]['uri'] = & $array[$uri][0]; // Raw
68 unset($array[$uri][0]); // Matched string itself
69 if (! $preserve_chunk) {
71 $array[$uri]['scheme'],
72 $array[$uri]['userinfo'],
77 $array[$uri]['fragment']
81 $array[$uri]['area']['offset'] = $offset;
87 // Domain exposure callback (See spam_uri_pickup_preprocess())
88 // http://victim.example.org/?foo+site:nasty.example.com+bar
89 // => http://nasty.example.com/?refer=victim.example.org
90 // NOTE: 'refer=' is not so good for (at this time).
91 // Consider about using IP address of the victim, try to avoid that.
92 function _preg_replace_callback_domain_exposure($matches = array())
96 // Preserve the victim URI as a complicity or ...
97 if (isset($matches[5])) {
99 $matches[1] . '://' . // scheme
100 $matches[2] . '/' . // victim.example.org
101 $matches[3]; // The rest of all (before victim)
106 $matches[1] . '://' . // scheme
107 $matches[4] . // nasty.example.com
108 '/?refer=' . strtolower($matches[2]) . // victim.example.org
114 // Preprocess: rawurldecode() and adding space(s) and something
115 // to detect/count some URIs _if possible_
116 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
117 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
118 // [OK] http://victim.example.org/http://nasty.example.org
119 function spam_uri_pickup_preprocess($string = '')
121 if (! is_string($string)) return '';
123 $string = rawurldecode($string);
125 // Domain exposure (See _preg_replace_callback_domain_exposure())
126 $string = preg_replace_callback(
128 // Something Google: http://www.google.com/supported_domains
129 '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
130 '([a-z0-9?=&.%_+-]+)' . // ?query=foo+
131 '\bsite:([a-z0-9.%_-]+)' . // site:nasty.example.com
135 '_preg_replace_callback_domain_exposure',
139 // URI exposure (uriuri => uri uri)
140 $string = preg_replace(
142 '#(?<! )(?:https?|ftp):/#i',
143 // '#[a-z][a-z0-9.+-]{1,8}://#i',
144 // '#[a-z][a-z0-9.+-]{1,8}://#i'
153 // Main function of spam-uri pickup
154 function spam_uri_pickup($string = '', $area = array())
156 if (! is_array($area) || empty($area)) {
163 $string = spam_uri_pickup_preprocess($string);
165 $array = uri_pickup($string);
167 // Area elevation for '(especially external)link' intension
168 if (! empty($array)) {
170 $area_shadow = array();
171 foreach(array_keys($array) as $key){
172 $area_shadow[$key] = & $array[$key]['area'];
173 $area_shadow[$key]['anchor'] = 0;
174 $area_shadow[$key]['bbcode'] = 0;
177 // Anchor tags by preg_match_all()
178 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
179 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
180 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
181 // [NG] <a href= >Good site!</a> <a href= "#" >test</a>
182 if (isset($area['anchor'])) {
184 preg_match_all('#<a\b[^>]*href[^>]*>.*?</a\b[^>]*(>)#i',
185 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
186 //var_dump(recursive_map('htmlspecialchars', $areas));
187 foreach(array_keys($areas) as $_area) {
188 $areas[$_area] = array(
189 $areas[$_area][0][1], // Area start (<a href>)
190 $areas[$_area][1][1], // Area end (</a>)
193 area_measure($areas, $area_shadow, 1, 'anchor');
196 // phpBB's "BBCode" by preg_match_all()
197 // [url]http://nasty.example.com/[/url]
198 // [link]http://nasty.example.com/[/link]
199 // [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
200 // [link http://nasty.example.com/]buy something[/link]
202 if (isset($area['bbcode'])) {
204 preg_match_all('#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i',
205 $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
206 //var_dump(recursive_map('htmlspecialchars', $areas));
207 foreach(array_keys($areas) as $_area) {
208 $areas[$_area] = array(
209 $areas[$_area][0][1], // Area start ([url])
210 $areas[$_area][2][1], // Area end ([/url])
213 area_measure($areas, $area_shadow, 1, 'bbcode');
216 // Various Wiki syntax
217 // [text_or_uri>text_or_uri]
218 // [text_or_uri:text_or_uri]
219 // [text_or_uri|text_or_uri]
220 // [text_or_uri->text_or_uri]
221 // [text_or_uri text_or_uri] // MediaWiki
222 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
224 // Remove 'offset's for area_measure()
225 foreach(array_keys($array) as $key)
226 unset($array[$key]['area']['offset']);
232 // $array['something'] => $array['wanted']
233 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
235 if (! is_array($array) || ! is_array($keys)) return FALSE;
237 // Nondestructive test
239 foreach(array_keys($keys) as $from)
240 if (! isset($array[$from]))
243 foreach($keys as $from => $to) {
244 if ($from === $to) continue;
245 if (! $force || isset($array[$from])) {
246 $array[$to] = & $array[$from];
247 unset($array[$from]);
249 $array[$to] = $default;
256 // If in doubt, it's a little doubtful
257 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
259 if (! is_array($areas) || ! is_array($array)) return;
261 $areas_keys = array_keys($areas);
262 foreach(array_keys($array) as $u_index) {
263 $offset = isset($array[$u_index][$o_key]) ?
264 intval($array[$u_index][$o_key]) : 0;
265 foreach($areas_keys as $a_index) {
266 if (isset($array[$u_index][$a_key])) {
267 $offset_s = intval($areas[$a_index][0]);
268 $offset_e = intval($areas[$a_index][1]);
269 // [Area => inside <= Area]
270 if ($offset_s < $offset && $offset < $offset_e) {
271 $array[$u_index][$a_key] += $belief;
279 // ---------------------
282 // Scheme normalization: Renaming the schemes
283 // snntp://example.org => nntps://example.org
284 // NOTE: Keep the static lists simple. See also port_normalize().
285 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
287 // Abbreviations considerable they don't have link intension
288 static $abbrevs = array(
293 // Alias => normalized
294 static $aliases = array(
304 $scheme = strtolower(trim($scheme));
305 if (isset($abbrevs[$scheme])) {
306 if ($considerd_harmfull) {
307 $scheme = $abbrevs[$scheme];
312 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
317 // Port normalization: Suppress the (redundant) default port
318 // HTTP://example.org:80/ => http://example.org/
319 // HTTP://example.org:8080/ => http://example.org:8080/
320 // HTTPS://example.org:443/ => https://example.org/
321 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
323 // Schemes that users _maybe_ want to add protocol-handlers
324 // to their web browsers. (and attackers _maybe_ want to use ...)
325 // Reference: http://www.iana.org/assignments/port-numbers
326 static $array = array(
327 // scheme => default port
354 if ($port === '') return $port;
356 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
357 if (isset($array[$scheme]) && $port == $array[$scheme])
358 $port = ''; // Ignore the defaults
363 // Path normalization
364 // http://example.org => http://example.org/
365 // http://example.org#hoge => http://example.org/#hoge
366 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
367 // http://example.org/path/../../a/../back => http://example.org/back
368 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
370 if (! is_string($path) || $path == '') {
371 $path = $addroot ? $divider : '';
374 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
375 $array = explode($divider, $path);
378 foreach(array_keys($array) as $key) {
379 if ($array[$key] == '' || $array[$key] == '.')
384 foreach($array as $value) {
385 if ($value == '..') {
388 array_push($tmp, $value);
393 $path = $addroot ? $divider : '';
394 if (! empty($array)) $path .= implode($divider, $array) . $last;
400 // An URI array => An URI (See uri_pickup())
401 function uri_array_implode($uri = array())
403 if (empty($uri) || ! is_array($uri)) return NULL;
406 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
407 $tmp[] = & $uri['scheme'];
410 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
411 $tmp[] = & $uri['userinfo'];
414 if (isset($uri['host']) && $uri['host'] !== '') {
415 $tmp[] = & $uri['host'];
417 if (isset($uri['port']) && $uri['port'] !== '') {
419 $tmp[] = & $uri['port'];
421 if (isset($uri['path']) && $uri['path'] !== '') {
422 $tmp[] = & $uri['path'];
424 if (isset($uri['file']) && $uri['file'] !== '') {
425 $tmp[] = & $uri['file'];
427 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
429 $tmp[] = & $uri['fragment'];
432 return implode('', $tmp);
435 // ---------------------
436 // Part One : Checker
438 function generate_glob_regex($string = '', $divider = '/')
440 static $from = array(
465 $string = str_replace($from, $mid, $string); // Hide
466 $string = preg_quote($string, $divider);
467 $string = str_replace($mid, $to, $string); // Unhide
473 // TODO: require_or_include_once(another file) for Admin
474 function is_badhost($hosts = '', $asap = TRUE)
476 static $blocklist_regex;
478 if (! isset($blocklist_regex)) {
479 $blocklist_regex = array();
485 //'10.20.*.*', // 10.20.example.com also matches
488 // Too much malicious sub-domains
497 // 2006/11/19 17:50 dev
498 //'*.google0site.org',
499 //'*.bigpricesearch.org',
503 foreach ($blocklist as $part) {
504 $blocklist_regex[] = '#^' . generate_glob_regex($part, '#') . '$#i';
509 if (! is_array($hosts)) $hosts = array($hosts);
510 foreach($hosts as $host) {
511 if (! is_string($host)) $host = '';
512 foreach ($blocklist_regex as $regex) {
513 if (preg_match($regex, $host)) {
527 // Default (enabled) methods and thresholds
528 function check_uri_spam_method()
531 'quantity' => 8, // Allow N URIs
533 // 'total' => 0, // Allow N areas total, enabled below
534 'anchor' => 0, // Inside <a href> HTML tag
535 'bbcode' => 0, // Inside [url] or [link] BBCode
537 'non_uniq' => 3, // Allow N duped (and normalized) URIs
538 'badhost' => TRUE, // Check badhost
542 // TODO return TRUE or FALSE!
543 // Simple/fast spam check
544 function check_uri_spam($target = '', $method = array(), $asap = TRUE)
557 '_action' => array(),
560 if (! is_array($method) || empty($method)) {
561 $method = check_uri_spam_method();
564 if (is_array($target)) {
565 foreach($target as $str) {
567 list($is_spam, $_progress) = check_uri_spam($str, $method);
568 $progress['quantity'] += $_progress['quantity'];
569 $progress['area']['total'] += $_progress['area']['total'];
570 $progress['area']['anchor'] += $_progress['area']['anchor'];
571 $progress['area']['bbcode'] += $_progress['area']['bbcode'];
572 $progress['non_uniq'] += $_progress['non_uniq'];
573 $progress['uniqhost'] += $_progress['uniqhost'];
574 $progress['badhost'] += $_progress['badhost'];
575 if ($asap || $is_spam) break;
578 $pickups = spam_uri_pickup($target);
579 if (! empty($pickups)) {
580 $progress['quantity'] += count($pickups);
583 if ((! $is_spam || ! $asap) && isset($method['quantity']) &&
584 $progress['quantity'] > $method['quantity']) {
586 $progress['_action']['quantity'] = TRUE;
588 //var_dump($method['quantity'], $is_spam);
590 // Using invalid area
591 if ((! $is_spam || ! $asap) && isset($method['area'])) {
592 foreach($pickups as $pickup) {
593 foreach ($pickup['area'] as $key => $value) {
594 if ($key == 'offset') continue;
595 $progress['area']['total'] += $value;
596 $progress['area'][$key] += $value;
597 if (isset($method['area']['total']) &&
598 $progress['area']['total'] > $method['area']['total']) {
600 $progress['_action']['area']['total'] = TRUE;
601 if ($is_spam && $asap) break;
603 if(isset($method['area'][$key]) &&
604 $progress['area'][$key] > $method['area'][$key]) {
606 $progress['_action']['area'][$key] = TRUE;
607 if ($is_spam && $asap) break;
610 if ($is_spam && $asap) break;
613 //var_dump($method['area'], $is_spam);
615 // URI uniqueness (and removing non-uniques)
616 if ((! $is_spam || ! $asap) && isset($method['non_uniq'])) {
618 foreach ($pickups as $key => $pickup) {
619 $uris[$key] = uri_array_implode($pickup);
621 $count = count($uris);
622 $uris = array_unique($uris);
623 $progress['non_uniq'] += $count - count($uris);
624 if ($progress['non_uniq'] > $method['non_uniq']) {
626 $progress['_action']['non_uniq'] = TRUE;
628 if (! $asap || ! $is_spam) {
629 foreach (array_diff(array_keys($pickups),
630 array_keys($uris)) as $remove) {
631 unset($pickups[$remove]);
636 //var_dump($method['non_uniq'], $is_spam);
640 foreach ($pickups as $pickup) {
641 $hosts[] = & $pickup['host'];
643 $hosts = array_unique($hosts);
644 $progress['uniqhost'] += count($hosts);
645 //var_dump($method['uniqhost'], $is_spam);
648 if ((! $is_spam || ! $asap) && isset($method['badhost'])) {
649 $count = is_badhost($hosts, $asap);
650 $progress['badhost'] += $count;
652 $progress['_action']['badhost'] = TRUE;
656 //var_dump($method['badhost'], $is_spam);
660 return array($is_spam, $progress);
663 // ---------------------
666 // Summarize $progress
667 function summarize_check_uri_spam_progress($progress = array(), $shownum = TRUE)
670 foreach (array_keys($progress['_action']) as $_action) {
671 if (is_array($progress['_action'][$_action])) {
672 foreach (array_keys($progress['_action'][$_action]) as $_area) {
673 $tmp[] = $_action . '=>' . $_area .
674 ($shownum ? '(' . $progress[$_action][$_area] . ')' : '');
678 ($shownum ? '(' . $progress[$_action] . ')' : '');
682 return implode(', ', $tmp);
685 // Simple/fast spam filter ($target: 'a string' or an array())
686 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $asap = FALSE)
688 global $notify, $notify_subject;
690 list($is_spam, $progress) = check_uri_spam($target, $method, $asap);
692 // Mail to administrator(s)
693 if ($is_spam && $notify) {
694 $footer['BLOCKED'] = 'Blocked by: ' .
695 summarize_check_uri_spam_progress($progress);
696 $footer['ACTION'] = $action;
697 $footer['PAGE'] = '[blocked] ' . $page;
698 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
699 $footer['USER_AGENT'] = TRUE;
700 $footer['REMOTE_ADDR'] = TRUE;
701 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $footer);
705 if ($is_spam) spam_exit();
708 // ---------------------
710 // Common bahavior for blocking
711 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'