CPClient.php 31.7 KB
Newer Older
Ad Schellevis's avatar
Ad Schellevis committed
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/**
 *    Copyright (C) 2015 Deciso B.V.
 *
 *    All rights reserved.
 *
 *    Redistribution and use in source and binary forms, with or without
 *    modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 *    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 *    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 *    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *    POSSIBILITY OF SUCH DAMAGE.
 *
 */
29 30
namespace OPNsense\CaptivePortal;

31 32
use \Phalcon\Logger\Adapter\Syslog;
use \Phalcon\DI\FactoryDefault;
33
use \OPNsense\Core;
34 35

/**
36
 * Class CPClient main class for captive portal backend functionality
37
 * // TODO: CARP interfaces are probably not handled correctly
38
 * @package CaptivePortal
39
 */
40 41
class CPClient
{
42 43 44 45
    /**
     * config handle
     * @var Core_Config
     */
46
    private $config = null;
47 48 49

    /**
     * ipfw rule object
50
     * @var \CaptivePortal\Rules
51 52 53 54 55
     */
    private $rules = null;

    /**
     * link to shell object
Ad Schellevis's avatar
Ad Schellevis committed
56
     * @var  Core\Shell
57 58 59
     */
    private $shell = null;

60
    /**
61
     * Constructor
62
     */
63 64 65 66 67 68 69 70
    public function __construct()
    {
        // Request handle to configuration
        $this->config = Core\Config::getInstance();
        // generate new ruleset
        $this->rules = new Rules();
        // keep a link to the shell object
        $this->shell = new Core\Shell();
71 72 73
    }

    /**
74
     * reset traffic counters
75
     *
76
     * @param string|null $rulenum
77
     */
78 79 80 81 82 83
    public function zeroCounters($rulenum = null)
    {
        if ($rulenum != null and is_numeric($rulenum)) {
            $this->shell->exec("/sbin/ipfw zero " . $rulenum);
        } elseif ($rulenum == null) {
            $this->shell->exec("/sbin/ipfw zero ");
84 85 86 87
        }

    }

Ad Schellevis's avatar
Ad Schellevis committed
88
    /**
89
     * Reconfigure zones ( generate and load ruleset )
Ad Schellevis's avatar
Ad Schellevis committed
90
     */
91
    public function reconfigure()
Ad Schellevis's avatar
Ad Schellevis committed
92
    {
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        if ($this->isEnabled()) {
            $ruleset_filename = FactoryDefault::getDefault()->get('config')->globals->temp_path."/ipfw.rules";
            $this->rules->generate($ruleset_filename);

            // load ruleset
            $this->shell->exec("/sbin/ipfw -f ".$ruleset_filename);

            // update tables
            $this->update();

            // after reinit all accounting rules are vanished, reapply them for active sessions
            $this->loadAccounting();
        } else {
            // captiveportal is disabled, flush all rules to be sure
            $this->shell->exec("/sbin/ipfw -f flush");
Ad Schellevis's avatar
Ad Schellevis committed
108 109 110
        }
    }

111 112 113 114 115 116 117
    /**
     * check if captiveportal is enabled (traverse zones, if none active return false )
     * @return bool
     */
    public function isEnabled()
    {
        $enabled_zones = 0 ;
118 119 120 121 122 123
        $conf = $this->config->object();
        if (isset($conf->captiveportal)) {
            foreach ($conf->captiveportal->children() as $cpzonename => $zone) {
                if (isset($zone->enable)) {
                    $enabled_zones++;
                }
124 125 126 127 128 129 130 131 132 133
            }
        }

        if ($enabled_zones > 0) {
            return true;
        } else {
            return false ;
        }
    }

134 135
    /**
     * update zone(s) with new configuration data
136
     * @param string|null $zone
137
     */
138 139 140 141
    public function update($zone = null)
    {
        $this->refreshAllowedIPs($zone);
        $this->refreshAllowedMACs($zone);
142 143 144 145
    }

    /**
     * refresh allowed ip's for defined zone ( null for all zones )
146
     * @param string|null $cpzone
147
     */
148 149
    public function refreshAllowedIPs($cpzone = null)
    {
150
        $handled_addresses = array();
151
        foreach ($this->config->object()->captiveportal->children() as $cpzonename => $zone) {
152
            // search requested zone (id)
153
            if ($cpzonename == $cpzone || $zone->zoneid == $cpzone || $cpzone == null) {
154 155 156 157
                $db = new DB($cpzonename);
                $db_iplist = $db->listFixedIPs();

                // calculate table numbers for this zone
158
                $ipfw_tables = $this->rules->getAuthIPTables($zone->zoneid);
159 160 161 162 163 164 165 166

                foreach ($zone->children() as $tagname => $tagcontent) {
                    $ip = $tagcontent->ip->__toString();
                    if ($tagname == 'allowedip') {
                        $handled_addresses[$ip] = array();
                        $handled_addresses[$ip]["bw_up"] = $tagcontent->bw_up->__toString() ;
                        $handled_addresses[$ip]["bw_down"] = $tagcontent->bw_down->__toString() ;

167
                        if (!array_key_exists($ip, $db_iplist)) {
168
                            // only insert new values
169 170
                            $pipeno_in = $this->newIPFWpipeno() ;
                            $pipeno_out = $this->newIPFWpipeno() ;
171 172 173

                            $exec_commands = array(
                                # insert new ip address
174 175 176 177
                                "/sbin/ipfw table ". $ipfw_tables["in"]  ." add " .
                                $ip . "/" . $tagcontent->sn->__toString() . " " . $pipeno_in,
                                "/sbin/ipfw table ". $ipfw_tables["out"] ." add " .
                                $ip . "/" . $tagcontent->sn->__toString() . " " . $pipeno_out,
178 179 180
                            );

                            // execute all ipfw actions
181
                            $this->shell->exec($exec_commands, false, false);
182
                            // update administration
183
                            $db->upsertFixedIP($ip, $pipeno_in, $pipeno_out);
184 185
                            // save bandwidth data
                            $handled_addresses[$ip]["pipeno_in"] = $pipeno_in ;
186 187
                            $handled_addresses[$ip]["pipeno_out"] = $pipeno_out ;
                        } else {
188 189 190 191 192 193 194 195 196 197
                            //
                            $handled_addresses[$ip]["pipeno_in"] = $db_iplist[$ip]->pipeno_in ;
                            $handled_addresses[$ip]["pipeno_out"] = $db_iplist[$ip]->pipeno_out ;
                        }
                    }

                }


                // Cleanup deleted addresses
198 199
                foreach ($db_iplist as $ip => $record) {
                    if (!array_key_exists($ip, $handled_addresses)) {
200 201
                        $exec_commands = array(
                            # insert new ip address
202 203 204 205
                            "/sbin/ipfw table ". $ipfw_tables["in"]  .
                            " del " . $ip . "/" . $tagcontent->sn->__toString() ,
                            "/sbin/ipfw table ". $ipfw_tables["out"] .
                            " del " . $ip . "/" . $tagcontent->sn->__toString() ,
206 207 208
                        );

                        // execute all ipfw actions
209
                        $this->shell->exec($exec_commands, false, false);
210 211 212 213 214 215
                        // TODO : cleanup $record->pipeno_in, $record->pipeno_out ;
                        $db->dropFixedIP($ip);
                    }
                }

                // reset bandwidth,
216 217 218 219
                foreach ($handled_addresses as $mac => $record) {
                    if (array_key_exists("pipeno_in", $record)) {
                        $this->resetBandwidth($record["pipeno_in"], $record["bw_down"]);
                        $this->resetBandwidth($record["pipeno_out"], $record["bw_up"]);
220 221 222 223 224 225 226 227 228
                    }
                }

                unset($db);
            }
        }

    }

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    /**
     * Request new pipeno
     * @return int
     */
    private function newIPFWpipeno()
    {
        // TODO: implement global pipe number assigment
        return 999;
    }

    /**
     * reset bandwidth, if the current bandwidth is unchanged, do nothing
     * @param  int $pipeno system pipeno
     * @param  int $bw  bandwidth in Kbit/s
     * @return status
     */
    private function resetBandwidth($pipeno, $bw)
    {
        //TODO : setup bandwidth for sessions ( check changed )
        //#pipe 2000 config bw 2000Kbit/s
        return false;
    }

252 253 254 255
    /**
     * To be able to grant access to physical pc's, we need to do some administration.
     * Our captive portal database keeps a list of every used address and last know mac address
     *
256
     * @param string|null $cpzone zone name or number
257
     */
258 259
    public function refreshAllowedMACs($cpzone = null)
    {
260 261 262 263 264 265 266

        // read ARP table
        $arp= new ARP();
        $arp_maclist = $arp->getMACs();

        // keep a list of handled addresses, so we can cleanup the rest and keep track of needed bandwidth restrictions
        $handled_mac_addresses = array();
267 268
        foreach ($this->config->object()->captiveportal->children() as $cpzonename => $zone) {
            if ($cpzonename == $cpzone || $zone->zoneid == $cpzone || $cpzone == null) {
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
                // open administrative database for this zone
                $db = new DB($cpzonename);
                $db_maclist = $db->listPassthruMacs();
                $ipfw_tables = $this->rules->getAuthMACTables($zone->zoneid);

                foreach ($zone->children() as $tagname => $tagcontent) {
                    $mac = trim(strtolower($tagcontent->mac));
                    if ($tagname == 'passthrumac') {
                        // only accept valid macaddresses
                        if (preg_match('/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/', $mac)) {
                            if ($tagcontent->action == "pass") {
                                $handled_mac_addresses[$mac] = array("action"=>"skipped" );
                                $handled_mac_addresses[$mac]["bw_up"] = $tagcontent->bw_up ;
                                $handled_mac_addresses[$mac]["bw_down"] = $tagcontent->bw_down ;

                                // only handle addresses we know of
                                if (array_key_exists($mac, $arp_maclist)) {
                                    // if the address is already in our database, check if it has changed
287
                                    if (array_key_exists($mac, $db_maclist)) {
288 289 290 291
                                        // save pipe numbers for bandwidth restriction
                                        $handled_mac_addresses[$mac]["pipeno_in"] = $db_maclist[$mac]->pipeno_in ;
                                        $handled_mac_addresses[$mac]["pipeno_out"] = $db_maclist[$mac]->pipeno_out ;

292
                                        if ($db_maclist[$mac]->ip !=  $arp_maclist[$mac]['ip']) {
293 294 295 296
                                            // handle changed ip,
                                            $handled_mac_addresses[$mac]["action"] = "changed ip";
                                            $exec_commands = array(
                                                # delete old ip address
297 298 299 300
                                                "/sbin/ipfw table ". $ipfw_tables["in"] .
                                                " delete ". $db_maclist[$mac]->ip,
                                                "/sbin/ipfw table ". $ipfw_tables["out"] .
                                                " delete ". $db_maclist[$mac]->ip,
301
                                                # insert new ip address
302 303 304 305
                                                "/sbin/ipfw table ". $ipfw_tables["in"]  .
                                                " add " . $arp_maclist[$mac]['ip']. " " . $db_maclist[$mac]->pipeno_in,
                                                "/sbin/ipfw table ". $ipfw_tables["out"] .
                                                " add " . $arp_maclist[$mac]['ip']. " " . $db_maclist[$mac]->pipeno_out,
306 307 308
                                            );

                                            // execute all ipfw actions
309
                                            $this->shell->exec($exec_commands, false, false);
310
                                            // update administration
311 312 313 314 315 316
                                            $db->upsertPassthruMAC(
                                                $tagcontent->mac,
                                                $arp_maclist[$mac]['ip'],
                                                $db_maclist[$mac]->pipeno_in,
                                                $db_maclist[$mac]->pipeno_out
                                            ); // new ip according to arp table
317
                                        }
318
                                    } else {
319 320
                                        // new host, not seen it yet
                                        $handled_mac_addresses[$mac]["action"] = "new";
321 322
                                        $pipeno_in = $this->newIPFWpipeno() ;
                                        $pipeno_out = $this->newIPFWpipeno() ;
323 324 325 326

                                        // execute all ipfw actions
                                        $exec_commands = array(
                                            # insert new ip address
327 328 329 330
                                            "/sbin/ipfw table ". $ipfw_tables["in"]  .
                                            " add " . $arp_maclist[$mac]['ip']. " " . $pipeno_in,
                                            "/sbin/ipfw table ". $ipfw_tables["out"] .
                                            " add " . $arp_maclist[$mac]['ip']. " " . $pipeno_out,
331
                                        );
332
                                        $this->shell->exec($exec_commands, false, false);
333

334 335 336 337 338 339
                                        $db->upsertPassthruMAC(
                                            $tagcontent->mac,
                                            $arp_maclist[$mac]['ip'],
                                            $pipeno_in,
                                            $pipeno_out
                                        );
340 341 342 343 344 345 346 347 348 349 350 351 352
                                        // save pipe numbers for bandwidth restriction
                                        $handled_mac_addresses[$mac]["pipeno_in"] = $pipeno_in ;
                                        $handled_mac_addresses[$mac]["pipeno_out"] =  $pipeno_out ;
                                    }
                                }
                            }
                        }
                    }
                }

                //
                // cleanup old addresses
                //
353 354
                foreach ($db_maclist as $mac => $record) {
                    if (!array_key_exists($mac, $handled_mac_addresses)) {
355 356
                        # delete old ip address, execute all actions
                        $exec_commands = array(
357 358 359 360
                            "/sbin/ipfw table ". $ipfw_tables["in"] .
                            " delete ". $db_maclist[$mac]->ip,
                            "/sbin/ipfw table ". $ipfw_tables["out"] .
                            " delete ". $db_maclist[$mac]->ip,
361
                        );
362
                        $this->shell->exec($exec_commands, false, false);
363 364 365 366 367 368
                        // TODO : cleanup $record->pipeno_in, $record->pipeno_out ;
                        $db->dropPassthruMAC($mac);
                    }
                }

                // reset bandwidth
369 370 371 372
                foreach ($handled_mac_addresses as $mac => $record) {
                    if (array_key_exists("pipeno_in", $record)) {
                        $this->resetBandwidth($record["pipeno_in"], $record["bw_down"]);
                        $this->resetBandwidth($record["pipeno_out"], $record["bw_up"]);
373 374 375 376 377 378 379 380 381 382
                    }
                }

                unset($db);

            }
        }

    }

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
    /**
     * load accounting rules into ruleset, used for reinitialisation of the ruleset.
     * triggers addAccounting() for all active clients in all zones
     */
    private function loadAccounting()
    {
        foreach ($this->config->object()->captiveportal->children() as $cpzonename => $zone) {
            $db = new DB($cpzonename);
            foreach ($db->listClients(array()) as $client) {
                $this->addAccounting($zone->zoneid, $client->ip) ;
            }
            unset($db);
        }
    }

    /**
     * add accounting rules for ip
     * @param int $zoneid zone
     * @param string $ip  ip address
     */
    public function addAccounting($zoneid, $ip)
    {
        // TODO: check processing speed, this might need some improvement
        // check if our ip is already in the list and collect first free rule number to place it there if necessary
        $shell_output=array();
        $this->shell->exec("/sbin/ipfw show", false, false, $shell_output);
        $prev_id = 0;
        $new_id = null;
        foreach ($shell_output as $line) {
            // only trigger on counter rules and last item in the list
            if (strpos($line, " count ") !== false || strpos($line, "65535 ") !== false) {
                if (strpos($line, " ".$ip." ") !== false) {
                    // already in table... exit
                    return;
                }

                $this_line_id = (int)(explode(" ", $line)[0]) ;
                if ($this_line_id  > 30000 and ($this_line_id -1) > $prev_id and $new_id == null) {
                    // new id found
                    if ($this_line_id == 65535) {
                        $new_id = $prev_id+1;
                    } else {
                        $new_id = $this_line_id-1;
                    }
                }

                $prev_id =  $this_line_id;
            }
        }

        if ($new_id != null) {
            $exec_commands = array(
                "/sbin/ipfw add " . $new_id . " set " . $zoneid . " count ip from " . $ip . " to any ",
                "/sbin/ipfw add " . $new_id . " set " . $zoneid . " count ip from  any to " . $ip,
            );

            // execute all ipfw actions
            $this->shell->exec($exec_commands, false, false);
        }
    }

444
    /**
445
     * unlock host for captiveportal use
446 447 448 449
     * @param string $cpzonename
     * @param string $clientip
     * @param string $clientmac
     * @param string $username
450 451 452 453 454 455 456 457
     * @param string|null $password
     * @param string|null $bw_up
     * @param string|null $bw_down
     * @param string|null $radiusctx
     * @param int|null $session_timeout
     * @param int|null $idle_timeout
     * @param int|null $session_terminate_time
     * @param int|null $interim_interval
458
     * @return bool|string
459
     */
460 461 462 463 464 465 466 467 468 469 470 471 472 473
    public function portalAllow(
        $cpzonename,
        $clientip,
        $clientmac,
        $username,
        $password = null,
        $bw_up = null,
        $bw_down = null,
        $radiusctx = null,
        $session_timeout = null,
        $idle_timeout = null,
        $session_terminate_time = null,
        $interim_interval = null
    ) {
474 475 476 477 478 479 480
        // defines
        $exec_commands = array() ;
        $db = new DB($cpzonename);
        $arp= new ARP();

        // find zoneid for this named zone
        $zoneid = -1;
481 482 483 484
        foreach ($this->config->object()->captiveportal->children() as $zone => $zoneobj) {
            if ($zone == $cpzonename) {
                $zoneid = $zoneobj->zoneid;
            }
485 486
        }

487 488 489
        if ($zoneid == -1) {
            return false; // not a valid zone, bailout
        }
490 491 492 493


        // grap needed data to generate our rules
        $ipfw_tables = $this->rules->getAuthUsersTables($zoneid);
494 495
        $cp_table = $db->listClients(array("mac"=>$clientmac, "ip"=>$clientip), "or");
        if (sizeof($cp_table) > 0 && ($cp_table[0]->ip == $clientip && $cp_table[0]->mac == $clientmac)) {
496
            // nothing (important) changed here... move on
497
            return $cp_table[0]->sessionid;
498
        } elseif (sizeof($cp_table) > 0) {
499
            // something changed...
500 501
            // prevent additional sessions to popup,
            // one MAC should have only one active session, remove the rest (if any)
502 503
            $cnt = 0;
            $remove_sessions = array();
504 505 506 507 508 509
            foreach ($cp_table as $record) {
                if ($cnt >0) {
                    $remove_sessions[] = $record->sessionid;
                } else {
                    $current_session = $record;
                }
510 511 512 513 514 515 516
                $cnt++;
                // prepare removal for all ip addresses belonging to this host
                $exec_commands[] = "/sbin/ipfw table ". $ipfw_tables["in"] ." delete ". $record->ip;
                $exec_commands[] = "/sbin/ipfw table ". $ipfw_tables["out"] ." delete ". $record->ip;
                // TODO: if for some strange reason there is more than one session, we are failing to drop the pipes
                $exec_commands[] = "/usr/sbin/arp -d ".trim($record->ip); // drop static arp entry (prevent MAC change)
            }
517 518
            if (sizeof($remove_sessions)) {
                $db->removeSession($remove_sessions);
519 520 521 522 523 524
            }

            // collect pipe numbers for  dummynet
            $pipeno_in = $current_session->pipeno_in;
            $pipeno_out = $current_session->pipeno_out;

525
            $db->updateSession($current_session->sessionid, array("ip"=>$clientip, "mac"=>$clientmac));
526 527 528

            // preserve session for response
            $sessionid = $current_session->sessionid;
529
        } else {
530
            // new session, allocate new dummynet pipes and generate a unique id
531 532
            $pipeno_in = $this->newIPFWpipeno();
            $pipeno_out = $this->newIPFWpipeno();
533 534

            // construct session data
535
            $session_data=array();
536 537 538 539 540
            $session_data["ip"]=$clientip;
            $session_data["mac"]=$clientmac;
            $session_data["pipeno_in"] = $pipeno_in;
            $session_data["pipeno_out"] = $pipeno_out;
            $session_data["username"]=\SQLite3::escapeString($username);
Ad Schellevis's avatar
Ad Schellevis committed
541
            $session_data["bpassword"] = base64_encode($password);
542 543 544 545
            $session_data["session_timeout"] = $session_timeout;
            $session_data["idle_timeout"] = $idle_timeout;
            $session_data["session_terminate_time"] = $session_terminate_time;
            $session_data["interim_interval"] = $interim_interval;
546 547 548 549
            $session_data["radiusctx"] = $radiusctx;
            $session_data["allow_time"] = time(); // allow time is actual starting time of this session
            $sessionid = uniqid() ;

550
            $db->insertSession($sessionid, $session_data);
551 552 553 554 555 556

        }

        // add commands for access tables, and execute all collected
        $exec_commands[] = "/sbin/ipfw table ". $ipfw_tables["in"] ." add ". $clientip . " ".$pipeno_in;
        $exec_commands[] = "/sbin/ipfw table ". $ipfw_tables["out"] ." add ". $clientip . " ".$pipeno_out;
557
        $this->shell->exec($exec_commands, false, false);
558 559

        // lock the user/ip to it's MAC address using arp
560
        $arp->setStatic($clientip, $clientmac);
561 562

        // add accounting rule
563
        $this->addAccounting($zoneid, $clientip);
564

565
        // set bandwidth restrictions
566 567
        $this->resetBandwidth($pipeno_in, $bw_up);
        $this->resetBandwidth($pipeno_in, $bw_down);
568

569
        // log
570
        $this->logportalauth($cpzonename, $username, $clientmac, $clientip, $status = "LOGIN");
571

572 573
        // cleanup
        unset($db);
574 575

        return $sessionid;
576 577 578
    }

    /**
579 580 581 582 583 584 585
     * send message to syslog
     * @param string $cpzonename
     * @param string $user
     * @param string $mac
     * @param string $ip
     * @param string $status
     * @param string $message
586
     */
587 588 589 590 591 592 593 594 595 596
    private function logportalauth($cpzonename, $user, $mac, $ip, $status, $message = "")
    {
        $message = trim($message);
        $message = "Zone : {$cpzonename} {$status}: {$user}, {$mac}, {$ip}, {$message}";

        $logger = new Syslog("logportalauth", array(
            'option' => LOG_PID,
            'facility' => LOG_LOCAL4
        ));
        $logger->info($message);
597 598 599 600
    }

    /**
     * flush zone (null flushes all zones)
601
     * @param string|null $zone zone name or id
602
     */
603 604 605
    public function flush($zone = null)
    {
        if ($zone == null) {
606
            $shell = new Core\Shell();
607
            $shell->exec("/sbin/ipfw -f table all flush");
608
        } else {
609
            // find zoneid for this named zone
610
            if (preg_match("/^[0-9]{1,2}$/", trim($zone))) {
611
                $zoneid = $zone;
612
            } else {
613 614
                $zoneid = -1;
                foreach ($this->config->object()->captiveportal->children() as $zonenm => $zoneobj) {
615 616 617
                    if ($zonenm == $zone) {
                        $zoneid = $zoneobj->zoneid;
                    }
618 619 620
                }
            }

621
            if ($zoneid != -1) {
622 623 624 625 626 627 628 629 630
                $exec_commands= array(
                    "/sbin/ipfw -f table ".$this->rules->getAuthUsersTables($zoneid)["in"]." flush",
                    "/sbin/ipfw -f table ".$this->rules->getAuthUsersTables($zoneid)["out"]." flush",
                    "/sbin/ipfw -f table ".$this->rules->getAuthIPTables($zoneid)["in"]." flush",
                    "/sbin/ipfw -f table ".$this->rules->getAuthIPTables($zoneid)["out"]." flush",
                    "/sbin/ipfw -f table ".$this->rules->getAuthMACTables($zoneid)["in"]." flush",
                    "/sbin/ipfw -f table ".$this->rules->getAuthMACTables($zoneid)["out"]." flush",
                    "/sbin/ipfw delete set ".$zoneid,
                );
631
                $this->shell->exec($exec_commands, false, false);
632 633 634 635
            }
        }
    }

636 637
    /**
     * cleanup portal sessions
638
     * @param $cpzone|null zone name
639
     */
640 641 642 643 644
    public function portalCleanupSessions($cpzone = null)
    {
        $acc_list = $this->listAccounting();
        foreach ($this->config->object()->captiveportal->children() as $cpzonename => $zoneobj) {
            if ($cpzone == null || $cpzone == $cpzonename) {
645
                $db = new DB($cpzonename);
646

647
                $clients = $db->listClients(array(), null, null);
648

649 650 651 652 653
                foreach ($clients as $client) {
                    $idle_time = 0;
                    if (array_key_exists($client->ip, $acc_list)) {
                        $idle_time = $acc_list[$client->ip];
                    }
654

655
                    // if session timeout is reached, disconnect
656
                    if (is_numeric($client->session_timeout) && $client->session_timeout > 0) {
657
                        if (((time() - $client->allow_time) ) > $client->session_timeout) {
658
                            $this->disconnect($cpzonename, $client->sessionid);
659 660 661 662 663 664 665
                            $this->logportalauth(
                                $cpzonename,
                                $client->username,
                                $client->mac,
                                $client->ip,
                                $status = "SESSION TIMEOUT"
                            );
666 667 668 669 670 671 672 673
                            continue;
                        }
                    }

                    // disconnect session if idle timeout is reached
                    if (is_numeric($client->idle_timeout) && $client->idle_timeout > 0  && $idle_time > 0) {
                        if ($idle_time > $client->idle_timeout) {
                            $this->disconnect($cpzonename, $client->sessionid);
674 675 676 677 678 679 680
                            $this->logportalauth(
                                $cpzonename,
                                $client->username,
                                $client->mac,
                                $client->ip,
                                $status = "IDLE TIMEOUT"
                            );
681 682
                            continue;
                        }
683 684
                    }

685
                    // disconnect on session terminate time
686 687 688
                    if (is_numeric($client->session_terminate_time) &&
                        $client->session_terminate_time > 0 &&
                        $client->session_terminate_time < time()) {
689
                        $this->disconnect($cpzonename, $client->sessionid);
690 691 692 693 694 695 696
                        $this->logportalauth(
                            $cpzonename,
                            $client->username,
                            $client->mac,
                            $client->ip,
                            $status = "TERMINATE TIME REACHED"
                        );
697 698 699 700
                        continue;
                    }
                }

701 702
                unset($db);
            }
703 704 705 706 707
        }

        unset ($acc_list);

    }
708

709 710
    /**
     * list (ipfw) accounting information
711
     * @param string|null $ipaddr  ip address
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
     * @return array (key = hosts ip)
     */
    public function listAccounting($ipaddr = null)
    {
        $filter_cmd = "";
        $result = array();
        $shell_output = array();
        if ($ipaddr != null) {
            $filter_cmd =" | /usr/bin/grep ' " . $ipaddr ." '" ;
        }

        if ($this->shell->exec("/sbin/ipfw -aT list ".$filter_cmd, false, false, $shell_output) == 0) {
            foreach ($shell_output as $line) {
                if (strpos($line, ' count ip from') !== false) {
                    $parts = preg_split('/\s+/', $line);
                    if (count($parts) > 8 && $parts[7] != 'any' and strlen($parts[7]) > 5) {
                        $result[$parts[7]] = array(
                            "rulenum" => $parts[0],
                            "last_accessed" => (int)$parts[3],
                            "idle_time" => time() - (int)$parts[3],
                            "out_packets" => (int)$parts[1],
                            "in_packets" => (int)$parts[2]
                        );
                    }
                }
            }
        }

        return $result;

    }

    /**
     * disconnect a session or a list of sessions depending on the parameter
     * @param string $cpzonename zone name or id
747
     * @param string $sessionid session id
748 749 750 751 752 753 754 755 756 757 758
     */
    public function disconnect($cpzonename, $sessionid)
    {
        if (is_array($sessionid)) {
            foreach ($sessionid as $sessid) {
                $this->disconnectSession($cpzonename, $sessid);
            }
        } else {
            $this->disconnectSession($cpzonename, $sessionid);
        }
    }
759

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
    /**
     * @param string $cpzonename zone name
     * @param string $sessionid session id
     * @return boolean false for invalid request
     */
    private function disconnectSession($cpzonename, $sessionid)
    {
        $zoneid = -1;
        foreach ($this->config->object()->captiveportal->children() as $zone => $zoneobj) {
            if ($zone == $cpzonename) {
                $zoneid = $zoneobj->zoneid;
            }
        }

        if ($zoneid == -1) {
            // not a valid zone
            return false;
        }

        $db = new DB($cpzonename);
        $db_clients = $db->listClients(array("sessionid"=>$sessionid));

        $ipfw_tables = $this->rules->getAuthUsersTables($zoneid);
        if (sizeof($db_clients) > 0) {
            if ($db_clients[0]->ip != null) {
                // only handle disconnect if we can find a client in our database
                $exec_commands[] = "/sbin/ipfw table " . $ipfw_tables["in"] . " delete " . $db_clients[0]->ip;
                $exec_commands[] = "/sbin/ipfw table " . $ipfw_tables["out"] . " delete " . $db_clients[0]->ip;
                $this->shell->exec($exec_commands, false, false);
                // TODO: cleanup dummynet pipes $db_clients[0]->pipeno_in/out
                // TODO: log removal
                // ( was : captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "DISCONNECT");)
            }
            $db->removeSession($sessionid);
        }
        return true;
    }
797
}