Iptables.php
[Pman.Admin] / Iptables.php
1 <?php
2 /***
3  * how this might work..
4  *
5  * a) login - if it's a new IP not seen that day
6  * --> touch /tmp/run_pman_admin_iptables
7  *
8  * cron every minute... ?? << could do some kind of IPC?!?
9  *
10  * if file exists -> run this code.
11  *
12  * This code finds all the IP's used in the last 24 hours.
13  * and opens the firew all for them.
14  *
15  *
16  *
17  *
18  *
19  
20  
21  *
22  *
23  */
24
25 require_once 'Pman.php';
26
27 class Pman_Admin_Iptables extends Pman {
28     
29     static $cli_desc = "Read ip addresses that have been used to log in, and add them to the iptables list..";
30     
31    
32     
33     function getAuth()
34     {
35         // add locking here..
36         
37         if (!$this->bootLoader->cli) {
38             die("cli only");
39         }
40     }
41     
42     function monitorFile()
43     {
44         $ev = DB_DataObject::Factory('Events');
45         $db = $ev->database();
46         
47         return '/tmp/run_pman_admin_iptables-'.$db;
48     }
49     
50     function get($opt = '')
51     {
52         
53         // monitor file
54         
55         $mf = $this->monitorFile();
56         
57         $fe = file_exists($mf);
58         if (empty($opt)) {
59             if (!$fe) {
60                 exit;
61             }
62         }
63         if ($fe) {
64             unlink($mf);
65         }
66         
67         // find IP's that have been used to log in.
68         // dump them to the iptables file.
69         // if it's different - apply it...
70         //DB_DataObject::debugLevel(1);
71         // need to get a list of users who have Admin.Iptables rights..
72         /*$gr = DB_DataObject::factory('group_rights');
73         $grps = $gr->groupsWithRights('Admin.Iptables', 'S');
74         
75         $gr = DB_DataObject::factory('groups');
76         $gr->get('name', 'Administrators');
77         $grps[] = $gr->id;
78         
79         $gm = DB_DataObject::factory('group_members');
80         $gm->whereAddIn('group_id', $grps, 'int');
81         $gm->selectAdd();
82         $gm->selectAdd('distinct(user_id) as user_id');
83         $peps = $gm->fetchAll('user_id');
84         
85         
86         */
87         //DB_DataObject::debugLevel(1);
88         
89         $p = DB_DataObject::Factory('Person');
90         $p->autoJoin();
91         $p->whereAdd("join_company_id_id.comptype = 'OWNER'");
92         $p->selectAdd();
93         $p->selectAdd("{$p->tableName()}.id as  id");
94         
95         $peps = $p->fetchAll('id');
96         
97         
98         switch( $p->getDatabaseConnection()->phptype) {
99             case 'mysql':
100                 $interval = "INTERVAL 1 DAY";
101                 break;
102             case 'pgsql':
103                 $interval = " INTERVAL '1 DAY'";
104                 break;
105             default:
106                 die("database NOT SUPPORTED?!");
107         }
108         
109         $e = DB_DataObject::factory('Events');
110         $e->action = 'LOGIN';
111         $e->selectAdd();
112         $e->selectAdd(" 
113             distinct(ipaddr) as ipaddr,
114             max(event_when) + $interval as expires
115                      
116         ");
117         $e->person_table = DB_DataObject::factory('person')->tableName();
118         $e->whereAddIn('person_id', $peps, 'int');
119         $e->groupBy('ipaddr');
120         $e->whereAdd("event_when > NOW() - $interval");
121                 
122        
123         $ips = $e->fetchAll('ipaddr','expires');
124
125         require_once 'System.php';
126         //inet addr:202.67.151.28  Bcast:202.67.151.255  Mask:255.255.255.0
127         $ifconfig = System::which('ifconfig');
128         
129         if (!$ifconfig) {
130             $this->jerr("ifconfig could not be found.");
131         }
132
133         $if = $this->exec($ifconfig);
134         
135          
136         foreach(explode("\n", $if) as $l) {
137             //var_dump($l);
138             if (!preg_match('/inet addr/', $l)) {
139                 continue;
140             }
141             $match = array();
142             preg_match('/\s*inet addr:([0-9.]+)\s+/', $l, $match);
143             $ips[$match[1]] = ''; // no expiry...
144             
145         }
146         $this->ips = $ips;
147         $cache = ini_get('session.save-path') . '/pman_admin_iptables.cache';
148         
149         $this->updateTables();
150         
151          
152         exit;
153
154     }
155     
156     function readTable($chain)
157     {
158         
159          require_once 'System.php';
160         
161         $iptables = System::which('iptables');
162         
163          if (!$iptables) {
164             $this->jerr("iptables could not be found.");
165         }
166         // this should have been set up already..
167         // in the base firewall code.
168        
169         $res = $this->exec("{$iptables} -L {$chain} -v -n --line-numbers");   
170         
171         
172         
173         $lastrulenum = 1;
174        
175         $remove = array();
176         $cur = array();
177         $head = false;
178         
179         foreach(explode("\n", $res) as $i => $line) {
180             if ($i == 1) {
181                 $head = preg_split('/\s+/', $line);
182                 $head[10] = 'comments';
183             }
184             if ($i < 2) {
185                 continue;
186             }
187             
188             $ar = preg_split('/\s+/', $line);
189             if (count($ar) < 3) {
190                 continue;
191             }
192             $ar[10] = implode(' ',array_slice($ar, 10));
193             $row = array();
194             foreach($head as $k=>$v) {
195                 $row[$v] = $ar[$k];
196             }
197            // print_r($row);
198             //var_dump($row['target']);
199              
200             
201             // got input rules now..
202             if (!empty($row['comments'])) {
203                 
204                 $row['comments'] = preg_replace('#^/\*#', '', trim($row['comments']) );
205                 $row['comments'] = preg_replace('#\*/$#', '', $row['comments'] );
206                 foreach((array)json_decode($row['comments']) as $k=>$v) {
207                     $row[$k] = $v;
208                 }
209             }
210             $rows[] = $row;
211                           
212              
213         }
214         if (empty($head)) {
215             return false;
216         }
217         
218         return  $rows;
219     
220     }
221     
222     
223     
224     function updateTables()
225     {
226        
227         require_once 'System.php';
228         
229         $iptables = System::which('iptables');
230         
231          if (!$iptables) {
232             $this->jerr("iptables could not be found.");
233         }
234         // this should have been set up already..
235         // in the base firewall code.
236        
237        
238         $rows = $this->readChain('INPUT');
239         $gotpg = false;
240         foreach($rows as $r) {
241             if ($r['target'] == 'postgres') {
242                 $gotpg = true;
243             }
244         }
245         if (!$gotpg) {
246             $this->exec("{$iptables} -A INPUT -p udp -m udp --dport 5432 -j postgres");
247             $this->exec("{$iptables} -A INPUT -p tcp -m udp --dport 5432 -j postgres");
248         }
249         
250         
251         $rows = $this->readChain('postgres');
252         if ($rows === false) {
253             $this->createBase();
254         }
255         
256         
257         // /sbin/iptables -L postgres -v -n --line-numbers
258         
259         $res = $this->exec("{$iptables} -L postgres -v -n --line-numbers");   
260        
261        
262         $lastrulenum = 1;
263        
264         $remove = array();
265         $cur = array();
266         $head = false;
267         
268         foreach(explode("\n", $res) as $i => $line) {
269             if ($i == 1) {
270                 $head = preg_split('/\s+/', $line);
271                 $head[10] = 'comments';
272             }
273             if ($i < 2) {
274                 continue;
275             }
276             
277             $ar = preg_split('/\s+/', $line);
278             if (count($ar) < 3) {
279                 continue;
280             }
281             $ar[10] = implode(' ',array_slice($ar, 10));
282             $row = array();
283             foreach($head as $k=>$v) {
284                 $row[$v] = $ar[$k];
285             }
286            // print_r($row);
287             //var_dump($row['target']);
288             if ($row['target'] != 'ACCEPT') {
289                 continue;
290             }
291             
292             // got input rules now..
293             if (!empty($row['comments'])) {
294                 
295                 $row['comments'] = preg_replace('#^/\*#', '', trim($row['comments']) );
296                 $row['comments'] = preg_replace('#\*/$#', '', $row['comments'] );
297                 foreach((array)json_decode($row['comments']) as $k=>$v) {
298                     $row[$k] = $v;
299                 }
300             }
301             
302             if (!empty($row['expires'])) {
303                 if (strtotime($row['expires']) < time()) {
304                     $remove[ $row['source'] ] = $row;
305                 }
306             }
307             
308             $cur[ $row['source'] ] = $row;
309             
310             $lastrulenum = $row['num'];
311             
312         }
313         if (empty($head)) {
314             // then there was no chain.
315             $this->createBase();
316         }
317         
318         //print_r($cur);
319         //--comment
320         
321           
322          
323         foreach($this->ips as $ip=>$expires) {
324             $comment = strlen($expires) ?
325                     ('-m comment --comment ' . escapeshellarg(json_encode(array('expires'=>$expires))) ) :
326                     '';
327
328             
329             $old = isset($cur[$ip]) ? $cur[$ip] : false;
330             if ($old) {
331                 if (empty($old['expires'])) {
332                     continue;
333                 }
334                 if (strtotime($expires) <= strtotime($old['expires'])) {
335                     // expires time is the same..
336                     //?? make sure it's not flagged for removal..
337                     
338                     continue;
339                 }
340             }
341             
342             if ($old) {
343                 $this->exec("{$iptables} -R postgres {$old['num']} -s {$ip}/32 -j ACCEPT   $comment");
344                 
345                 if (isset($remove[$ip])) {
346                     unset($remove[$ip]);
347                 }
348                 continue;
349             }
350             
351             $this->exec("{$iptables} -I postgres {$lastrulenum} -s {$ip}/32 -j ACCEPT  $comment");
352                     
353             
354                                    
355         }
356         
357         // remove rules that need deleting..
358         foreach($remove as $ip => $r) {
359             $this->exec("{$iptables} -d postgres {$r['num']} ");
360             
361         }
362         
363         $this->exec("{$iptables} -L postgres -v -n --line-numbers");   
364        
365   
366         
367     }
368     
369     
370     function createBase()
371     {
372         
373         $iptables = System::which('iptables');
374         if (!$iptables) {
375             $this->jerr("iptables could not be found.");
376         }
377         
378         
379         
380         //$this->exec("{$iptables} -F postgres"); // flush old
381         $this->exec("{$iptables} -X postgres"); // flush old
382         
383         $this->exec("{$iptables} -N postgres");  // create new..
384         
385         $this->exec($iptables. ' -A postgres -m limit --limit 2/min -j LOG '.
386                         '--log-prefix "IPTables-Dropped: " --log-level 4');
387         $this->exec("$iptables -A postgres -j DROP");  
388
389         
390         
391         
392         
393     }
394     
395     function exec($cmd)
396     {
397         echo "$cmd\n";
398         $ret =  `$cmd`;
399         echo $ret."\n";
400         return $ret;
401     }
402     
403 }