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         
96         $e = DB_DataObject::factory('Events');
97         $e->action = 'LOGIN';
98         $e->selectAdd();
99         $e->selectAdd('distinct(ipaddr) as ipaddr');
100         $e->person_table = DB_DataObject::factory('person')->tableName();
101         $e->whereAddIn('person_id', $peps, 'int');
102         switch( $e->getDatabaseConnection()->phptype) {
103             case 'mysql':
104                 $e->whereAdd("event_when > NOW() - INTERVAL 1 DAY");
105                 break;
106             case 'pgsql':
107                 $e->whereAdd("event_when > NOW() - INTERVAL '1 DAY'");
108                 break;   
109         }
110         $ips = $e->fetchAll('ipaddr');
111
112         //inet addr:202.67.151.28  Bcast:202.67.151.255  Mask:255.255.255.0
113
114
115         // local ips..
116         $if = `/sbin/ifconfig`;
117         
118         foreach(explode("\n", $if) as $l) {
119             //var_dump($l);
120             if (!preg_match('/inet addr/', $l)) {
121                 continue;
122             }
123             $match = array();
124             preg_match('/\s*inet addr:([0-9.]+)\s+/', $l, $match);
125              $ips[] = $match[1];
126             
127         }
128         $this->ips = $ips;
129         $cache = ini_get('session.save-path') . '/pman_admin_iptables.cache';
130         
131         
132         
133         
134         $fn = tempnam(ini_get('session.save-path'), 'firewallconf');
135         file_put_contents($fn, $this->output());
136         echo file_get_contents($fn);
137         //`/sbin/iptables-restore < $fn`;
138
139         exit;
140
141     }
142     function output()
143     {
144        
145         require_once 'System.php';
146         
147         $iptables = System::which('iptables');
148         // this should have been set up already..
149         // in the base firewall code.
150        
151         
152         // -A INPUT -p udp -m udp --dport 5432 -j postgres
153         // -A INPUT -p tcp -m tcp --dport 5432 -j postgres
154         
155         
156         // /sbin/iptables -L postgres -v -n --line-numbers
157         
158         $res = $this->exec("{$iptables} -L postgres -v -n --line-numbers");   
159         var _dump($res);
160         foreach(explode("\n", $res) as $line) {
161             $ar = preg_split('/\s+/', $line);
162             print_r($ar);
163         }
164         exit;
165         //--comment
166         
167           
168         
169         
170        
171         if (!$iptables) {
172             $this->jerr("iptables could not be found.");
173         }
174         $this->exec("{$iptables} -F postgres"); // flush old
175         $this->exec("{$iptables} -N postgres");  // create new..
176         
177         foreach($this->ips as $ip=>$expires) {
178             $old = isset($cur[$ip]) ? $cur[$ip] : false;
179             if ($old) {
180                 if (strtotime($expires) <= strtotime($old['expires'])) {
181                     // expires time is the same..
182                     //?? make sure it's not flagged for removal..
183                     
184                     continue;
185                 }
186             }
187             
188             if ($old) {
189                 $this->exec("{$iptables} -R postgres {$old['num']} -s {$ip}/32 -j ACCEPT --comment ".
190                     escapeshellarg(json_encode(array('expires'=>$expires)))) ;
191                 
192                 if (isset($remove[$ip])) {
193                     unset($remove[$ip]);
194                 }
195                 continue;
196             }
197             
198             $this->exec("{$iptables} -I postgres {$lastrulenum} -s {$ip}/32 -j ACCEPT --comment ".
199                     escapeshellarg(json_encode(array('expires'=>$expires))));
200             
201                                    
202         }
203         
204         // remove rules that need deleting..
205         foreach($remove as $ip => $r) {
206             $this->exec("{$iptables} -d postgres {$r['num']} ");
207             
208         }
209         
210         
211         $this->exec($iptables. ' -A postgres -m limit --limit 2/min -j LOG '.
212                         '--log-prefix "IPTables-Dropped: " --log-level 4');
213         $this->exec("$iptables -A postgres -j DROP");  
214
215         
216     }
217     
218     
219     function createBase()
220     {
221         
222         $iptables = System::which('iptables');
223         if (!$iptables) {
224             $this->jerr("iptables could not be found.");
225         }
226         
227         
228         
229         $this->exec("{$iptables} -F postgres"); // flush old
230         $this->exec("{$iptables} -N postgres");  // create new..
231         
232         $this->exec($iptables. ' -A postgres -m limit --limit 2/min -j LOG '.
233                         '--log-prefix "IPTables-Dropped: " --log-level 4');
234         $this->exec("$iptables -A postgres -j DROP");  
235
236         
237         
238         
239         
240     }
241     
242     function exec($cmd)
243     {
244         echo "$cmd\n";
245         $ret =  `$cmd`;
246         echo $ret."\n";
247         return $ret;
248     }
249     
250 }