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         if (!$this->bootLoader->cli) {
36             die("cli only");
37         }
38     }
39     
40     function monitorFile()
41     {
42         $ev = DB_DataObject::Factory('Events');
43         $db = $ev->database();
44         
45         return '/tmp/run_pman_admin_iptables-'.$db;
46     }
47     
48     function get($opt = '')
49     {
50         
51         // monitor file
52         
53         $mf = $this->monitorFile();
54         
55         $fe = file_exists($mf);
56         if (empty($opt)) {
57             if (!$fe) {
58                 exit;
59             }
60         }
61         if ($fe) {
62             unlink($mf);
63         }
64         
65         // find IP's that have been used to log in.
66         // dump them to the iptables file.
67         // if it's different - apply it...
68         //DB_DataObject::debugLevel(1);
69         // need to get a list of users who have Admin.Iptables rights..
70         /*$gr = DB_DataObject::factory('group_rights');
71         $grps = $gr->groupsWithRights('Admin.Iptables', 'S');
72         
73         $gr = DB_DataObject::factory('groups');
74         $gr->get('name', 'Administrators');
75         $grps[] = $gr->id;
76         
77         $gm = DB_DataObject::factory('group_members');
78         $gm->whereAddIn('group_id', $grps, 'int');
79         $gm->selectAdd();
80         $gm->selectAdd('distinct(user_id) as user_id');
81         $peps = $gm->fetchAll('user_id');
82         
83         
84         */
85         
86         
87         $p = DB_DataObject::Factory('Person');
88         $p->autoJoin();
89         $p->whereAdd("join_company_id_id.comptype = 'OWNER'");
90         $p->selectAdd();
91         $p->selectAdd("{$p->tableName()}.id as  id");
92         
93         $peps = $p->fetchAll('id');
94         
95         switch( $e->getDatabaseConnection()->phptype) {
96             case 'mysql':
97                 $interval = "INTERVAL 1 DAY";
98                 break;
99             case 'pgsql':
100                 $interval = " INTERVAL '1 DAY'";
101                 break;
102             default:
103                 die("database NOT SUPPORTED?!");
104         }
105         
106         $e = DB_DataObject::factory('Events');
107         $e->action = 'LOGIN';
108         $e->selectAdd();
109         $e->selectAdd(" 
110             distinct(ipaddr) as ipaddr
111             max(event_when) + $interval as expires
112                      
113         ");
114         $e->person_table = DB_DataObject::factory('person')->tableName();
115         $e->whereAddIn('person_id', $peps, 'int');
116         $e->groupBy('ipaddr');
117         $e->whereAdd("event_when > NOW() - $interval");
118                 
119        
120         $ips = $e->fetchAll('ipaddr','expires');
121
122         //inet addr:202.67.151.28  Bcast:202.67.151.255  Mask:255.255.255.0
123         $ifconfig = System::which('ifconfig');
124         
125         if (!$ifconfig) {
126             $this->jerr("ifconfig could not be found.");
127         }
128
129         $if = $this->exec($ifconfig);
130         
131          
132         foreach(explode("\n", $if) as $l) {
133             //var_dump($l);
134             if (!preg_match('/inet addr/', $l)) {
135                 continue;
136             }
137             $match = array();
138             preg_match('/\s*inet addr:([0-9.]+)\s+/', $l, $match);
139             $ips[$match[1]] = ''; // no expiry...
140             
141         }
142         $this->ips = $ips;
143         $cache = ini_get('session.save-path') . '/pman_admin_iptables.cache';
144         
145         $this->updateTables();
146         
147          
148         exit;
149
150     }
151     function updateTables()
152     {
153        
154         require_once 'System.php';
155         
156         $iptables = System::which('iptables');
157         
158          if (!$iptables) {
159             $this->jerr("iptables could not be found.");
160         }
161         // this should have been set up already..
162         // in the base firewall code.
163        
164         
165         // -A INPUT -p udp -m udp --dport 5432 -j postgres
166         // -A INPUT -p tcp -m tcp --dport 5432 -j postgres
167         
168         
169         // /sbin/iptables -L postgres -v -n --line-numbers
170         
171         $res = $this->exec("{$iptables} -L postgres -v -n --line-numbers");   
172        
173        
174         $lastrulenum = 1;
175        
176         $remove = array();
177        
178         foreach(explode("\n", $res) as $i => $line) {
179             if ($i == 1) {
180                 $head = preg_split('/\s+/', $line);
181                 $head[10] = 'comments';
182             }
183             if ($i < 2) {
184                 continue;
185             }
186             
187             $ar = preg_split('/\s+/', $line);
188             if (count($ar) < 3) {
189                 continue;
190             }
191             $ar[10] = implode(' ',array_slice($ar, 10));
192             $row = array();
193             foreach($head as $k=>$v) {
194                 $row[$v] = $ar[$k];
195             }
196             print_r($row);
197             
198             if ($row['target'] != 'INPUT') {
199                 continue;
200             }
201             // got input rules now..
202             if (!empty($row['comment'])) {
203                 foreach((array)json_decode($row['comment']) as $k=>$v) {
204                     $row[$k] = $v;
205                 }
206             }
207             if (!empty($row['expires'])) {
208                 if (strtotime($row['expires']) < time()) {
209                     $remove[ $row['source'] ] = $row;
210                 }
211             }
212             $old[ $row['source'] ] = $row;
213             
214             $lastrulenum = $row['num'];
215             
216         }
217         exit;
218         //--comment
219         
220           
221          
222         foreach($this->ips as $ip=>$expires) {
223             $old = isset($cur[$ip]) ? $cur[$ip] : false;
224             if ($old) {
225                 if (strtotime($expires) <= strtotime($old['expires'])) {
226                     // expires time is the same..
227                     //?? make sure it's not flagged for removal..
228                     
229                     continue;
230                 }
231             }
232             
233             if ($old) {
234                 $this->exec("{$iptables} -R postgres {$old['num']} -s {$ip}/32 -j ACCEPT --comment ".
235                     escapeshellarg(json_encode(array('expires'=>$expires)))) ;
236                 
237                 if (isset($remove[$ip])) {
238                     unset($remove[$ip]);
239                 }
240                 continue;
241             }
242             
243             $this->exec("{$iptables} -I postgres {$lastrulenum} -s {$ip}/32 -j ACCEPT --comment ".
244                     escapeshellarg(json_encode(array('expires'=>$expires))));
245             
246                                    
247         }
248         
249         // remove rules that need deleting..
250         foreach($remove as $ip => $r) {
251             $this->exec("{$iptables} -d postgres {$r['num']} ");
252             
253         }
254         
255         
256   
257         
258     }
259     
260     
261     function createBase()
262     {
263         
264         $iptables = System::which('iptables');
265         if (!$iptables) {
266             $this->jerr("iptables could not be found.");
267         }
268         
269         
270         
271         $this->exec("{$iptables} -F postgres"); // flush old
272         $this->exec("{$iptables} -N postgres");  // create new..
273         
274         $this->exec($iptables. ' -A postgres -m limit --limit 2/min -j LOG '.
275                         '--log-prefix "IPTables-Dropped: " --log-level 4');
276         $this->exec("$iptables -A postgres -j DROP");  
277
278         
279         
280         
281         
282     }
283     
284     function exec($cmd)
285     {
286         echo "$cmd\n";
287         $ret =  `$cmd`;
288         echo $ret."\n";
289         return $ret;
290     }
291     
292 }