captiveportal.inc 51 KB
Newer Older
Ad Schellevis's avatar
Ad Schellevis committed
1
<?php
2

Ad Schellevis's avatar
Ad Schellevis committed
3
/*
4
    Copyright (C) 2004-2011 Scott Ullrich <sullrich@gmail.com>
5
    Copyright (C) 2009-2012 Ermal Luçi <eri@pfsense.org>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
    Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>.
    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.

    This version of captiveportal.inc has been modified by Rob Parker
    <rob.parker@keycom.co.uk> to include changes for per-user bandwidth management
    via returned RADIUS attributes. This page has been modified to delete any
    added rules which may have been created by other per-user code (index.php, etc).
    These changes are (c) 2004 Keycom PLC.
Ad Schellevis's avatar
Ad Schellevis committed
35 36 37 38
*/

/* include all configuration functions */
require_once("radius.inc");
39 40
require_once("captiveportal.radius_accounting.inc");
require_once("captiveportal.radius_authentication.inc");
Ad Schellevis's avatar
Ad Schellevis committed
41
require_once("voucher.inc");
42

43 44 45 46 47 48 49 50 51 52 53 54 55
function get_include_contents($filename) {
	if (is_file($filename)) {
		ob_start();
		include $filename;
		$contents = ob_get_contents();
		ob_end_clean();
		return $contents;
	}
	return false;
}



56 57 58 59
//
// TODO : restructure code / gui, for now we try to maintain gui compatibility by not breaking the old callbacks
//
function captiveportal_passthrumac_configure_entry($macent) {
60
    $cpc = new OPNsense\CaptivePortal\CPClient();
61 62 63 64 65 66
    $cpc->update();

    return "" ;
}

function captiveportal_passthrumac_delete_entry($macent) {
67
    $cpc = new OPNsense\CaptivePortal\CPClient();
68 69 70 71 72 73 74 75 76 77
    $cpc->update();

    return "" ;
}

function captiveportal_passthrumac_configure($lock = false) {
    return captiveportal_passthrumac_delete_entry(null) ;
}

function captiveportal_allowedip_configure_entry($ipent, $ishostname = false) {
78
    $cpc = new OPNsense\CaptivePortal\CPClient();
79 80 81 82 83 84 85 86 87 88 89 90 91
    $cpc->update();

    return "" ;
}

function captiveportal_allowedip_configure() {
    return captiveportal_allowedip_configure_entry(null);
}

/* remove a single client by sessionid */
function captiveportal_disconnect_client($sessionid, $term_cause = 1, $logoutReason = "LOGOUT") {
    global $cpzone;

92
    $cpc = new OPNsense\CaptivePortal\CPClient();
93 94 95 96 97 98 99 100 101
    $cpc->disconnect($cpzone,$sessionid);
}

function captiveportal_remove_entries($remove) {
    global $cpzone ;

    if (!is_array($remove) || empty($remove))
        return;

102
    $cpc = new OPNsense\CaptivePortal\CPClient();
103 104 105 106
    $cpc->disconnect($cpzone,$remove);
}

function portal_allow($clientip,$clientmac,$username,$password = null, $attributes = null, $pipeno = null, $radiusctx = null)  {
107
    global $config, $cpzone ,$type,$g;
108

109 110
    $cpc = new OPNsense\CaptivePortal\CPClient();

111
    // Ensure we create an array if we are missing attributes
Ad Schellevis's avatar
Ad Schellevis committed
112
    if (!is_array($attributes)) {
113 114 115 116 117 118
        $attributes = array();
    }

    if ($attributes['voucher']) {
        $remaining_time = $attributes['session_timeout'];
    }
119 120 121 122 123 124 125 126

    // handle
    $dwfaultbw_up = isset($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
    $dwfaultbw_down = isset($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
    $bw_up = isset($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
    $bw_down = isset($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
    $interim_interval = (!empty($attributes['interim_interval'])) ? $attributes['interim_interval'] : 'NULL';

127 128 129 130 131
    $session_timeout = 0 ;
    if ( array_key_exists("session_timeout",$attributes ) ){
        $session_timeout = $attributes['session_timeout'] ;
    }
    elseif ( is_numeric($config['captiveportal'][$cpzone]["timeout"]) ){
132 133
        // calculate to seconds for timeout parameters ( config in minutes )
        $session_timeout = $config['captiveportal'][$cpzone]["timeout"] * 60 ;
134 135 136 137 138 139 140
    }

    $idle_timeout = 0 ;
    if ( array_key_exists("idle_timeout",$attributes ) ){
        $idle_timeout = $attributes['idle_timeout'] ;
    }
    elseif ( is_numeric($config['captiveportal'][$cpzone]["idletimeout"]) ){
141 142
        // calculate to seconds for timeout parameters ( config in minutes )
        $idle_timeout = $config['captiveportal'][$cpzone]["idletimeout"] * 60 ;
143 144 145
    }


146 147 148 149 150 151 152
    $session_terminate_time = 0;
    if ( array_key_exists("session_timeout",$attributes ) ) {
        $session_terminate_time = $attributes['session_terminate_time'] ;
    }



153
    if ($attributes['voucher']) {
Ad Schellevis's avatar
Ad Schellevis committed
154
        $db = new OPNsense\CaptivePortal\DB($cpzone);
155 156 157 158 159
        $clients  = $db->listClients(array("username"=>$username), null, null);
        foreach ($clients as $client) {
            // user is already connected, disconnect old session
            $cpc->disconnect($cpzone, $client->sessionid);

160 161
            // calculate new session end time for this voucher ( session connection time + timeout - now, correct with 1 second to trap exact cleanup hit)
            $session_terminate_time = $client->allow_time + $client->session_timeout - time() - 1;
162 163
        }

164
        if ($session_terminate_time < 0) {
165 166 167 168 169 170 171 172 173
            // no time left for voucher
            return 0;
        }

        unset($db);
    }


    if (is_null($radiusctx)) {
174
        $radiusctx = 'first';
175 176
    }

177

178
    $sessionid = $cpc->portalAllow($cpzone,$clientip,$clientmac,$username,$password,$bw_up,$bw_down,$radiusctx,$session_timeout,$idle_timeout,$session_terminate_time,$interim_interval);
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

    if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers[$radiusctx])) {
        $acct_val = RADIUS_ACCOUNTING_START($pipeno, $username, $sessionid, $radiusservers[$radiusctx], $clientip, $clientmac);
        if ($acct_val == 1)
            captiveportal_logportalauth($username,$clientmac,$clientip,$type,"RADIUS ACCOUNTING FAILED");
    }

    // TODO: error handling
//    /* if the pool is empty, return appropriate message and exit */
//    if (is_null($pipeno)) {
//        portal_reply_page($redirurl, "error", "System reached maximum login capacity");
//        log_error("Zone: {$cpzone} - WARNING!  Captive portal has reached maximum login capacity");
//        unlock($cpdblck);
//        return;
//    }

    /* redirect user to desired destination */
    if (!empty($attributes['url_redirection']))
        $my_redirurl = $attributes['url_redirection'];
    else if (!empty($redirurl))
        $my_redirurl = $redirurl;
    else if (!empty($config['captiveportal'][$cpzone]['redirurl']))
        $my_redirurl = $config['captiveportal'][$cpzone]['redirurl'];

Ad Schellevis's avatar
Ad Schellevis committed
203
    if(isset($config['captiveportal'][$cpzone]['logoutwin_enable']) ) {
204 205 206 207 208 209 210 211 212
        $ourhostname = portal_hostname_from_client_ip($clientip);
        $protocol = (isset($config['captiveportal'][$cpzone]['httpslogin'])) ? 'https://' : 'http://';
        $logouturl = "{$protocol}{$ourhostname}/";

        if (isset($attributes['reply_message']))
            $message = $attributes['reply_message'];
        else
            $message = 0;

213
        include("/var/etc/captiveportal-{$cpzone}-logout.html");
214
    }
215 216 217 218 219 220 221 222 223

    return $sessionid;
}

//
//
//

/* reinit will disconnect all users, be careful! */
224 225
function captiveportal_init_rules($reinit = false)
{
226
        $cpc = new OPNsense\CaptivePortal\CPClient();
227 228 229 230 231 232 233
        $cpc->reconfigure();
        unset($cpc);
}


// Unchanged

Ad Schellevis's avatar
Ad Schellevis committed
234 235

function get_default_captive_portal_html() {
236
    global $config, $g, $cpzone;
Ad Schellevis's avatar
Ad Schellevis committed
237

238
    $htmltext = <<<EOD
239 240 241
<html>
<body>
<form method="post" action="\$PORTAL_ACTION\$">
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    <input name="redirurl" type="hidden" value="\$PORTAL_REDIRURL\$">
    <input name="zone" type="hidden" value="\$PORTAL_ZONE\$">
    <center>
    <table cellpadding="6" cellspacing="0" width="550" height="380" style="border:1px solid #000000">
    <tr height="10" bgcolor="#990000">
        <td style="border-bottom:1px solid #000000">
            <font color='white'>
            <b>
                {$g['product_name']} captive portal
            </b>
            </font>
        </td>
    </tr>
    <tr>
        <td>
            <div id="mainlevel">
            <center>
            <table width="100%" border="0" cellpadding="5" cellspacing="0">
            <tr>
                <td>
                    <center>
                    <div id="mainarea">
                    <center>
                    <table width="100%" border="0" cellpadding="5" cellspacing="5">
                    <tr>
                        <td>
                            <div id="maindivarea">
                            <center>
                                <div id='statusbox'>
                                    <font color='red' face='arial' size='+1'>
                                    <b>
                                        \$PORTAL_MESSAGE\$
                                    </b>
                                    </font>
                                </div>
                                <br />
                                <div id='loginbox'>
                                <table>
                                    <tr><td colspan="2"><center>Welcome to the {$g['product_name']} Captive Portal!</td></tr>
                                    <tr><td>&nbsp;</td></tr>
                                    <tr><td align="right">Username:</td><td><input name="auth_user" type="text" style="border: 1px dashed;"></td></tr>
                                    <tr><td align="right">Password:</td><td><input name="auth_pass" type="password" style="border: 1px dashed;"></td></tr>
                                    <tr><td>&nbsp;</td></tr>
Ad Schellevis's avatar
Ad Schellevis committed
285 286 287

EOD;

288 289 290 291 292 293
    if(isset($config['voucher'][$cpzone]['enable'])) {
    $htmltext .= <<<EOD
                                    <tr>
                                        <td align="right">Enter Voucher Code: </td>
                                        <td><input name="auth_voucher" type="text" style="border:1px dashed;" size="22"></td>
                                    </tr>
Ad Schellevis's avatar
Ad Schellevis committed
294 295

EOD;
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    }

    $htmltext .= <<<EOD
                                    <tr>
                                        <td colspan="2"><center><input name="accept" type="submit" value="Continue"></center></td>
                                    </tr>
                                </table>
                                </div>
                            </center>
                            </div>
                        </td>
                    </tr>
                    </table>
                    </center>
                    </div>
                    </center>
                </td>
            </tr>
            </table>
            </center>
            </div>
        </td>
    </tr>
    </table>
    </center>
Ad Schellevis's avatar
Ad Schellevis committed
321
</form>
322
</body>
Ad Schellevis's avatar
Ad Schellevis committed
323 324 325 326
</html>

EOD;

327
    return $htmltext;
Ad Schellevis's avatar
Ad Schellevis committed
328 329 330 331
}


function captiveportal_configure() {
332
    global $config, $cpzone, $cpzoneid;
Ad Schellevis's avatar
Ad Schellevis committed
333

334 335 336
    /* init ipfw rules */
    captiveportal_init_rules(true);

337 338 339 340 341
    $cpc = new OPNsense\CaptivePortal\CPClient();
    if ($cpc->isEnabled()) {
	$cpc->reconfigure();
    }

342 343 344 345 346 347 348
    if (is_array($config['captiveportal'])) {
        foreach ($config['captiveportal'] as $cpkey => $cp) {
            $cpzone = $cpkey;
            $cpzoneid = $cp['zoneid'];
            captiveportal_configure_zone($cp);
        }
    }
Ad Schellevis's avatar
Ad Schellevis committed
349 350 351
}

function captiveportal_configure_zone($cpcfg) {
352 353 354 355 356 357
    global $config, $g, $cpzone, $cpzoneid;

    $captiveportallck = lock("captiveportal{$cpzone}", LOCK_EX);

    if (isset($cpcfg['enable'])) {

Ad Schellevis's avatar
Ad Schellevis committed
358
        if (file_exists("/var/run/booting")) {
359 360 361
            echo "Starting captive portal({$cpcfg['zone']})... ";

            /* remove old information */
362
            @unlink("/var/db/captiveportal{$cpzone}.db");
363 364 365
        } else
            captiveportal_syslog("Reconfiguring captive portal({$cpcfg['zone']}).");
        /* kill any running minicron */
366
        killbypid("/var/run/cp_prunedb_{$cpzone}.pid");
367 368

        /* initialize minicron interval value */
369
        $croninterval = isset($cpcfg['croninterval']) && !empty($cpcfg['croninterval']) ? $cpcfg['croninterval'] : 60;
370 371 372 373 374 375

        /* double check if the $croninterval is numeric and at least 10 seconds. If not we set it to 60 to avoid problems */
        if ((!is_numeric($croninterval)) || ($croninterval < 10))
            $croninterval = 60;

        /* write portal page */
376
        if (isset($cpcfg['page']['htmltext']) && $cpcfg['page']['htmltext'])
377 378 379 380 381 382
            $htmltext = base64_decode($cpcfg['page']['htmltext']);
        else {
            /* example/template page */
            $htmltext = get_default_captive_portal_html();
        }

383
        $fd = @fopen("/var/etc/captiveportal_{$cpzone}.html", "w");
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
        if ($fd) {
            // Special case handling.  Convert so that we can pass this page
            // through the PHP interpreter later without clobbering the vars.
            $htmltext = str_replace("\$PORTAL_ZONE\$", "#PORTAL_ZONE#", $htmltext);
            $htmltext = str_replace("\$PORTAL_REDIRURL\$", "#PORTAL_REDIRURL#", $htmltext);
            $htmltext = str_replace("\$PORTAL_MESSAGE\$", "#PORTAL_MESSAGE#", $htmltext);
            $htmltext = str_replace("\$CLIENT_MAC\$", "#CLIENT_MAC#", $htmltext);
            $htmltext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $htmltext);
            $htmltext = str_replace("\$ORIGINAL_PORTAL_IP\$", "#ORIGINAL_PORTAL_IP#", $htmltext);
            $htmltext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $htmltext);
            if($cpcfg['preauthurl']) {
                $htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
                $htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
            }
            fwrite($fd, $htmltext);
            fclose($fd);
        }
        unset($htmltext);

        /* write error page */
404
        if (isset($cpcfg['page']['errtext']) && $cpcfg['page']['errtext'])
405 406 407 408 409 410
            $errtext = base64_decode($cpcfg['page']['errtext']);
        else {
            /* example page  */
            $errtext = get_default_captive_portal_html();
        }

411
        $fd = @fopen("/var/etc/captiveportal-{$cpzone}-error.html", "w");
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
        if ($fd) {
            // Special case handling.  Convert so that we can pass this page
            // through the PHP interpreter later without clobbering the vars.
            $errtext = str_replace("\$PORTAL_ZONE\$", "#PORTAL_ZONE#", $errtext);
            $errtext = str_replace("\$PORTAL_REDIRURL\$", "#PORTAL_REDIRURL#", $errtext);
            $errtext = str_replace("\$PORTAL_MESSAGE\$", "#PORTAL_MESSAGE#", $errtext);
            $errtext = str_replace("\$CLIENT_MAC\$", "#CLIENT_MAC#", $errtext);
            $errtext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $errtext);
            $errtext = str_replace("\$ORIGINAL_PORTAL_IP\$", "#ORIGINAL_PORTAL_IP#", $errtext);
            $errtext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $errtext);
            if($cpcfg['preauthurl']) {
                $errtext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $errtext);
                $errtext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $errtext);
            }
            fwrite($fd, $errtext);
            fclose($fd);
        }
        unset($errtext);

        /* write logout page */
432
        if (isset($cpcfg['page']['logouttext']) && $cpcfg['page']['logouttext'])
433 434 435 436
            $logouttext = base64_decode($cpcfg['page']['logouttext']);
        else {
            /* example page */
            $logouttext = <<<EOD
Ad Schellevis's avatar
Ad Schellevis committed
437 438 439 440 441 442 443 444 445 446
<html>
<head><title>Redirecting...</title></head>
<body>
<span style="font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">
<b>Redirecting to <a href="<?=\$my_redirurl;?>"><?=\$my_redirurl;?></a>...</b>
</span>
<script type="text/javascript">
//<![CDATA[
LogoutWin = window.open('', 'Logout', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=256,height=64');
if (LogoutWin) {
447 448 449 450 451 452 453 454 455 456 457 458 459
    LogoutWin.document.write('<html>');
    LogoutWin.document.write('<head><title>Logout</title></head>') ;
    LogoutWin.document.write('<body bgcolor="#435370">');
    LogoutWin.document.write('<div align="center" style="color: #ffffff; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">') ;
    LogoutWin.document.write('<b>Click the button below to disconnect</b><p />');
    LogoutWin.document.write('<form method="POST" action="<?=\$logouturl;?>">');
    LogoutWin.document.write('<input name="logout_id" type="hidden" value="<?=\$sessionid;?>" />');
    LogoutWin.document.write('<input name="zone" type="hidden" value="<?=\$cpzone;?>" />');
    LogoutWin.document.write('<input name="logout" type="submit" value="Logout" />');
    LogoutWin.document.write('</form>');
    LogoutWin.document.write('</div></body>');
    LogoutWin.document.write('</html>');
    LogoutWin.document.close();
Ad Schellevis's avatar
Ad Schellevis committed
460 461 462 463 464 465 466 467 468
}

document.location.href="<?=\$my_redirurl;?>";
//]]>
</script>
</body>
</html>

EOD;
469 470
        }

471
        $fd = @fopen("/var/etc/captiveportal-{$cpzone}-logout.html", "w");
472 473 474 475 476 477 478 479 480 481
        if ($fd) {
            fwrite($fd, $logouttext);
            fclose($fd);
        }
        unset($logouttext);

        /* write elements */
        captiveportal_write_elements();

        /* kill any running mini_httpd */
482 483
        killbypid("/var/run/lighty-{$cpzone}-CaptivePortal.pid");
        killbypid("/var/run/lighty-{$cpzone}-CaptivePortal-SSL.pid");
484 485 486 487 488

        /* start up the webserving daemon */
        captiveportal_init_webgui_zone($cpcfg);

        /* Kill any existing prunecaptiveportal processes */
489
        killbypid("/var/run/cp_prunedb_{$cpzone}.pid");
490 491

        /* start pruning process (interval defaults to 60 seconds) */
492 493
        mwexecf(
		'/usr/local/bin/minicron %s %s %s %s',
494
		 array($croninterval,
495 496
		"/var/run/cp_prunedb_{$cpzone}.pid",
		'/usr/local/etc/rc.prunecaptiveportal',
497
		$cpzone)
498
	);
499 500

        /* generate radius server database */
501
        @unlink("/var/db/captiveportal_radius_{$cpzone}.db");
502 503
        captiveportal_init_radius_servers();

Ad Schellevis's avatar
Ad Schellevis committed
504
        if (file_exists("/var/run/booting")) {
505 506 507 508 509 510
            /* send Accounting-On to server */
            captiveportal_send_server_accounting();
            echo "done\n";
        }

    } else {
511 512 513
        killbypid("/var/run/lighty-{$cpzone}-CaptivePortal.pid");
        killbypid("/var/run/lighty-{$cpzone}-CaptivePortal-SSL.pid");
        killbypid("/var/run/cp_prunedb_{$cpzone}.pid");
514 515 516
        @unlink("/var/etc/captiveportal_{$cpzone}.html");
        @unlink("/var/etc/captiveportal-{$cpzone}-error.html");
        @unlink("/var/etc/captiveportal-{$cpzone}-logout.html");
517 518 519 520

        captiveportal_radius_stop_all();

        /* send Accounting-Off to server */
Ad Schellevis's avatar
Ad Schellevis committed
521
        if (!file_exists("/var/run/booting")) {
522 523 524 525
            captiveportal_send_server_accounting(true);
        }

        /* remove old information */
526 527 528
        @unlink("/var/db/captiveportal{$cpzone}.db");
        @unlink("/var/db/captiveportal_radius_{$cpzone}.db");
        @unlink("/var/db/captiveportal_{$cpzone}.rules");
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
        /* Release allocated pipes for this zone */
        captiveportal_free_dnrules();

        if (empty($config['captiveportal']))
            set_single_sysctl("net.link.ether.ipfw", "0");
        else {
            /* Deactivate ipfw(4) if not needed */
            $cpactive = false;
            if (is_array($config['captiveportal'])) {
                foreach ($config['captiveportal'] as $cpkey => $cp) {
                    if (isset($cp['enable'])) {
                        $cpactive = true;
                        break;
                    }
                }
            }
            if ($cpactive === false)
                set_single_sysctl("net.link.ether.ipfw", "0");

        }
    }

    unlock($captiveportallck);

    return 0;
Ad Schellevis's avatar
Ad Schellevis committed
554 555 556
}

function captiveportal_init_webgui() {
557 558 559 560 561 562 563 564
    global $config, $cpzone;

    if (is_array($config['captiveportal'])) {
        foreach ($config['captiveportal'] as $cpkey => $cp) {
            $cpzone = $cpkey;
            captiveportal_init_webgui_zone($cp);
        }
    }
Ad Schellevis's avatar
Ad Schellevis committed
565 566 567
}

function captiveportal_init_webgui_zonename($zone) {
568 569 570 571 572 573
    global $config, $cpzone;

    if (isset($config['captiveportal'][$zone])) {
        $cpzone = $zone;
        captiveportal_init_webgui_zone($config['captiveportal'][$zone]);
    }
Ad Schellevis's avatar
Ad Schellevis committed
574 575
}

576 577
function captiveportal_init_webgui_zone($cpcfg)
{
578 579
    global $g, $config, $cpzone;

580
    if (!isset($cpcfg['enable'])) {
581
        return;
582
    }
583 584 585 586 587 588 589 590

    if (isset($cpcfg['httpslogin'])) {
        $cert = lookup_cert($cpcfg['certref']);
        $crt = base64_decode($cert['crt']);
        $key = base64_decode($cert['prv']);
        $ca = ca_chain($cert);

        /* generate lighttpd configuration */
591
        if (!empty($cpcfg['listenporthttps'])) {
592
            $listenporthttps = $cpcfg['listenporthttps'];
593
        } else {
594
            $listenporthttps = 8001 + $cpcfg['zoneid'];
595 596 597
        }

        system_generate_lighty_config(
598
	    "/var/etc/lighty-{$cpzone}-CaptivePortal-SSL.conf",
599 600 601 602 603 604 605 606 607 608
            $crt,
            $key,
            $ca,
            "lighty-{$cpzone}-CaptivePortal-SSL.pid",
            $listenporthttps,
            "/usr/local/captiveportal",
            "cert-{$cpzone}-portal.pem",
            "ca-{$cpzone}-portal.pem",
            $cpzone
        );
609 610 611
    }

    /* generate lighttpd configuration */
612
    if (!empty($cpcfg['listenporthttp'])) {
613
        $listenporthttp = $cpcfg['listenporthttp'];
614
    } else {
615
        $listenporthttp = 8000 + $cpcfg['zoneid'];
616 617 618
    }

    system_generate_lighty_config(
619
        "/var/etc/lighty-{$cpzone}-CaptivePortal.conf",
620 621 622 623 624 625 626 627 628 629
        "",
        "",
        "",
        "lighty-{$cpzone}-CaptivePortal.pid",
        $listenporthttp,
        "/usr/local/captiveportal",
        "",
        "",
        $cpzone
    );
630 631 632

    @unlink("{$g['varrun']}/lighty-{$cpzone}-CaptivePortal.pid");
    /* attempt to start lighttpd */
633
    $res = mwexec("/usr/local/sbin/lighttpd -f /var/etc/lighty-{$cpzone}-CaptivePortal.conf");
634 635 636 637

    /* fire up https instance */
    if (isset($cpcfg['httpslogin'])) {
        @unlink("{$g['varrun']}/lighty-{$cpzone}-CaptivePortal-SSL.pid");
638
        $res = mwexec("/usr/local/sbin/lighttpd -f /var/etc/lighty-{$cpzone}-CaptivePortal-SSL.conf");
639
    }
Ad Schellevis's avatar
Ad Schellevis committed
640 641 642
}


643
/*
Ad Schellevis's avatar
Ad Schellevis committed
644 645 646 647 648
 * Remove clients that have been around for longer than the specified amount of time
 * db file structure:
 * timestamp,ipfw_rule_no,clientip,clientmac,username,sessionid,password,session_timeout,idle_timeout,session_terminate_time,interim_interval
 * (password is in Base64 and only saved when reauthentication is enabled)
 */
649 650
function captiveportal_prune_old()
{
651
    global $g, $config, $cpzone, $cpzoneid;
Ad Schellevis's avatar
Ad Schellevis committed
652

653
    if (empty($cpzone)) {
654
        return;
655
    }
Ad Schellevis's avatar
Ad Schellevis committed
656

657
    $cpc = new OPNsense\CaptivePortal\CPClient();
Ad Schellevis's avatar
Ad Schellevis committed
658

659 660 661
    $cpcfg = $config['captiveportal'][$cpzone];
    if ( !isset($cpcfg['radacct_enable'])) {
        // cleanup session (default)
662
        $cpc->portalCleanupSessions($cpzone);
663 664 665
    }else{
        // cleanup sessions if radius accounting is enable
        // TODO: this code needs a rewrite, probably the easiest thing todo is update the zone administration and run
666
        //		 the normal cleanup (portalCleanupSessions) to detach both processes
667 668
        //
        $vcpcfg = $config['voucher'][$cpzone];
669

670 671 672 673 674
        /* check for expired entries */
        $idletimeout = 0;
        $timeout = 0;
        if (!empty($cpcfg['timeout']) && is_numeric($cpcfg['timeout']))
            $timeout = $cpcfg['timeout'] * 60;
675

676 677
        if (!empty($cpcfg['idletimeout']) && is_numeric($cpcfg['idletimeout']))
            $idletimeout = $cpcfg['idletimeout'] * 60;
678

679 680 681 682
        /* Is there any job to do? */
        if (!$timeout && !$idletimeout && !isset($cpcfg['reauthenticate']) &&
            !isset($cpcfg['radiussession_timeout']) && !isset($vcpcfg['enable']))
            return;
683

684
        $radiussrvs = captiveportal_get_radius_servers();
685

686 687
        /* Read database */
        /* NOTE: while this can be simplified in non radius case keep as is for now */
688
        $cpdb = array(); // captiveportal_read_db();
689

690
        $unsetindexes = array();
691

692
        /*
693 694 695
         * Snapshot the time here to use for calculation to speed up the process.
         * If something is missed next run will catch it!
         */
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 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 747 748 749 750 751 752 753 754 755 756 757 758 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 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
        $pruning_time = time();
        $stop_time = $pruning_time;
        foreach ($cpdb as $cpentry) {

            $timedout = false;
            $term_cause = 1;
            if (empty($cpentry[11]))
                $cpentry[11] = 'first';
            $radiusservers = $radiussrvs[$cpentry[11]];

            /* hard timeout? */
            if ($timeout) {
                if (($pruning_time - $cpentry[0]) >= $timeout) {
                    $timedout = true;
                    $term_cause = 5; // Session-Timeout
                }
            }

            /* Session-Terminate-Time */
            if (!$timedout && !empty($cpentry[9])) {
                if ($pruning_time >= $cpentry[9]) {
                    $timedout = true;
                    $term_cause = 5; // Session-Timeout
                }
            }


            /* if vouchers are configured, activate session timeouts */
            if (!$timedout && isset($vcpcfg['enable']) && !empty($cpentry[7])) {
                if ($pruning_time >= ($cpentry[0] + $cpentry[7])) {
                    $timedout = true;
                    $term_cause = 5; // Session-Timeout
                    $voucher_needs_sync = true;
                }
            }

            /* if radius session_timeout is enabled and the session_timeout is not null, then check if the user should be logged out */
            if (!$timedout && isset($cpcfg['radiussession_timeout']) && !empty($cpentry[7])) {
                if ($pruning_time >= ($cpentry[0] + $cpentry[7])) {
                    $timedout = true;
                    $term_cause = 5; // Session-Timeout
                }
            }

            if ($timedout) {
                captiveportal_disconnect($cpentry, $radiusservers,$term_cause,$stop_time);
                captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "TIMEOUT");
                $unsetindexes[] = $cpentry[5];
            }

            /* do periodic RADIUS reauthentication? */
            if (!$timedout && !empty($radiusservers)) {
                if (isset($cpcfg['radacct_enable'])) {
                    if ($cpcfg['reauthenticateacct'] == "stopstart") {
                        /* stop and restart accounting */
                        RADIUS_ACCOUNTING_STOP($cpentry->pipeno_in, // ruleno
                            $cpentry->username, // username
                            $cpentry->sessionid, // sessionid
                            $cpentry->allow_time, // start time
                            $radiusservers,
                            $cpentry->ip, // clientip
                            $cpentry->mac, // clientmac
                            10); // NAS Request

                        // todo, zero counters

                        RADIUS_ACCOUNTING_START($cpentry->pipeno_in, // ruleno
                            $cpentry->username, // username
                            $cpentry->sessionid, // sessionid
                            $radiusservers,
                            $cpentry->ip, // clientip
                            $cpentry->mac); // clientmac
                    } else if ($cpcfg['reauthenticateacct'] == "interimupdate") {
                        $session_time = $pruning_time - $cpentry[0];
                        if (!empty($cpentry[10]) && $cpentry[10] > 60)
                            $interval = $cpentry[10];
                        else
                            $interval = 0;
                        $past_interval_min = ($session_time > $interval);
                        if ($interval != 0)
                            $within_interval = ($session_time % $interval >= 0 && $session_time % $interval <= 59);
                        if ($interval === 0 || ($interval > 0 && $past_interval_min && $within_interval)) {
                            RADIUS_ACCOUNTING_STOP($cpentry->pipeno_in, // ruleno
                                $cpentry->username, // username
                                $cpentry->sessionid, // sessionid
                                $cpentry->allow_time, // start time
                                $radiusservers,
                                $cpentry->ip, // clientip
                                $cpentry->mac, // clientmac
                                10, // NAS Request
                                true); // Interim Updates
                        }
                    }
                }

                /* check this user against RADIUS again */
                if (isset($cpcfg['reauthenticate'])) {
                    $auth_list = RADIUS_AUTHENTICATION($cpentry[4], // username
                        base64_decode($cpentry->bpassword), // password
                        $radiusservers,
                        $cpentry->ip, // clientip
                        $cpentry->mac, // clientmac
                        $cpentry->pipeno_in); // ruleno
                    if ($auth_list['auth_val'] == 3) {
                        $cpc->disconnect($cpzone, $cpentry->sessionid);
                        captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "RADIUS_DISCONNECT", $auth_list['reply_message']);
                        $unsetindexes[] = $cpentry[5];
                    } else if ($auth_list['auth_val'] == 2)
                        //captiveportal_reapply_attributes($cpentry, $auth_list);
                        null;
                }
            }
        }
    }

    unset($cpdb);
Ad Schellevis's avatar
Ad Schellevis committed
812 813 814 815
}

/* send RADIUS acct stop for all current clients */
function captiveportal_radius_stop_all() {
816 817 818 819 820 821 822
    global $config, $cpzone;

    if (!isset($config['captiveportal'][$cpzone]['radacct_enable']))
        return;

    $radiusservers = captiveportal_get_radius_servers();
    if (!empty($radiusservers)) {
Ad Schellevis's avatar
Ad Schellevis committed
823
        $cpdb = new OPNsense\CaptivePortal\DB($cpzone);
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843

        $clients  = $cpdb->listClients(array());

        foreach ($clients as $cpentry) {
            if (empty($cpentry->radiusctx))
                $cpentry->radiusctx = 'first';
            if (!empty($radiusservers[$cpentry->radiusctx])) {
                RADIUS_ACCOUNTING_STOP($cpentry->pipeno_in, // ruleno
                    $cpentry->username, // username
                    $cpentry->sessionid, // sessionid
                    $cpentry->allow_time, // start time
                    $radiusservers[$cpentry->radiusctx],
                    $cpentry->ip, // clientip
                    $cpentry->mac, // clientmac
                    7); // Admin Reboot
            }
        }

        unset($cpdb);
    }
Ad Schellevis's avatar
Ad Schellevis committed
844 845 846 847
}


function captiveportal_passthrumac_findbyname($username) {
848 849 850 851 852 853 854 855 856
    global $config, $cpzone;

    if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
        foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
            if ($macent['username'] == $username)
                return $macent;
        }
    }
    return NULL;
Ad Schellevis's avatar
Ad Schellevis committed
857 858 859 860 861
}



function captiveportal_init_radius_servers() {
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
    global $config, $g, $cpzone;

    /* generate radius server database */
    if ($config['captiveportal'][$cpzone]['radiusip'] && (!isset($config['captiveportal'][$cpzone]['auth_method']) ||
        ($config['captiveportal'][$cpzone]['auth_method'] == "radius"))) {
        $radiusip = $config['captiveportal'][$cpzone]['radiusip'];
        $radiusip2 = ($config['captiveportal'][$cpzone]['radiusip2']) ? $config['captiveportal'][$cpzone]['radiusip2'] : null;
        $radiusip3 = ($config['captiveportal'][$cpzone]['radiusip3']) ? $config['captiveportal'][$cpzone]['radiusip3'] : null;
        $radiusip4 = ($config['captiveportal'][$cpzone]['radiusip4']) ? $config['captiveportal'][$cpzone]['radiusip4'] : null;

        if ($config['captiveportal'][$cpzone]['radiusport'])
            $radiusport = $config['captiveportal'][$cpzone]['radiusport'];
        else
            $radiusport = 1812;
        if ($config['captiveportal'][$cpzone]['radiusacctport'])
            $radiusacctport = $config['captiveportal'][$cpzone]['radiusacctport'];
        else
            $radiusacctport = 1813;
        if ($config['captiveportal'][$cpzone]['radiusport2'])
            $radiusport2 = $config['captiveportal'][$cpzone]['radiusport2'];
        else
            $radiusport2 = 1812;
        if ($config['captiveportal'][$cpzone]['radiusport3'])
            $radiusport3 = $config['captiveportal'][$cpzone]['radiusport3'];
        else
            $radiusport3 = 1812;
        if ($config['captiveportal'][$cpzone]['radiusport4'])
            $radiusport4 = $config['captiveportal'][$cpzone]['radiusport4'];
        else
            $radiusport4 = 1812;

        $radiuskey = $config['captiveportal'][$cpzone]['radiuskey'];
        $radiuskey2 = $config['captiveportal'][$cpzone]['radiuskey2'];
        $radiuskey3 = $config['captiveportal'][$cpzone]['radiuskey3'];
        $radiuskey4 = $config['captiveportal'][$cpzone]['radiuskey4'];

        $cprdsrvlck = lock("captiveportalradius{$cpzone}", LOCK_EX);
899
        $fd = @fopen("/var/db/captiveportal_radius_{$cpzone}.db", "w");
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
        if (!$fd) {
            captiveportal_syslog("Error: cannot open radius DB file in captiveportal_configure().\n");
            unlock($cprdsrvlck);
            return 1;
        }
        if (isset($radiusip))
            fwrite($fd,$radiusip . "," . $radiusport . "," . $radiusacctport . "," . $radiuskey . ",first");
        if (isset($radiusip2))
            fwrite($fd,"\n" . $radiusip2 . "," . $radiusport2 . "," . $radiusacctport . "," . $radiuskey2 . ",first");
        if (isset($radiusip3))
            fwrite($fd,"\n" . $radiusip3 . "," . $radiusport3 . "," . $radiusacctport . "," . $radiuskey3 . ",second");
        if (isset($radiusip4))
            fwrite($fd,"\n" . $radiusip4 . "," . $radiusport4 . "," . $radiusacctport . "," . $radiuskey4 . ",second");


        fclose($fd);
        unlock($cprdsrvlck);
    }
Ad Schellevis's avatar
Ad Schellevis committed
918 919 920 921
}

/* read RADIUS servers into array */
function captiveportal_get_radius_servers() {
922 923 924
    global $g, $cpzone;

    $cprdsrvlck = lock("captiveportalradius{$cpzone}");
925
    if (file_exists("/var/db/captiveportal_radius_{$cpzone}.db")) {
926
        $radiusservers = array();
927
        $cpradiusdb = file("/var/db/captiveportal_radius_{$cpzone}.db",
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
        FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if ($cpradiusdb) {
            foreach($cpradiusdb as $cpradiusentry) {
                $line = trim($cpradiusentry);
                if ($line) {
                    $radsrv = array();
                        list($radsrv['ipaddr'],$radsrv['port'],$radsrv['acctport'],$radsrv['key'], $context) = explode(",",$line);
                }
                if (empty($context)) {
                    if (!is_array($radiusservers['first']))
                        $radiusservers['first'] = array();
                    $radiusservers['first'] = $radsrv;
                } else {
                    if (!is_array($radiusservers[$context]))
                        $radiusservers[$context] = array();
                    $radiusservers[$context][] = $radsrv;
                }
            }
        }
        unlock($cprdsrvlck);
        return $radiusservers;
    }

    unlock($cprdsrvlck);
    return false;
Ad Schellevis's avatar
Ad Schellevis committed
953 954 955 956 957
}

/* log successful captive portal authentication to syslog */
/* part of this code from php.net */
function captiveportal_logportalauth($user,$mac,$ip,$status, $message = null) {
958 959 960 961 962 963 964 965
    // Log it
    if (!$message)
        $message = "{$status}: {$user}, {$mac}, {$ip}";
    else {
        $message = trim($message);
        $message = "{$status}: {$user}, {$mac}, {$ip}, {$message}";
    }
    captiveportal_syslog($message);
Ad Schellevis's avatar
Ad Schellevis committed
966 967 968 969
}

/* log simple messages to syslog */
function captiveportal_syslog($message) {
970 971 972 973 974 975 976 977
    global $cpzone;

    $message = trim($message);
    $message .= "Zone: {$cpzone} - {$message}";
    openlog("logportalauth", LOG_PID, LOG_LOCAL4);
    // Log it
    syslog(LOG_INFO, $message);
    closelog();
Ad Schellevis's avatar
Ad Schellevis committed
978 979 980
}

function radius($username,$password,$clientip,$clientmac,$type, $radiusctx = null) {
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    global $g, $config, $cpzoneid;

    $pipeno = captiveportal_get_next_dn_ruleno();

    /* If the pool is empty, return appropriate message and fail authentication */
    if (empty($pipeno)) {
        $auth_list = array();
        $auth_list['auth_val'] = 1;
        $auth_list['error'] = "System reached maximum login capacity";
        return $auth_list;
    }

    $radiusservers = captiveportal_get_radius_servers();

    if (is_null($radiusctx))
        $radiusctx = 'first';

    $auth_list = RADIUS_AUTHENTICATION($username,
        $password,
        $radiusservers[$radiusctx],
        $clientip,
        $clientmac,
        $pipeno);

    if ($auth_list['auth_val'] == 2) {
        captiveportal_logportalauth($username,$clientmac,$clientip,$type);
        $sessionid = portal_allow($clientip,
            $clientmac,
            $username,
            $password,
            $auth_list,
            $pipeno,
            $radiusctx);
    } else {
             captiveportal_free_dn_ruleno($pipeno);
           }

    return $auth_list;
Ad Schellevis's avatar
Ad Schellevis committed
1019 1020 1021
}


1022 1023
function captiveportal_write_elements()
{
1024 1025 1026 1027
    global $g, $config, $cpzone;

    $cpcfg = $config['captiveportal'][$cpzone];

1028
    @mkdir('/var/db/cpelements');
1029

1030
    if (isset($cpcfg['element']) && is_array($cpcfg['element'])) {
1031
        foreach ($cpcfg['element'] as $data) {
1032
            if (!@file_put_contents("/var/db/cpelements/{$data['name']}", base64_decode($data['content']))) {
1033 1034 1035
                printf(gettext("Error: cannot open '%s' in captiveportal_write_elements()%s"), $data['name'], "\n");
                return 1;
            }
1036 1037 1038
            if (!file_exists("/usr/local/captiveportal/{$data['name']}")) {
                @symlink("/var/db/cpelements/{$data['name']}", "/usr/local/captiveportal/{$data['name']}");
	    }
1039 1040 1041 1042
        }
    }

    return 0;
Ad Schellevis's avatar
Ad Schellevis committed
1043 1044 1045
}

function captiveportal_free_dnrules($rulenos_start = 2000, $rulenos_range_max = 64500) {
1046 1047 1048
    global $cpzone;

    $cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1049 1050
    if (file_exists("/var/db/captiveportaldn.rules")) {
        $rules = unserialize(file_get_contents("/var/db/captiveportaldn.rules"));
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
        $ridx = $rulenos_start;
        while ($ridx < $rulenos_range_max) {
            if ($rules[$ridx] == $cpzone) {
                $rules[$ridx] = false;
                $ridx++;
                $rules[$ridx] = false;
                $ridx++;
            } else
                $ridx += 2;
        }
1061
        file_put_contents("/var/db/captiveportaldn.rules", serialize($rules));
1062 1063 1064
        unset($rules);
    }
    unlock($cpruleslck);
Ad Schellevis's avatar
Ad Schellevis committed
1065 1066 1067
}

function captiveportal_get_next_dn_ruleno($rulenos_start = 2000, $rulenos_range_max = 64500) {
1068 1069 1070 1071
    global $config, $g, $cpzone;

    $cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
    $ruleno = 0;
1072 1073
    if (file_exists("/var/db/captiveportaldn.rules")) {
        $rules = unserialize(file_get_contents("/var/db/captiveportaldn.rules"));
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
        $ridx = $rulenos_start;
        while ($ridx < $rulenos_range_max) {
            if (empty($rules[$ridx])) {
                $ruleno = $ridx;
                $rules[$ridx] = $cpzone;
                $ridx++;
                $rules[$ridx] = $cpzone;
                break;
            } else {
                $ridx += 2;
            }
        }
    } else {
        $rules = array_pad(array(), $rulenos_range_max, false);
        $ruleno = $rulenos_start;
        $rules[$rulenos_start] = $cpzone;
        $rulenos_start++;
        $rules[$rulenos_start] = $cpzone;
    }
1093
    file_put_contents("/var/db/captiveportaldn.rules", serialize($rules));
1094 1095 1096 1097
    unlock($cpruleslck);
    unset($rules);

    return $ruleno;
Ad Schellevis's avatar
Ad Schellevis committed
1098 1099 1100
}

function captiveportal_free_dn_ruleno($ruleno) {
1101 1102 1103
    global $config, $g;

    $cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1104 1105
    if (file_exists("/var/db/captiveportaldn.rules")) {
        $rules = unserialize(file_get_contents("/var/db/captiveportaldn.rules"));
1106 1107 1108
        $rules[$ruleno] = false;
        $ruleno++;
        $rules[$ruleno] = false;
1109
        file_put_contents("/var/db/captiveportaldn.rules", serialize($rules));
1110 1111 1112
        unset($rules);
    }
    unlock($cpruleslck);
Ad Schellevis's avatar
Ad Schellevis committed
1113 1114
}

1115

Ad Schellevis's avatar
Ad Schellevis committed
1116 1117 1118 1119 1120 1121 1122 1123 1124
/**
 * Get the NAS-IP-Address based on the current wan address
 *
 * Use functions in interfaces.inc to find this out
 *
 */

function getNasIP()
{
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
    global $config, $cpzone;

    if (empty($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
            $nasIp = get_interface_ip();
    } else {
        if (is_ipaddr($config['captiveportal'][$cpzone]['radiussrcip_attribute']))
            $nasIp = $config['captiveportal'][$cpzone]['radiussrcip_attribute'];
        else
            $nasIp = get_interface_ip($config['captiveportal'][$cpzone]['radiussrcip_attribute']);
    }

    if(!is_ipaddr($nasIp))
        $nasIp = "0.0.0.0";

    return $nasIp;
Ad Schellevis's avatar
Ad Schellevis committed
1140 1141 1142
}

function portal_ip_from_client_ip($cliip) {
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    global $config, $cpzone;

    $isipv6 = is_ipaddrv6($cliip);
    $interfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
    foreach ($interfaces as $cpif) {
        if ($isipv6) {
            $ip = get_interface_ipv6($cpif);
            $sn = get_interface_subnetv6($cpif);
        } else {
            $ip = get_interface_ip($cpif);
            $sn = get_interface_subnet($cpif);
        }
        if (ip_in_subnet($cliip, "{$ip}/{$sn}"))
            return $ip;
    }

    $inet = ($isipv6) ? '-inet6' : '-inet';
    $iface = exec_command("/sbin/route -n get {$inet} {$cliip} | /usr/bin/awk '/interface/ { print \$2; };'");
    $iface = trim($iface, "\n");
    if (!empty($iface)) {
        $ip = ($isipv6) ? find_interface_ipv6($iface) : find_interface_ip($iface);
        if (is_ipaddr($ip))
            return $ip;
    }

    // doesn't match up to any particular interface
    // so let's set the portal IP to what PHP says
    // the server IP issuing the request is.
    // allows same behavior as 1.2.x where IP isn't
    // in the subnet of any CP interface (static routes, etc.)
    // rather than forcing to DNS hostname resolution
    $ip = $_SERVER['SERVER_ADDR'];
    if (is_ipaddr($ip))
        return $ip;

    return false;
Ad Schellevis's avatar
Ad Schellevis committed
1179 1180 1181
}

function portal_hostname_from_client_ip($cliip) {
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    global $config, $cpzone;

    $cpcfg = $config['captiveportal'][$cpzone];

    if (isset($cpcfg['httpslogin'])) {
        $listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 8001);
        $ourhostname = $cpcfg['httpsname'];

        if ($listenporthttps != 443)
            $ourhostname .= ":" . $listenporthttps;
    } else {
        $listenporthttp  = $cpcfg['listenporthttp']  ? $cpcfg['listenporthttp']  : ($cpcfg['zoneid'] + 8000);
        $ifip = portal_ip_from_client_ip($cliip);
        if (!$ifip)
            $ourhostname = "{$config['system']['hostname']}.{$config['system']['domain']}";
        else
            $ourhostname = (is_ipaddrv6($ifip)) ? "[{$ifip}]" : "{$ifip}";

        if ($listenporthttp != 80)
            $ourhostname .= ":" . $listenporthttp;
    }

    return $ourhostname;
Ad Schellevis's avatar
Ad Schellevis committed
1205 1206 1207 1208 1209
}

/* functions move from index.php */

function portal_reply_page($redirurl, $type = null, $message = null, $clientmac = null, $clientip = null, $username = null, $password = null) {
1210 1211 1212 1213 1214 1215 1216
    global $g, $config, $cpzone;

    /* Get captive portal layout */
    if ($type == "redir") {
        header("Location: {$redirurl}");
        return;
    } else if ($type == "login")
1217
        $htmltext = get_include_contents("/var/etc/captiveportal_{$cpzone}.html");
1218
    else
1219
        $htmltext = get_include_contents("/var/etc/captiveportal-{$cpzone}-error.html");
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252

    $cpcfg = $config['captiveportal'][$cpzone];

    /* substitute the PORTAL_REDIRURL variable */
    if ($cpcfg['preauthurl']) {
        $htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
        $htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
    }

    /* substitute other variables */
    $ourhostname = portal_hostname_from_client_ip($clientip);
    $protocol = (isset($cpcfg['httpslogin'])) ? 'https://' : 'http://';
    $htmltext = str_replace("\$PORTAL_ACTION\$", "{$protocol}{$ourhostname}/", $htmltext);
    $htmltext = str_replace("#PORTAL_ACTION#", "{$protocol}{$ourhostname}/", $htmltext);

    $htmltext = str_replace("\$PORTAL_ZONE\$", htmlspecialchars($cpzone), $htmltext);
    $htmltext = str_replace("\$PORTAL_REDIRURL\$", htmlspecialchars($redirurl), $htmltext);
    $htmltext = str_replace("\$PORTAL_MESSAGE\$", htmlspecialchars($message), $htmltext);
    $htmltext = str_replace("\$CLIENT_MAC\$", htmlspecialchars($clientmac), $htmltext);
    $htmltext = str_replace("\$CLIENT_IP\$", htmlspecialchars($clientip), $htmltext);

    // Special handling case for captive portal master page so that it can be ran
    // through the PHP interpreter using the include method above.  We convert the
    // $VARIABLE$ case to #VARIABLE# in /usr/local/etc/inc/captiveportal.inc before writing out.
    $htmltext = str_replace("#PORTAL_ZONE#", htmlspecialchars($cpzone), $htmltext);
    $htmltext = str_replace("#PORTAL_REDIRURL#", htmlspecialchars($redirurl), $htmltext);
    $htmltext = str_replace("#PORTAL_MESSAGE#", htmlspecialchars($message), $htmltext);
    $htmltext = str_replace("#CLIENT_MAC#", htmlspecialchars($clientmac), $htmltext);
    $htmltext = str_replace("#CLIENT_IP#", htmlspecialchars($clientip), $htmltext);
    $htmltext = str_replace("#USERNAME#", htmlspecialchars($username), $htmltext);
    $htmltext = str_replace("#PASSWORD#", htmlspecialchars($password), $htmltext);

    echo $htmltext;
Ad Schellevis's avatar
Ad Schellevis committed
1253 1254 1255
}

function portal_mac_radius($clientmac,$clientip) {
1256
    global $config, $cpzone;
Ad Schellevis's avatar
Ad Schellevis committed
1257

1258
    $radmac_secret = $config['captiveportal'][$cpzone]['radmac_secret'];
Ad Schellevis's avatar
Ad Schellevis committed
1259

1260 1261 1262 1263 1264
    /* authentication against the radius server */
    $username = mac_format($clientmac);
    $auth_list = radius($username,$radmac_secret,$clientip,$clientmac,"MACHINE LOGIN");
    if ($auth_list['auth_val'] == 2)
        return TRUE;
Ad Schellevis's avatar
Ad Schellevis committed
1265

1266 1267
    if (!empty($auth_list['url_redirection']))
        portal_reply_page($auth_list['url_redirection'], "redir");
Ad Schellevis's avatar
Ad Schellevis committed
1268

1269
    return FALSE;
Ad Schellevis's avatar
Ad Schellevis committed
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
}



/*
 * Used for when pass-through credits are enabled.
 * Returns true when there was at least one free login to deduct for the MAC.
 * Expired entries are removed as they are seen.
 * Active entries are updated according to the configuration.
 */
function portal_consume_passthrough_credit($clientmac) {
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    global $config, $cpzone;

    if (!empty($config['captiveportal'][$cpzone]['freelogins_count']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_count']))
        $freeloginscount = $config['captiveportal'][$cpzone]['freelogins_count'];
    else
        return false;

    if (!empty($config['captiveportal'][$cpzone]['freelogins_resettimeout']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_resettimeout']))
        $resettimeout = $config['captiveportal'][$cpzone]['freelogins_resettimeout'];
    else
        return false;

    if ($freeloginscount < 1 || $resettimeout <= 0 || !$clientmac)
        return false;

    $updatetimeouts = isset($config['captiveportal'][$cpzone]['freelogins_updatetimeouts']);

    /*
     * Read database of used MACs.  Lines are a comma-separated list
     * of the time, MAC, then the count of pass-through credits remaining.
     */
    $usedmacs = captiveportal_read_usedmacs_db();

    $currenttime = time();
    $found = false;
    foreach ($usedmacs as $key => $usedmac) {
        $usedmac = explode(",", $usedmac);

        if ($usedmac[1] == $clientmac) {
            if ($usedmac[0] + ($resettimeout * 3600) > $currenttime) {
                if ($usedmac[2] < 1) {
                    if ($updatetimeouts) {
                        $usedmac[0] = $currenttime;
                        unset($usedmacs[$key]);
                        $usedmacs[] = implode(",", $usedmac);
                        captiveportal_write_usedmacs_db($usedmacs);
                    }

                    return false;
                } else {
                    $usedmac[2] -= 1;
                    $usedmacs[$key] = implode(",", $usedmac);
                }

                $found = true;
            } else
                unset($usedmacs[$key]);

            break;
        } else if ($usedmac[0] + ($resettimeout * 3600) <= $currenttime)
                unset($usedmacs[$key]);
    }

    if (!$found) {
        $usedmac = array($currenttime, $clientmac, $freeloginscount - 1);
        $usedmacs[] = implode(",", $usedmac);
    }

    captiveportal_write_usedmacs_db($usedmacs);
    return true;
Ad Schellevis's avatar
Ad Schellevis committed
1341 1342 1343
}

function captiveportal_read_usedmacs_db() {
1344 1345 1346
    global $g, $cpzone;

    $cpumaclck = lock("captiveusedmacs{$cpzone}");
1347 1348
    if (file_exists("/var/db/captiveportal_usedmacs_{$cpzone}.db")) {
        $usedmacs = file("/var/db/captiveportal_usedmacs_{$cpzone}.db", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1349 1350 1351 1352 1353 1354 1355
        if (!$usedmacs)
            $usedmacs = array();
    } else
        $usedmacs = array();

    unlock($cpumaclck);
    return $usedmacs;
Ad Schellevis's avatar
Ad Schellevis committed
1356 1357 1358
}

function captiveportal_write_usedmacs_db($usedmacs) {
1359
    global $g, $cpzone;
Ad Schellevis's avatar
Ad Schellevis committed
1360

1361
    $cpumaclck = lock("captiveusedmacs{$cpzone}", LOCK_EX);
1362
    @file_put_contents("/var/db/captiveportal_usedmacs_{$cpzone}.db", implode("\n", $usedmacs));
1363
    unlock($cpumaclck);
Ad Schellevis's avatar
Ad Schellevis committed
1364 1365 1366
}

function captiveportal_blocked_mac($mac) {
1367
    global $config, $g, $cpzone;
Ad Schellevis's avatar
Ad Schellevis committed
1368

1369 1370
    if (empty($mac) || !is_macaddr($mac))
        return false;
Ad Schellevis's avatar
Ad Schellevis committed
1371

1372 1373
    if (!is_array($config['captiveportal'][$cpzone]['passthrumac']))
        return false;
Ad Schellevis's avatar
Ad Schellevis committed
1374

1375 1376 1377 1378
    foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac)
        if (($passthrumac['action'] == 'block') &&
            ($passthrumac['mac'] == strtolower($mac)))
            return true;
Ad Schellevis's avatar
Ad Schellevis committed
1379

1380
    return false;
Ad Schellevis's avatar
Ad Schellevis committed
1381 1382 1383 1384

}

function captiveportal_send_server_accounting($off = false) {
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
    global $cpzone, $config;

    if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) {
        return;
    }
    if ($off) {
        $racct = new Auth_RADIUS_Acct_Off;
    } else {
        $racct = new Auth_RADIUS_Acct_On;
    }
    $radiusservers = captiveportal_get_radius_servers();
    if (empty($radiusservers)) {
        return;
    }
    foreach ($radiusservers['first'] as $radsrv) {
        // Add a new server to our instance
        $racct->addServer($radsrv['ipaddr'], $radsrv['acctport'], $radsrv['key']);
    }
    if (PEAR::isError($racct->start())) {
        $retvalue['acct_val'] = 1;
        $retvalue['error'] = $racct->getMessage();

        // If we encounter an error immediately stop this function and go back
        $racct->close();
        return $retvalue;
    }
    // Send request
    $result = $racct->send();
    // Evaluation of the response
    // 5 -> Accounting-Response
    // See RFC2866 for this.
    if (PEAR::isError($result)) {
        $retvalue['acct_val'] = 1;
        $retvalue['error'] = $result->getMessage();
    } else if ($result === true) {
        $retvalue['acct_val'] = 5 ;
    } else {
        $retvalue['acct_val'] = 1 ;
    }

    $racct->close();
    return $retvalue;
Ad Schellevis's avatar
Ad Schellevis committed
1427
}