OSDN Git Service

Added scheme_normalize(), port_normalize()
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.19 2006/11/18 06:35:26 henoheno Exp $
3 // Copyright (C) 2006 PukiWiki Developers Team
4 // License: GPL v2 or (at your option) any later version
5
6 // Functions for Concept-work of spam-uri metrics
7
8 // Return an array of URIs in the $string
9 // [OK] http://nasty.example.org#nasty_string
10 // [OK] http://nasty.example.org/foo/xxx#nasty_string/bar
11 // [OK] ftp://dfshodfs:80/dfsdfs
12 function uri_pickup($string = '', $normalize = TRUE)
13 {
14         // Not available for: user@password, IDN, Fragment(=ignored)
15         $array = array();
16         preg_match_all(
17                 // Refer RFC3986
18                 '#(\b[a-z][a-z0-9.+-]{1,8})://' .       // 1: Scheme
19                 '(' .
20                         // 2: Host
21                         '\[[0-9a-f:.]+\]' . '|' .                               // IPv6([colon-hex and dot]): RFC2732
22                         '(?:[0-9]{1-3}\.){3}[0-9]{1-3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
23                         '[^\s<>"\'\[\]:/\#?]+' .                                // FQDN: foo.example.org
24                 ')' .
25                 '(?::([a-z0-9]{2,}))?' .                        // 3: Port
26                 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' .      // 4: Directory path or path-info
27                 '([^\s<>"\'\[\]\#]+)?' .                        // 5: File and query string
28                                                                                         // #: Fragment(ignored)
29                 '#i',
30                  $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
31         //var_dump(recursive_map('htmlspecialchars', $array));
32
33         // Shrink $array
34         $parts = array(1 => 'scheme', 2 => 'host', 3 => 'port',
35                 4 => 'path', 5 => 'file');
36         $default = array('');
37         foreach(array_keys($array) as $uri) {
38                 unset($array[$uri][0]); // Matched string itself
39                 array_rename_keys($array[$uri], $parts, TRUE, $default);
40                 $offset = $array[$uri]['scheme'][1]; // Scheme's offset
41
42                 foreach(array_keys($array[$uri]) as $part) {
43                         // Remove offsets for each part
44                         $array[$uri][$part] = & $array[$uri][$part][0];
45                 }
46                 if ($normalize) {
47                         $array[$uri]['scheme'] = scheme_normalize($array[$uri]['scheme']);
48                         $array[$uri]['host']   = strtolower($array[$uri]['host']);
49                         $array[$uri]['port']   = port_normalize($array[$uri]['scheme'], $array[$uri]['port'], FALSE);
50                         $array[$uri]['path']   = path_normalize($array[$uri]['path']);
51                 }
52                 $array[$uri]['offset'] = $offset;
53                 $array[$uri]['area']   = 0;
54         }
55
56         return $array;
57 }
58
59 // Preprocess: rawurldecode() and adding space(s) to detect/count some URIs _if possible_
60 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
61 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
62 // [OK] http://victim.example.org/http://nasty.example.org
63 function spam_uri_pickup_preprocess($string = '')
64 {
65         if (is_string($string)) {
66                 return preg_replace(
67                         array(
68                                 '#(?:https?|ftp):/#',
69                                 '#\b[a-z][a-z0-9.+-]{1,8}://#i',
70                                 '#[a-z][a-z0-9.+-]{1,8}://#i'
71                         ),
72                         ' $0',
73                         rawurldecode($string)
74                         );
75         } else {
76                 return '';
77         }
78 }
79
80 // TODO: Area selection (Check BBCode only, check anchor only, check ...)
81 // Main function of spam-uri pickup
82 function spam_uri_pickup($string = '')
83 {
84         $string = spam_uri_pickup_preprocess($string);
85
86         $array  = uri_pickup($string);
87
88         // Area elevation for '(especially external)link' intension
89         if (! empty($array)) {
90                 // Anchor tags by preg_match_all()
91                 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
92                 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a> 
93                 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
94                 // [NG] <a href=  >Good site!</a> <a href= "#" >test</a>
95                 $areas = array();
96                 preg_match_all('#<a\b[^>]*href[^>]*>.*?</a\b[^>]*(>)#i',
97                          $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
98                 //var_dump(recursive_map('htmlspecialchars', $areas));
99                 foreach(array_keys($areas) as $area) {
100                         $areas[$area] =  array(
101                                 $areas[$area][0][1], // Area start (<a href>)
102                                 $areas[$area][1][1], // Area end   (</a>)
103                         );
104                 }
105                 area_measure($areas, $array);
106
107                 // phpBB's "BBCode" by preg_match_all()
108                 // [url]http://nasty.example.com/[/url]
109                 // [link]http://nasty.example.com/[/link]
110                 // [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
111                 // [link http://nasty.example.com/]buy something[/link]
112                 // ?? [url=][/url]
113                 $areas = array();
114                 preg_match_all('#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i',
115                          $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
116                 //var_dump(recursive_map('htmlspecialchars', $areas));
117                 foreach(array_keys($areas) as $area) {
118                         $areas[$area] = array(
119                                 $areas[$area][0][1], // Area start ([url])
120                                 $areas[$area][2][1], // Area end   ([/url])
121                         );
122                 }
123                 area_measure($areas, $array);
124
125                 // Various Wiki syntax
126                 // [text_or_uri>text_or_uri]
127                 // [text_or_uri:text_or_uri]
128                 // [text_or_uri|text_or_uri]
129                 // [text_or_uri->text_or_uri]
130                 // [text_or_uri text_or_uri] // MediaWiki
131                 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
132
133                 // Remove 'offset's for area_measure()
134                 //foreach(array_keys($array) as $key)
135                 //      unset($array[$key]['offset']);
136         }
137
138         return $array;
139 }
140
141 // $array['something'] => $array['wanted']
142 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
143 {
144         if (! is_array($array) || ! is_array($keys))
145                 return FALSE;
146
147         // Nondestructive test
148         if (! $force)
149                 foreach(array_keys($keys) as $from)
150                         if (! isset($array[$from]))
151                                 return FALSE;
152
153         foreach($keys as $from => $to) {
154                 if ($from === $to) continue;
155                 if (! $force || isset($array[$from])) {
156                         $array[$to] = & $array[$from];
157                         unset($array[$from]);
158                 } else  {
159                         $array[$to] = $default;
160                 }
161         }
162
163         return TRUE;
164 }
165
166 // If in doubt, it's a little doubtful
167 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
168 {
169         if (! is_array($areas) || ! is_array($array)) return;
170
171         $areas_keys = array_keys($areas);
172         foreach(array_keys($array) as $u_index) {
173                 $offset = isset($array[$u_index][$o_key]) ?
174                         intval($array[$u_index][$o_key]) : 0;
175                 foreach($areas_keys as $a_index) {
176                         if (isset($array[$u_index][$a_key])) {
177                                 $offset_s = intval($areas[$a_index][0]);
178                                 $offset_e = intval($areas[$a_index][1]);
179                                 // [Area => inside <= Area]
180                                 if ($offset_s < $offset && $offset < $offset_e) {
181                                         $array[$u_index][$a_key] += $belief;
182                                 }
183                         }
184                 }
185         }
186 }
187
188
189 // ---------------------
190 // Part Two
191
192 // Scheme normalization (Before port normalization)
193 // snntp://example.org =>  nntps://example.org
194 // NOTE: These alias are needed only for anti URI spamming now. See port_normalize().
195 function scheme_normalize($scheme = '')
196 {
197         $scheme = strtolower($scheme);
198         switch ($scheme) {
199                 case 'pop':   $scheme = 'pop3';  break;
200                 case 'news':  $scheme = 'nntp';  break;
201                 case 'imap4': $scheme = 'imap';  break;
202                 case 'snntp': $scheme = 'nntps'; break;
203                 case 'snews': $scheme = 'nntps'; break;
204                 case 'spop3': $scheme = 'pop3s'; break;
205                 case 'pops':  $scheme = 'pop3s'; break;
206         }
207         return $scheme;
208 }
209
210 // Port normalization
211 // http://example.org:80/ => http://example.org/
212 // http://example.org:8080/ => http://example.org:8080/
213 // https://example.org:443/ => https://example.org/
214 // NOTE: These alias are needed only for anti URI spamming now
215 function port_normalize($scheme, $port = '', $scheme_normalize = TRUE)
216 {
217         if ($port === '') return $port;
218
219         // Refer: http://www.iana.org/assignments/port-numbers
220         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
221         switch ($port) {
222                 case    21:     if ($scheme == 'ftp')     $port = ''; break;
223                 case    22:     if ($scheme == 'ssh')     $port = ''; break;
224                 case    23:     if ($scheme == 'telnet')  $port = ''; break;
225                 case    25:     if ($scheme == 'smtp')    $port = ''; break;
226                 case    69:     if ($scheme == 'tftp')    $port = ''; break;
227                 case    70:     if ($scheme == 'gopher')  $port = ''; break;
228                 case    79:     if ($scheme == 'finger')  $port = ''; break;
229                 case    80:     if ($scheme == 'http')    $port = ''; break;
230                 case   110:     if ($scheme == 'pop3')    $port = ''; break;
231                 case   115:     if ($scheme == 'sftp')    $port = ''; break;
232                 case   119:     if ($scheme == 'nntp')    $port = ''; break;
233                 case   143:     if ($scheme == 'imap')    $port = ''; break;
234                 case   194:     if ($scheme == 'irc')     $port = ''; break;
235                 case   210:     if ($scheme == 'wais')    $port = ''; break;
236                 case   443:     if ($scheme == 'https')   $port = ''; break;
237                 case   563:     if ($scheme == 'nntps')   $port = ''; break;
238                 case   873:     if ($scheme == 'rsync')   $port = ''; break;
239                 case   990:     if ($scheme == 'ftps')    $port = ''; break;
240                 case   992:     if ($scheme == 'telnets') $port = ''; break;
241                 case   993:     if ($scheme == 'imaps')   $port = ''; break;
242                 case   994:     if ($scheme == 'ircs')    $port = ''; break;
243                 case   995:     if ($scheme == 'pop3s')   $port = ''; break;
244                 case  3306:     if ($scheme == 'mysql')   $port = ''; break;
245         }
246
247         return $port;
248 }
249
250 // Path normalization
251 // '' => '/'
252 // #hoge => /#hoge
253 // /path/a/b/./c////./d => /path/a/b/c/d
254 // /path/../../a/../back => /back
255 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
256 {
257         if (! is_string($path) || $path == '') {
258                 $path = $addroot ? $divider : '';
259         } else {
260                 $path = trim($path);
261                 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
262                 $array = explode($divider, $path);
263
264                 // Remove paddings
265                 foreach(array_keys($array) as $key) {
266                         if ($array[$key] == '' || $array[$key] == '.')
267                                  unset($array[$key]);
268                 }
269                 // Back-track
270                 $tmp = array();
271                 foreach($array as $value) {
272                         if ($value == '..') {
273                                 array_pop($tmp);
274                         } else {
275                                 array_push($tmp, $value);
276                         }
277                 }
278                 $array = & $tmp;
279
280                 $path = $addroot ? $divider : '';
281                 if (! empty($array)) $path .= implode($divider, $array) . $last;
282         }
283
284         return $path;
285 }
286
287 // Input: '/a/b'
288 // Output: array('' => array('a' => array('b' => NULL)))
289 function array_tree($string, $delimiter = '/', $reverse = FALSE)
290 {
291         // Create a branch
292         $tree = NULL;
293         $tmps = explode($delimiter, $string);
294         if (! $reverse) $tmps = array_reverse($tmps);
295         foreach ($tmps as $tmp) {
296                 $tree = array($tmp => $tree);
297         }
298         return $tree;
299 }
300
301
302 // ---------------------
303 // Part One : Checker
304
305 // Simple/fast spam check
306 function is_uri_spam($target = '')
307 {
308         $is_spam = FALSE;
309         $urinum = 0;
310
311         if (is_array($target)) {
312                 foreach($target as $str) {
313                         // Recurse
314                         list($is_spam, $_urinum) = is_uri_spam($str);
315                         $urinum += $_urinum;
316                         if ($is_spam) break;
317                 }
318         } else {
319                 $pickups = spam_uri_pickup($target);
320                 $urinum += count($pickups);
321                 if (! empty($pickups)) {
322                         // Some users want to post some URLs, but ...
323                         if ($urinum > 8) {
324                                 $is_spam = TRUE;        // Too many!
325                         } else {
326                                 foreach($pickups as $pickup) {
327                                         if ($pickup['area'] < 0) {
328                                                 $is_spam = TRUE;
329                                                 break;
330                                         }
331                                 }
332                         }
333                 }
334         }
335
336         return array($is_spam, $urinum);
337 }
338
339 // ---------------------
340
341 // Check User-Agent (not testing yet)
342 function is_invalid_useragent($ua_name = '' /*, $ua_vars = ''*/ )
343 {
344         return $ua_name === '';
345 }
346
347 // ---------------------
348
349 // TODO: Multi-metrics (uri, host, user-agent, ...)
350 // TODO: Mail to administrator with more measurement data?
351 // Simple/fast spam filter ($target: 'a string' or an array())
352 function pkwk_spamfilter($action, $page, $target = array('title' => ''))
353 {
354         $is_spam = FALSE;
355
356         //$is_spam =  is_invalid_useragent('NOTYET');
357         if ($is_spam) {
358                 $action .= ' (Invalid User-Agent)';
359         } else {
360                 list($is_spam) = is_uri_spam($target);
361         }
362
363         if ($is_spam) {
364                 // Mail to administrator(s)
365                 global $notify, $notify_subject;
366                 if ($notify) {
367                         $footer['ACTION'] = $action;
368                         $footer['PAGE']   = '[blocked] ' . $page;
369                         $footer['URI']    = get_script_uri() . '?' . rawurlencode($page);
370                         $footer['USER_AGENT']  = TRUE;
371                         $footer['REMOTE_ADDR'] = TRUE;
372                         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $footer);
373                         unset($footer);
374                 }
375         }
376
377         if ($is_spam) spam_exit();
378 }
379
380 // ---------------------
381
382 // Common bahavior for blocking
383 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
384 function spam_exit()
385 {
386         die("\n");
387 }
388
389 ?>