Captive Portal: migrate to pf (#8368)

* Captive Portal: WIP for migration to pf (https://github.com/opnsense/core/issues/8326)

Captive Portal: cleanup references to ipfw

Captive Portal: move accounting deletion to get action, update references and descriptions

Captive Portal: remove note

Captive Portal: move accounting to pf match rules

Captive Portal: cleanup and shorten code

Captive Portal: parser issue after refactor

Captive Portal: update logo in default login page

* Captive Portal: internal alias should not be editable

* Captive Portal: move to periodic accounting sync

* Captive Portal: update lighttpd zone config

* Captive Portal: ether rules for accounting

* Captive Portal: safe accounting fetch

* Captive Portal: move counter calculation to bgprocess

* Captive Portal: remove nested anchors, match anchors on interfaces as well

* Captive Portal: move service logic to captiveportal.inc

* Captive Portal: leftover test statement

* Captive Portal: properly initialize accounting result

* Captive Portal: cleanup sql

* Captive Portal: Implement backend requirements for RFC 8908

While here, the zoneid is provided to the client, even though there
there is no need to do so. Instead let lighttpd forward the
request with an added header containing the zoneid of the client

* Captive Portal: review feedback

* Captive Portal: from_not case
This commit is contained in:
Stephan de Wit 2025-03-03 10:48:57 +01:00 committed by GitHub
parent 03f96eb008
commit d08addc25c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
23 changed files with 547 additions and 398 deletions

6
plist
View File

@ -18,6 +18,7 @@
/usr/local/etc/inc/interfaces.lib.inc
/usr/local/etc/inc/legacy_bindings.inc
/usr/local/etc/inc/plugins.inc
/usr/local/etc/inc/plugins.inc.d/captiveportal.inc
/usr/local/etc/inc/plugins.inc.d/core.inc
/usr/local/etc/inc/plugins.inc.d/dhcpd.inc
/usr/local/etc/inc/plugins.inc.d/dhcrelay.inc
@ -738,6 +739,7 @@
/usr/local/opnsense/mvc/app/models/OPNsense/Firewall/Alias.xml
/usr/local/opnsense/mvc/app/models/OPNsense/Firewall/Category.php
/usr/local/opnsense/mvc/app/models/OPNsense/Firewall/Category.xml
/usr/local/opnsense/mvc/app/models/OPNsense/Firewall/DynamicAliases/CaptivePortalAliases.php
/usr/local/opnsense/mvc/app/models/OPNsense/Firewall/DynamicAliases/InterfaceNetworkAliases.php
/usr/local/opnsense/mvc/app/models/OPNsense/Firewall/DynamicAliases/README.md
/usr/local/opnsense/mvc/app/models/OPNsense/Firewall/DynamicAliases/StaticAliases.php
@ -1054,7 +1056,7 @@
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/htdocs_default/fonts/glyphicons-halflings-regular.ttf
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/htdocs_default/fonts/glyphicons-halflings-regular.woff
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/htdocs_default/fonts/glyphicons-halflings-regular.woff2
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/htdocs_default/images/default-logo.png
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/htdocs_default/images/default-logo.svg
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/htdocs_default/images/favicon.png
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/htdocs_default/index.html
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/htdocs_default/js/bootstrap.min.js
@ -1063,7 +1065,7 @@
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/lib/arp.py
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/lib/daemonize.py
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/lib/db.py
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/lib/ipfw.py
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/lib/pf.py
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/listClients.py
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/overlay_template.py
/usr/local/opnsense/scripts/OPNsense/CaptivePortal/process_accounting_messages.php

View File

@ -355,6 +355,7 @@ function filter_configure_sync($verbose = false, $load_aliases = true)
$rules .= "set skip on lo0\n";
$rules .= "set skip on pfsync0\n";
$rules .= "\n";
$rules .= $fw->anchorToText('ether', 'head');
$rules .= filter_generate_scrubbing($cnfint);
$rules .= "\n";
$rules .= $fw->anchorToText('nat,binat,rdr', 'head');

View File

@ -0,0 +1,172 @@
<?php
/*
* Copyright (C) 2025 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.
*/
function captiveportal_services()
{
$services = [];
if ((new \OPNsense\CaptivePortal\CaptivePortal())->isEnabled()) {
$services[] = array(
'pidfile' => '/var/run/lighttpd-api-dispatcher.pid',
'description' => gettext('Captive Portal'),
'configd' => array(
'restart' => array('captiveportal restart'),
'start' => array('captiveportal start'),
'stop' => array('captiveportal stop'),
),
'name' => 'captiveportal',
);
}
return $services;
}
function captiveportal_cron()
{
global $config;
$jobs = [];
if (!empty($config['system']['captiveportalbackup']) && $config['system']['captiveportalbackup'] > 0) {
$jobs[]['autocron'] = array(
'/usr/local/etc/rc.syshook.d/backup/20-captiveportal',
'0',
'*/' . $config['system']['captiveportalbackup']
);
}
return $jobs;
}
function captiveportal_syslog()
{
$logfacilities = [];
$logfacilities['portalauth'] = ['facility' => ['captiveportal']];
return $logfacilities;
}
function captiveportal_firewall($fw)
{
global $config;
$cp = new \OPNsense\CaptivePortal\CaptivePortal();
if ($cp->isEnabled()) {
foreach ($cp->zones->zone->iterateItems() as $zone) {
if ($zone->enabled->isEmpty()) {
continue;
}
$zoneid = (string)$zone->zoneid;
$uuid = $zone->getAttribute('uuid');
// register anchor, to be filled with ether rules for accounting
$fw->registerAnchor("captiveportal_zone_{$zoneid}", "ether", 0, "head", false, (string)$zone->interfaces);
foreach (explode(',', $zone->interfaces) as $intf) {
// allow DNS
$fw->registerFilterRule(
1,
[
'type' => 'pass',
'interface' => $intf,
'protocol' => 'tcp/udp',
'direction' => 'in',
'from' => 'any',
'to' => '(self)',
'to_port' => 53,
'descr' => "Allow DNS for Captive Portal (zone {$zoneid})",
'log' => !isset($config['syslog']['nologdefaultpass']),
'#ref' => "ui/captiveportal#edit={$uuid}",
]
);
foreach (['80', '443'] as $to_port) {
$rdr_port = $to_port === '443' ? (8000 + (int)$zoneid) : (9000 + (int)$zoneid);
// forward to localhost if not authenticated
$fw->registerForwardRule(
2,
[
'interface' => $intf,
'pass' => true,
'nordr' => false,
'ipprotocol' => 'inet',
'protocol' => 'tcp',
'from' => "<__captiveportal_zone_{$zoneid}>",
'from_not' => true,
'to' => 'any',
'to_port' => $to_port,
'target' => '127.0.0.1',
'localport' => $rdr_port,
'descr' => "Redirect to Captive Portal (zone {$zoneid})",
'#ref' => "ui/captiveportal#edit={$uuid}"
]
);
// Allow access to the captive portal
$proto = $to_port === '443' ? 'https': 'http';
$fw->registerFilterRule(
2,
[
'type' => 'pass',
'interface' => $intf,
'protocol' => 'tcp',
'direction' => 'in',
'from' => 'any',
'to' => '(self)',
'to_port' => $rdr_port,
'descr' => "Allow access to Captive Portal ({$proto}, zone {$zoneid})",
'log' => !isset($config['syslog']['nologdefaultpass']),
'#ref' => "ui/captiveportal#edit={$uuid}",
]
);
}
// block all non-authenticated users
$fw->registerFilterRule(
3,
[
'type' => 'block',
'interface' => $intf,
'direction' => 'in',
'from' => "<__captiveportal_zone_{$zoneid}>",
'from_not' => true,
'to' => 'any',
'descr' => "Default Captive Portal block rule (zone {$zoneid})",
'log' => !isset($config['syslog']['nologdefaultblock']),
'#ref' => "ui/captiveportal#edit={$uuid}",
]
);
// we do not create a pass rule for authenticated clients here, any user-defined pass rule will
// automatically apply to the authenticated clients of this zone.
}
}
}
}

View File

@ -32,33 +32,6 @@ function core_services()
$services = array();
if (isset($config['OPNsense']['captiveportal']['zones']['zone'])) {
$enabled = false;
if (!empty($config['OPNsense']['captiveportal']['zones']['zone']['enabled'])) {
// single zone and enabled
$enabled = true;
} else {
// possible more zones, traverse items
foreach ($config['OPNsense']['captiveportal']['zones']['zone'] as $zone) {
if (!empty($zone['enabled'])) {
$enabled = true;
}
}
}
if ($enabled) {
$services[] = array(
'pidfile' => '/var/run/lighttpd-api-dispatcher.pid',
'description' => gettext('Captive Portal'),
'configd' => array(
'restart' => array('captiveportal restart'),
'start' => array('captiveportal start'),
'stop' => array('captiveportal stop'),
),
'name' => 'captiveportal',
);
}
}
$services[] = array(
'description' => gettext('System Configuration Daemon'),
'pidfile' => '/var/run/configd.pid',
@ -330,14 +303,6 @@ function core_cron()
);
}
if (!empty($config['system']['captiveportalbackup']) && $config['system']['captiveportalbackup'] > 0) {
$jobs[]['autocron'] = array(
'/usr/local/etc/rc.syshook.d/backup/20-captiveportal',
'0',
'*/' . $config['system']['captiveportalbackup']
);
}
foreach ((new OPNsense\Backup\BackupFactory())->listProviders() as $classname => $provider) {
if ($provider['handle']->isEnabled()) {
$jobs[]['autocron'] = array('/usr/local/sbin/configctl -d system remote backup 3600', 0, 1);
@ -361,7 +326,6 @@ function core_syslog()
$logfacilities['dhcpd'] = ['facility' => ['dhcpd']];
$logfacilities['lighttpd'] = ['facility' => ['lighttpd']];
$logfacilities['pkg'] = ['facility' => ['pkg', 'pkg-static']];
$logfacilities['portalauth'] = ['facility' => ['captiveportal']];
$logfacilities['ppps'] = ['facility' => ['ppp']];
$logfacilities['resolver'] = ['facility' => ['unbound']];
$logfacilities['routing'] = ['facility' => ['routed', 'olsrd', 'zebra', 'ospfd', 'bgpd', 'miniupnpd']];

View File

@ -25,7 +25,7 @@
# POSSIBILITY OF SUCH DAMAGE.
# PROVIDE: captiveportal
# REQUIRE: ipfw
# REQUIRE: pf
# KEYWORD: shutdown
. /etc/rc.subr

View File

@ -117,7 +117,7 @@ class AccessController extends ApiControllerBase
/**
* logon client to zone, must use post type of request
* @param int|string $zoneid zone id number
* @param int|string $zoneid zone id number, provided for backwards compatibility
* @return array
* @throws \OPNsense\Base\ModelException
*/
@ -131,6 +131,7 @@ class AccessController extends ApiControllerBase
// init variables for authserver object and name
$authServer = null;
$authServerName = "";
$zoneid = $this->request->getHeader("zoneid");
// get username from post
$userName = $this->request->getPost("user", "striptags", null);
@ -223,9 +224,10 @@ class AccessController extends ApiControllerBase
/**
* logoff client
* @param int|string $zoneid zone id number
* @param int|string $zoneid zone id number, provided for backwards compatibility
* @return array
* @throws \OPNsense\Base\ModelException
*
*/
public function logoffAction($zoneid = 0)
{
@ -233,6 +235,7 @@ class AccessController extends ApiControllerBase
// return empty result on CORS preflight
return [];
} else {
$zoneid = $this->request->getHeader("zoneid");
$clientSession = $this->clientSession((string)$zoneid);
if (
$clientSession['clientState'] == 'AUTHORIZED' &&
@ -256,9 +259,10 @@ class AccessController extends ApiControllerBase
/**
* retrieve session info
* @param int|string $zoneid zone id number
* @param int|string $zoneid zone id number, provided for backwards compatibility
* @return array
* @throws \OPNsense\Base\ModelException
*
*/
public function statusAction($zoneid = 0)
{
@ -266,8 +270,64 @@ class AccessController extends ApiControllerBase
// return empty result on CORS preflight
return [];
} elseif ($this->request->isPost() || $this->request->isGet()) {
$clientSession = $this->clientSession((string)$zoneid);
$clientSession = $this->clientSession($this->request->getHeader("zoneid"));
return $clientSession;
}
}
/**
* RFC 8908: Captive Portal API status object
*
* The URI for this endpoint can be provisioned to the client
* as defined by RFC 7710.
*
* Request and response must set media type as "application/captive+json".
*
* Response contains the following fields:
* - captive: boolean: client is currently in a state of captivity.
* - user-portal-url: string: URL to login web portal (must be HTTPS).
* - seconds-remaining: number: seconds until session expires,
* only relevant if hardtimeout set.
*
* Fields not implemented here but possible in the future:
* - venue-info-url: string: Information page (must be HTTPS)
* - can-extend-session: boolean: hint that client system can access
* user-portal-url to extend session.
* - bytes-remaining: number: no. of bytes after which session expires.
*
* Response must set Cache-Control to 'private' or 'no-store'
*/
public function apiAction()
{
if ($this->request->isGet() &&
$this->request->getHeader("accept") == "application/captive+json") {
$result = [];
$zoneId = $this->request->getHeader("zoneid");
$clientSession = $this->clientSession($zoneId);
$captive = $clientSession["clientState"] != "AUTHORIZED";
$host = $this->request->getHeader('X-Forwarded-Host');
$zone = (new \OPNsense\CaptivePortal\CaptivePortal())->getByZoneId($zoneId);
if ($zone != null && !empty((string)$zone->hardtimeout) && !empty($clientSession['startTime'])) {
if ((time() - (int)$clientSession['startTime']) < (string)$zone->hardtimeout * 60) {
$result['seconds-remaining'] = (string)$zone->hardtimeout * 60 - ((time() - (int)$clientSession['startTime']));
}
}
$this->response->setRawHeader("Cache-Control: private");
$this->response->setContentType("application/captive+json");
$result["captive"] = $captive;
$result["user-portal-url"] = "https://{$host}/index.html";
$this->response->setContent($result);
return;
}
$this->response->setStatusCode(400);
$this->response->setContentType('application/json', 'UTF-8');
$this->response->setContent(['status' => 400, 'message' => 'Bad request']);
}
}

View File

@ -48,9 +48,7 @@ class ServiceController extends ApiControllerBase
{
if ($this->request->isPost()) {
$backend = new Backend();
// the ipfw rules need to know about all the zones, so we need to reload ipfw for the portal to work
$backend->configdRun('template reload OPNsense/IPFW');
$bckresult = trim($backend->configdRun("ipfw reload"));
$bckresult = trim($backend->configdRun("filter reload"));
if ($bckresult == "OK") {
// generate captive portal config
$bckresult = trim($backend->configdRun('template reload OPNsense/Captiveportal'));

View File

@ -214,10 +214,10 @@ class Plugin
* @param bool $quick
* @return null
*/
public function registerAnchor($name, $type = "fw", $priority = 0, $placement = "tail", $quick = false)
public function registerAnchor($name, $type = "fw", $priority = 0, $placement = "tail", $quick = false, $ifs = null)
{
$anchorKey = sprintf("%s.%s.%08d.%08d", $type, $placement, $priority, count($this->anchors));
$this->anchors[$anchorKey] = array('name' => $name, 'quick' => $quick);
$this->anchors[$anchorKey] = ['name' => $name, 'quick' => $quick, 'ifs' => $ifs];
ksort($this->anchors);
}
@ -233,11 +233,21 @@ class Plugin
foreach (explode(',', $types) as $type) {
foreach ($this->anchors as $anchorKey => $anchor) {
if (strpos($anchorKey, "{$type}.{$placement}") === 0) {
$result .= $type == "fw" ? "" : "{$type}-";
$result .= "anchor \"{$anchor['name']}\"";
$result .= ($type == "fw" || $type == "ether") ? "" : "{$type}-";
$prefix = $type == "ether" ? "ether " : "";
$result .= "{$prefix}anchor \"{$anchor['name']}\"";
if ($anchor['quick']) {
$result .= " quick";
}
if (!empty($anchor['ifs'])) {
$ifs = array_filter(array_map(function($if) {
return $this->interfaceMapping[$if]['if'] ?? null;
}, explode(',', $anchor['ifs'])));
if (!empty($ifs)) {
$result .= " on {" . implode(', ', $ifs) . "}";
}
}
$result .= "\n";
}
}

View File

@ -0,0 +1,60 @@
<?php
/**
* Copyright (C) 2025 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.
*
*/
namespace OPNsense\Firewall\DynamicAliases;
use OPNsense\Core\Config;
class CaptivePortalAliases
{
public function collect()
{
$result = [];
$cp = new \OPNsense\CaptivePortal\CaptivePortal();
if ($cp->isEnabled()) {
foreach ($cp->zones->zone->iterateItems() as $zone) {
if (empty((string)$zone->enabled)) {
continue;
}
$zoneid = (string)$zone->zoneid;
$result["__captiveportal_zone_{$zoneid}"] = [
"enabled" => "1",
"name" => "__captiveportal_zone_{$zoneid}",
"type" => "internal",
"description" => sprintf("%s %s", (string)$zone->descr, gettext("captiveportal")),
"content" => "",
];
}
}
return $result;
}
}

View File

@ -37,7 +37,10 @@
set:'/api/captiveportal/settings/setZone/',
add:'/api/captiveportal/settings/addZone/',
del:'/api/captiveportal/settings/delZone/',
toggle:'/api/captiveportal/settings/toggleZone/'
toggle:'/api/captiveportal/settings/toggleZone/',
options: {
triggerEditFor: getUrlHash('edit')
}
}
);

View File

@ -33,7 +33,7 @@ import sys
import ujson
from lib.db import DB
from lib.arp import ARP
from lib.ipfw import IPFW
from lib.pf import PF
parser = argparse.ArgumentParser()
parser.add_argument('-username', help='username', type=str, required=True)
@ -50,6 +50,6 @@ response = DB().add_client(
ip_address=args.ip_address,
mac_address=arp_entry['mac'] if arp_entry is not None else None
)
IPFW().add_to_table(table_number=args.zoneid, address=args.ip_address)
PF.add_to_table(zoneid=args.zoneid, address=args.ip_address)
response['clientState'] = 'AUTHORIZED'
print(ujson.dumps(response))

View File

@ -38,7 +38,7 @@ sys.path.insert(0, "/usr/local/opnsense/site-python")
from lib import Config
from lib.db import DB
from lib.arp import ARP
from lib.ipfw import IPFW
from lib.pf import PF
from lib.daemonize import Daemonize
from sqlite3_helper import check_and_repair
@ -50,18 +50,45 @@ class CPBackgroundProcess(object):
# open syslog and notice startup
syslog.openlog('captiveportal', facility=syslog.LOG_LOCAL4)
syslog.syslog(syslog.LOG_NOTICE, 'starting captiveportal background process')
# handles to ipfw, arp the config and the internal administration
self.ipfw = IPFW()
# handles to pf, arp, the config and the internal administration
self.arp = ARP()
self.cnf = Config()
self.db = DB()
self._conf_zone_info = self.cnf.get_zones()
self._accounting_info = {k: {'cur': {}, 'prev': {}, 'reset': False} for k in self.list_zone_ids()}
def list_zone_ids(self):
""" return zone numbers
"""
return self._conf_zone_info.keys()
def get_accounting(self):
""" returns only how much the accounting should add in total
"""
result = {}
for zoneid in self.list_zone_ids():
self._accounting_info[zoneid]['prev'] = self._accounting_info[zoneid]['cur']
self._accounting_info[zoneid]['cur'] = PF.list_accounting_info(zoneid)
if self._accounting_info[zoneid]['reset']:
# counters were reset to 0, simply add
result[zoneid] = self._accounting_info[zoneid]['cur']
else:
# counters still valid, calculate difference
result[zoneid] = {}
for ip in self._accounting_info[zoneid]['cur']:
result[zoneid][ip] = {'last_accessed': self._accounting_info[zoneid]['cur'][ip]['last_accessed']}
for key in ['in_pkts', 'in_bytes', 'out_pkts', 'out_bytes']:
if ip not in self._accounting_info[zoneid]['prev']:
result[zoneid][ip][key] = self._accounting_info[zoneid]['cur'][ip][key]
else:
result[zoneid][ip][key] = self._accounting_info[zoneid]['cur'][ip][key] \
- self._accounting_info[zoneid]['prev'][ip][key]
# map to flat dict of IPs
return {k: v for subdict in result.values() for k, v in subdict.items()}
def initialize_fixed(self):
""" initialize fixed ip / hosts per zone
"""
@ -94,12 +121,12 @@ class CPBackgroundProcess(object):
for dbclient in self.db.list_clients(zoneid):
if dbclient['authenticated_via'] == '---ip---' \
and dbclient['ipAddress'] not in cpzones[zoneid]['allowedaddresses']:
self.ipfw.delete(zoneid, dbclient['ipAddress'])
PF.remove_from_table(zoneid, dbclient['ipAddress'])
self.db.del_client(zoneid, dbclient['sessionId'])
elif dbclient['authenticated_via'] == '---mac---' \
and dbclient['macAddress'] not in cpzones[zoneid]['allowedmacaddresses']:
if dbclient['ipAddress'] != '':
self.ipfw.delete(zoneid, dbclient['ipAddress'])
PF.remove_from_table(zoneid, dbclient['ipAddress'])
self.db.del_client(zoneid, dbclient['sessionId'])
def sync_zone(self, zoneid):
@ -109,8 +136,7 @@ class CPBackgroundProcess(object):
if zoneid in self._conf_zone_info:
# fetch data for this zone
cpzone_info = self._conf_zone_info[zoneid]
registered_addresses = self.ipfw.list_table(zoneid)
registered_addr_accounting = self.ipfw.list_accounting_info()
registered_addresses = PF.list_table(zoneid)
expected_clients = self.db.list_clients(zoneid)
concurrent_users = self.db.find_concurrent_user_sessions(zoneid)
@ -160,23 +186,22 @@ class CPBackgroundProcess(object):
if current_ip is not None and db_client['ipAddress'] != current_ip:
if db_client['ipAddress'] != '':
# remove old ip
self.ipfw.delete(zoneid, db_client['ipAddress'])
PF.remove_from_table(zoneid, db_client['ipAddress'])
self.db.update_client_ip(zoneid, db_client['sessionId'], current_ip)
self.ipfw.add_to_table(zoneid, current_ip)
PF.add_to_table(zoneid, current_ip)
# check session, if it should be active, validate its properties
if drop_session_reason is None:
# registered client, but not active or missing accounting according to ipfw (after reboot)
if cpnet not in registered_addresses or cpnet not in registered_addr_accounting:
self.ipfw.add_to_table(zoneid, cpnet)
# registered client, but not active or missing accounting according to pf (after reboot)
if cpnet not in registered_addresses:
PF.add_to_table(zoneid, cpnet)
else:
# remove session
syslog.syslog(syslog.LOG_NOTICE, drop_session_reason)
self.ipfw.delete(zoneid, cpnet)
PF.remove_from_table(zoneid, cpnet)
self.db.del_client(zoneid, db_client['sessionId'])
# if there are addresses/networks in the underlying ipfw table which are not in our administration,
# remove them from ipfw.
# if there are addresses/networks in the underlying pf table which are not in our administration,
# remove them from pf.
for registered_address in registered_addresses:
address_active = False
for db_client in expected_clients:
@ -184,12 +209,24 @@ class CPBackgroundProcess(object):
address_active = True
break
if not address_active:
self.ipfw.delete(zoneid, registered_address)
PF.remove_from_table(zoneid, registered_address)
def sync_accounting(self):
for zoneid in self.list_zone_ids():
pf_stats = self._accounting_info[zoneid]['cur']
current_clients = self.db.list_clients(zoneid)
pf_ips = set(pf_stats.keys())
db_ips = {entry['ipAddress'] for entry in current_clients}
self._accounting_info[zoneid]['reset'] = False
if pf_ips != db_ips:
self._accounting_info[zoneid]['reset'] = True
PF.sync_accounting(zoneid)
def main():
""" Background process loop, runs as backend daemon for all zones. only one should be active at all times.
The main job of this procedure is to sync the administration with the actual situation in the ipfw firewall.
The main job of this procedure is to sync the administration with the actual situation in pf.
"""
# perform integrity check and repair database if needed
check_and_repair('/var/captiveportal/captiveportal.sqlite')
@ -211,13 +248,16 @@ def main():
# reload cached arp table contents
bgprocess.arp.reload()
# update accounting info, for all zones
bgprocess.db.update_accounting_info(bgprocess.ipfw.list_accounting_info())
# process sessions per zone
for zoneid in bgprocess.list_zone_ids():
bgprocess.sync_zone(zoneid)
# update accounting info, for all zones
bgprocess.db.update_accounting_info(bgprocess.get_accounting())
# sync accounting after db update, resets zone counters if sync is needed
bgprocess.sync_accounting()
# close the database handle while waiting for the next poll
bgprocess.db.close()

View File

@ -31,8 +31,7 @@
import argparse
import ujson
from lib.db import DB
from lib.ipfw import IPFW
from lib.pf import PF
parser = argparse.ArgumentParser()
parser.add_argument('session', help='session id to delete', type=str)
@ -43,7 +42,7 @@ response = {'terminateCause': 'UNKNOWN'}
client_session_info = DB().del_client(int(args.z) if str(args.z).isdigit() else None, args.session)
if client_session_info is not None:
if client_session_info['ip_address']:
IPFW().delete(client_session_info['zoneid'], client_session_info['ip_address'])
PF.remove_from_table(client_session_info['zoneid'], client_session_info['ip_address'])
client_session_info['terminateCause'] = 'User-Request'
response = client_session_info

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 1200 359" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(4.16667,0,0,4.16667,0,0)">
<path d="M18.602,0.961L18.602,19.563L66.437,19.563L66.437,67.398L85.039,67.398L85.039,27.536L58.464,0.961L18.602,0.961Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M66.437,86L66.437,67.398L18.602,67.398L18.602,19.563L0,19.563L0,59.426L26.574,86L66.437,86Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M105.6,69.491C104.445,69.128 103.467,68.564 103.467,67.338C103.467,65.828 104.61,64.875 106.54,64.875C107.53,64.875 108.38,65.073 109.079,65.345L108.971,66.317C108.298,66.005 107.39,65.828 106.628,65.828C105.366,65.828 104.579,66.323 104.579,67.243C104.579,68.145 105.333,68.348 106.089,68.595L107.441,69.027C108.85,69.491 109.51,70.106 109.51,71.281C109.51,72.759 108.298,73.749 106.407,73.749C105.391,73.749 104.198,73.515 103.449,73.16L103.55,72.169C104.287,72.518 105.422,72.791 106.324,72.791C107.581,72.791 108.418,72.251 108.418,71.312C108.418,70.62 108.038,70.258 107.054,69.948L105.6,69.491Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M115.705,70.118C115.634,69.077 114.917,68.341 113.755,68.341C112.607,68.341 111.762,69.077 111.667,70.118L115.705,70.118ZM116.352,73.153C115.641,73.566 114.873,73.749 114.054,73.749C112.003,73.749 110.588,72.454 110.588,70.576C110.588,68.76 111.896,67.402 113.724,67.402C115.787,67.402 116.955,69.072 116.624,70.944L111.642,70.944C111.813,72.144 112.829,72.804 114.009,72.804C114.72,72.804 115.355,72.683 116.174,72.239L116.352,73.153Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M121.212,67.402C122.038,67.402 122.743,67.643 123.04,67.808L122.933,68.716C122.527,68.519 121.917,68.348 121.212,68.348C119.785,68.348 118.807,69.243 118.807,70.557C118.807,71.883 119.79,72.804 121.225,72.804C121.841,72.804 122.533,72.645 122.984,72.416L123.149,73.337C122.609,73.578 121.898,73.749 121.225,73.749C119.181,73.749 117.785,72.454 117.785,70.557C117.785,68.684 119.175,67.402 121.212,67.402Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M129.044,67.529L130.039,67.529L130.039,71.147C130.039,72.677 128.961,73.749 127.28,73.749C125.597,73.749 124.518,72.69 124.518,71.185L124.518,67.529L125.521,67.529L125.521,71.001C125.521,72.144 126.226,72.804 127.28,72.804C128.339,72.804 129.044,72.144 129.044,71.001L129.044,67.529Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M133.003,68.43C133.346,67.726 133.95,67.402 134.648,67.402C135.08,67.402 135.397,67.51 135.511,67.561L135.41,68.493C135.238,68.43 135.003,68.341 134.61,68.341C133.797,68.341 133.003,68.874 133.003,70.24L133.003,73.622L131.988,73.622L131.988,67.529L133.003,67.529L133.003,68.43Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M136.753,67.529L137.762,67.529L137.762,73.622L136.753,73.622L136.753,67.529ZM136.632,65.485C136.632,65.117 136.886,64.863 137.254,64.863C137.623,64.863 137.889,65.117 137.889,65.485C137.889,65.853 137.623,66.114 137.254,66.114C136.886,66.114 136.632,65.853 136.632,65.485Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M145.429,69.915L145.429,73.622L144.426,73.622L144.426,70.163C144.426,68.976 143.804,68.354 142.7,68.354C141.659,68.354 140.814,69.072 140.814,70.182L140.814,73.622L139.805,73.622L139.805,67.529L140.821,67.529L140.821,68.443C141.164,67.878 141.887,67.402 142.858,67.402C144.464,67.402 145.429,68.348 145.429,69.915Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M147.928,70.557C147.928,71.82 148.83,72.835 150.099,72.835C151.401,72.835 152.359,71.82 152.359,70.557C152.359,69.3 151.401,68.316 150.099,68.316C148.83,68.316 147.928,69.3 147.928,70.557ZM149.998,73.749C148.252,73.749 146.925,72.391 146.925,70.557C146.925,68.729 148.252,67.402 149.998,67.402C151.089,67.402 151.889,67.871 152.346,68.526L152.346,67.529L153.356,67.529L153.356,73.216C153.356,74.988 152.143,76.288 149.909,76.288C149.154,76.288 148.151,76.118 147.509,75.781L147.668,74.861C148.347,75.197 149.154,75.374 149.903,75.374C151.318,75.374 152.346,74.658 152.346,73.292L152.346,72.619C151.902,73.261 151.089,73.749 149.998,73.749Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M164.023,69.915L164.023,73.622L163.02,73.622L163.02,70.163C163.02,68.976 162.398,68.354 161.293,68.354C160.252,68.354 159.409,69.072 159.409,70.182L159.409,73.622L158.399,73.622L158.399,67.529L159.415,67.529L159.415,68.443C159.757,67.878 160.481,67.402 161.453,67.402C163.058,67.402 164.023,68.348 164.023,69.915Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M170.629,70.118C170.56,69.077 169.842,68.341 168.681,68.341C167.532,68.341 166.688,69.077 166.592,70.118L170.629,70.118ZM171.277,73.153C170.566,73.566 169.798,73.749 168.979,73.749C166.929,73.749 165.513,72.454 165.513,70.576C165.513,68.76 166.821,67.402 168.649,67.402C170.712,67.402 171.88,69.072 171.55,70.944L166.567,70.944C166.739,72.144 167.754,72.804 168.935,72.804C169.646,72.804 170.281,72.683 171.099,72.239L171.277,73.153Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M174.456,68.399L174.456,71.693C174.456,72.493 174.887,72.842 175.509,72.842C175.839,72.842 176.258,72.779 176.55,72.67L176.684,73.54C176.423,73.655 175.897,73.749 175.402,73.749C174.227,73.749 173.447,73.102 173.447,71.858L173.447,68.399L172.323,68.399L172.323,67.529L173.453,67.529L173.453,65.574L174.45,65.574L174.45,67.529L176.398,67.529L176.398,68.399L174.456,68.399Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M182.42,67.592L184.071,72.664L185.588,67.529L186.655,67.529L184.756,73.622L183.405,73.622L181.887,69.001L180.371,73.622L179.018,73.622L177.114,67.529L178.187,67.529L179.698,72.658L181.348,67.592L182.42,67.592Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M190.614,72.81C191.896,72.81 192.841,71.832 192.841,70.576C192.841,69.319 191.896,68.341 190.614,68.341C189.332,68.341 188.385,69.319 188.385,70.576C188.385,71.832 189.332,72.81 190.614,72.81ZM190.614,67.402C192.467,67.402 193.851,68.792 193.851,70.576C193.851,72.36 192.467,73.749 190.614,73.749C188.76,73.749 187.376,72.36 187.376,70.576C187.376,68.792 188.76,67.402 190.614,67.402Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M196.433,68.43C196.776,67.726 197.378,67.402 198.077,67.402C198.508,67.402 198.826,67.51 198.94,67.561L198.838,68.493C198.667,68.43 198.432,68.341 198.039,68.341C197.226,68.341 196.433,68.874 196.433,70.24L196.433,73.622L195.417,73.622L195.417,67.529L196.433,67.529L196.433,68.43Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M200.183,64.685L201.192,64.685L201.192,70.036L202.494,70.036L204.131,67.529L205.254,67.529L203.281,70.499L205.572,73.622L204.391,73.622L202.43,70.906L201.192,70.906L201.192,73.622L200.183,73.622L200.183,64.685Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M209.169,70.189C210.382,70.43 211.023,70.976 211.023,71.928C211.023,73.115 210.078,73.749 208.598,73.749C207.735,73.749 206.884,73.578 206.313,73.292L206.453,72.391C207.011,72.677 207.792,72.848 208.529,72.848C209.506,72.848 210.033,72.543 210.033,71.979C210.033,71.433 209.563,71.204 208.707,71.039L207.913,70.88C206.904,70.684 206.256,70.151 206.256,69.211C206.256,68.125 207.214,67.402 208.732,67.402C209.468,67.402 210.21,67.541 210.687,67.739L210.56,68.62C210.065,68.424 209.392,68.297 208.795,68.297C207.805,68.297 207.259,68.627 207.259,69.186C207.259,69.712 207.678,69.897 208.535,70.062L209.169,70.189Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M225.538,69.897L225.538,73.622L224.528,73.622L224.528,70.144C224.528,69.021 223.906,68.354 222.846,68.354C221.856,68.354 221.037,69.046 221.037,70.125L221.037,73.622L220.028,73.622L220.028,70.144C220.028,69.021 219.406,68.354 218.383,68.354C217.362,68.354 216.549,69.059 216.549,70.163L216.549,73.622L215.54,73.622L215.54,67.529L216.549,67.529L216.549,68.437C216.885,67.871 217.596,67.402 218.548,67.402C219.627,67.402 220.409,67.884 220.777,68.684C221.189,67.891 222.014,67.402 223.004,67.402C224.591,67.402 225.538,68.405 225.538,69.897Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M228.037,70.557C228.037,71.82 228.938,72.835 230.207,72.835C231.509,72.835 232.467,71.82 232.467,70.557C232.467,69.3 231.509,68.316 230.207,68.316C228.938,68.316 228.037,69.3 228.037,70.557ZM233.464,73.622L232.455,73.622L232.455,72.619C231.998,73.274 231.198,73.749 230.106,73.749C228.361,73.749 227.034,72.391 227.034,70.557C227.034,68.729 228.361,67.402 230.106,67.402C231.198,67.402 231.998,67.871 232.455,68.526L232.455,67.529L233.464,67.529L233.464,73.622Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M240.477,70.563C240.477,69.3 239.518,68.316 238.217,68.316C236.948,68.316 236.046,69.3 236.046,70.563C236.046,71.82 236.948,72.835 238.217,72.835C239.518,72.835 240.477,71.82 240.477,70.563ZM240.464,72.632C240.007,73.28 239.207,73.749 238.116,73.749C236.37,73.749 235.043,72.391 235.043,70.563C235.043,68.735 236.37,67.402 238.116,67.402C239.207,67.402 240.007,67.878 240.464,68.532L240.464,64.685L241.473,64.685L241.473,73.622L240.464,73.622L240.464,72.632Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M248.162,70.118C248.092,69.077 247.374,68.341 246.213,68.341C245.064,68.341 244.22,69.077 244.124,70.118L248.162,70.118ZM248.809,73.153C248.098,73.566 247.331,73.749 246.511,73.749C244.461,73.749 243.045,72.454 243.045,70.576C243.045,68.76 244.353,67.402 246.181,67.402C248.245,67.402 249.413,69.072 249.082,70.944L244.099,70.944C244.271,72.144 245.287,72.804 246.467,72.804C247.178,72.804 247.813,72.683 248.631,72.239L248.809,73.153Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M258.359,70.118C258.29,69.077 257.573,68.341 256.411,68.341C255.262,68.341 254.417,69.077 254.323,70.118L258.359,70.118ZM259.006,73.153C258.295,73.566 257.528,73.749 256.709,73.749C254.659,73.749 253.244,72.454 253.244,70.576C253.244,68.76 254.551,67.402 256.379,67.402C258.441,67.402 259.609,69.072 259.28,70.944L254.297,70.944C254.468,72.144 255.484,72.804 256.665,72.804C257.375,72.804 258.01,72.683 258.829,72.239L259.006,73.153Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M261.45,70.557C261.45,71.82 262.351,72.835 263.621,72.835C264.921,72.835 265.88,71.82 265.88,70.557C265.88,69.3 264.921,68.316 263.621,68.316C262.351,68.316 261.45,69.3 261.45,70.557ZM266.876,73.622L265.868,73.622L265.868,72.619C265.411,73.274 264.611,73.749 263.519,73.749C261.773,73.749 260.446,72.391 260.446,70.557C260.446,68.729 261.773,67.402 263.519,67.402C264.611,67.402 265.411,67.871 265.868,68.526L265.868,67.529L266.876,67.529L266.876,73.622Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M271.37,70.189C272.582,70.43 273.223,70.976 273.223,71.928C273.223,73.115 272.277,73.749 270.798,73.749C269.935,73.749 269.084,73.578 268.513,73.292L268.653,72.391C269.211,72.677 269.992,72.848 270.728,72.848C271.706,72.848 272.233,72.543 272.233,71.979C272.233,71.433 271.763,71.204 270.906,71.039L270.113,70.88C269.103,70.684 268.456,70.151 268.456,69.211C268.456,68.125 269.415,67.402 270.931,67.402C271.667,67.402 272.411,67.541 272.886,67.739L272.759,68.62C272.264,68.424 271.591,68.297 270.995,68.297C270.004,68.297 269.458,68.627 269.458,69.186C269.458,69.712 269.877,69.897 270.735,70.062L271.37,70.189Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M278.992,67.529L280.102,67.529L277.227,74.397C276.707,75.61 276.135,76.288 274.904,76.288C274.415,76.288 274.034,76.168 273.863,76.079L273.983,75.222C274.193,75.318 274.529,75.387 274.846,75.387C275.539,75.387 275.951,74.95 276.306,74.079L276.415,73.794L273.78,67.529L274.878,67.529L276.954,72.632L278.992,67.529Z" style="fill:rgb(228,74,32);fill-rule:nonzero;"/>
<path d="M140.024,37.345L140.024,43.579L144.106,43.579C146.277,43.579 147.668,42.503 147.668,40.462C147.668,38.309 146.351,37.345 144.106,37.345L140.024,37.345ZM140.024,49.665L140.024,56.437L132.621,56.437L132.621,31.24L145.368,31.24C151.658,31.24 155.183,35.229 155.183,40.313C155.183,45.453 151.658,49.665 145.368,49.665L140.024,49.665Z" style="fill:rgb(64,63,65);fill-rule:nonzero;"/>
<path d="M164.994,56.437L157.794,56.437L157.794,31.24L163.825,31.24L175.31,44.692L175.31,31.24L182.509,31.24L182.509,56.437L176.739,56.437L164.994,43.134L164.994,56.437Z" style="fill:rgb(64,63,65);fill-rule:nonzero;"/>
<path d="M195.603,45.527C199.332,46.177 200.854,47.809 200.854,50.927C200.854,54.601 197.848,56.809 192.82,56.809C190.074,56.809 187.309,56.4 185.398,55.732L186.047,50.389C187.272,50.815 189.74,51.446 192.003,51.446C193.488,51.446 194.36,51.279 194.36,50.834C194.36,50.426 193.729,50.296 192.133,50.073L190.964,49.906C186.938,49.331 185.12,47.754 185.12,44.358C185.12,40.536 188.33,38.254 193.673,38.254C195.974,38.254 198.683,38.718 199.926,39.182L199.24,44.6C198.331,44.21 195.918,43.765 194.249,43.765C192.337,43.765 191.484,43.987 191.484,44.488C191.484,44.896 192.263,44.952 194.434,45.323L195.603,45.527Z" style="fill:rgb(64,63,65);fill-rule:nonzero;"/>
<path d="M214.468,45.713C214.468,44.655 213.578,43.431 212.093,43.431C210.405,43.431 209.551,44.544 209.44,45.713L214.468,45.713ZM220.294,55.25C219.033,55.955 216.435,56.809 213.411,56.809C206.675,56.809 202.779,53.098 202.779,47.494C202.779,41.909 206.527,38.254 212.186,38.254C217.827,38.254 221.872,41.668 220.74,49.09L209.44,49.09C209.57,50.463 211.555,51.279 213.745,51.279C216.101,51.279 218.346,50.76 219.497,50.203L220.294,55.25Z" style="fill:rgb(64,63,65);fill-rule:nonzero;"/>
<path d="M242.054,44.488L242.054,56.437L234.929,56.437L234.929,46.603C234.929,45.342 234.039,44.47 232.758,44.47C231.478,44.47 230.606,45.342 230.606,46.603L230.606,56.437L223.481,56.437L223.481,38.625L229.975,38.625L230.142,40.332C231.144,39.107 233.129,38.254 235.671,38.254C239.457,38.254 242.054,40.777 242.054,44.488Z" style="fill:rgb(64,63,65);fill-rule:nonzero;"/>
<path d="M254.999,45.527C258.729,46.177 260.25,47.809 260.25,50.927C260.25,54.601 257.245,56.809 252.216,56.809C249.47,56.809 246.706,56.4 244.794,55.732L245.444,50.389C246.668,50.815 249.136,51.446 251.4,51.446C252.884,51.446 253.756,51.279 253.756,50.834C253.756,50.426 253.125,50.296 251.53,50.073L250.361,49.906C246.334,49.331 244.516,47.754 244.516,44.358C244.516,40.536 247.726,38.254 253.07,38.254C255.371,38.254 258.079,38.718 259.323,39.182L258.635,44.6C257.726,44.21 255.315,43.765 253.645,43.765C251.734,43.765 250.88,43.987 250.88,44.488C250.88,44.896 251.66,44.952 253.831,45.323L254.999,45.527Z" style="fill:rgb(64,63,65);fill-rule:nonzero;"/>
<path d="M273.865,45.713C273.865,44.655 272.974,43.431 271.49,43.431C269.801,43.431 268.948,44.544 268.836,45.713L273.865,45.713ZM279.691,55.25C278.429,55.955 275.832,56.809 272.807,56.809C266.072,56.809 262.175,53.098 262.175,47.494C262.175,41.909 265.923,38.254 271.582,38.254C277.223,38.254 281.268,41.668 280.136,49.09L268.836,49.09C268.966,50.463 270.952,51.279 273.141,51.279C275.498,51.279 277.743,50.76 278.893,50.203L279.691,55.25Z" style="fill:rgb(64,63,65);fill-rule:nonzero;"/>
<path d="M283.51,32.01L283.51,33.063L284.174,33.063C284.519,33.063 284.731,32.827 284.731,32.533C284.731,32.216 284.505,32.01 284.174,32.01L283.51,32.01ZM283.51,35.029L282.543,35.029L282.543,31.141L284.308,31.141C285.112,31.141 285.733,31.708 285.733,32.533C285.733,33.033 285.458,33.49 285.063,33.733L286.016,35.029L284.865,35.029L284.068,33.924L283.51,33.924L283.51,35.029ZM284.145,35.949C285.747,35.949 287.046,34.815 287.046,33.107C287.046,31.435 285.719,30.25 284.145,30.25C282.564,30.25 281.308,31.435 281.308,33.107C281.308,34.815 282.55,35.949 284.145,35.949ZM284.145,29.308C286.206,29.308 287.978,30.957 287.978,33.107C287.978,35.345 286.298,36.921 284.145,36.921C282.099,36.921 280.362,35.367 280.362,33.107C280.369,30.913 282.056,29.308 284.145,29.308Z" style="fill:rgb(64,63,65);fill-rule:nonzero;"/>
<path d="M116.372,50.222C112.753,50.222 110.323,47.624 110.323,43.82C110.323,40.072 112.753,37.512 116.372,37.512C119.915,37.512 122.272,40.072 122.272,43.82C122.272,47.624 119.915,50.222 116.372,50.222ZM116.334,30.869C115.277,30.869 114.267,30.968 113.303,31.146L113.303,38.254L103.958,38.254C103.23,39.902 102.827,41.766 102.827,43.802C102.827,51.465 108.337,56.809 116.334,56.809C124.294,56.809 129.768,51.483 129.768,43.82C129.768,36.194 124.294,30.869 116.334,30.869Z" style="fill:rgb(64,63,65);fill-rule:nonzero;"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@ -18,9 +18,6 @@
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/signin.css" rel="stylesheet">
<!-- static zone info -->
<script src="js/zone.js"></script>
<script src="js/jquery-1.11.2.min.js"></script>
<script>
function getURLparams()
@ -47,7 +44,7 @@
// try to login
$.ajax({
type: "POST",
url: "/api/captiveportal/access/logon/" + zoneid + "/",
url: "/api/captiveportal/access/logon/",
dataType:"json",
data:{ user: $("#inputUsername").val(), password: $("#inputPassword").val() }
}).done(function(data) {
@ -81,7 +78,7 @@
// try to login
$.ajax({
type: "POST",
url: "/api/captiveportal/access/logon/" + zoneid + "/",
url: "/api/captiveportal/access/logon/",
dataType:"json",
data:{ user: '', password: '' }
}).done(function(data) {
@ -114,7 +111,7 @@
// try to login
$.ajax({
type: "POST",
url: "/api/captiveportal/access/logoff/" + zoneid + "/",
url: "/api/captiveportal/access/logoff/",
dataType:"json",
data:{ user: '', password: '' }
}).done(function(data) {
@ -138,7 +135,7 @@
*/
$.ajax({
type: "POST",
url: "/api/captiveportal/access/status/" + zoneid + "/",
url: "/api/captiveportal/access/status/",
dataType:"json",
data:{ user: $("#inputUsername").val(), password: $("#inputPassword").val() }
}).done(function(data) {
@ -163,7 +160,7 @@
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">
<img class="brand-logo" src="images/default-logo.png" height="30" width="150">
<img class="brand-logo" src="images/default-logo.svg" height="30" width="150">
</a>
</div>
</div>

View File

@ -266,14 +266,13 @@ class DB(object):
return result
def update_accounting_info(self, details):
""" update internal accounting database with given ipfw info (not per zone)
:param details: ipfw accounting details
""" update internal accounting database with given pf info (not per zone)
:param details: pf accounting details
"""
if type(details) == dict:
# query registered data
sql = """ select cc.ip_address, cc.zoneid, cc.sessionid
, si.rowid si_rowid, si.prev_packets_in, si.prev_bytes_in
, si.prev_packets_out, si.prev_bytes_out, si.last_accessed
, si.rowid si_rowid, si.last_accessed
from cp_clients cc
left join session_info si on si.zoneid = cc.zoneid and si.sessionid = cc.sessionid
order by cc.ip_address, cc.deleted
@ -291,12 +290,10 @@ class DB(object):
if prev_record['ip_address'] != record['ip_address'] and record['ip_address'] in details:
if record['si_rowid'] is None:
# new session, add info object
sql_new = """ insert into session_info(zoneid, sessionid, prev_packets_in, prev_bytes_in,
prev_packets_out, prev_bytes_out,
packets_in, packets_out, bytes_in, bytes_out,
last_accessed)
values (:zoneid, :sessionid, :packets_in, :bytes_in, :packets_out, :bytes_out,
:packets_in, :packets_out, :bytes_in, :bytes_out, :last_accessed)
sql_new = """ insert into session_info(zoneid, sessionid, packets_in,
packets_out, bytes_in, bytes_out, last_accessed)
values (:zoneid, :sessionid, :packets_in,
:packets_out, :bytes_in, :bytes_out, :last_accessed)
"""
record['packets_in'] = details[record['ip_address']]['in_pkts']
record['bytes_in'] = details[record['ip_address']]['in_bytes']
@ -308,10 +305,6 @@ class DB(object):
# update session
sql_update = """ update session_info
set last_accessed = :last_accessed
, prev_packets_in = :prev_packets_in
, prev_packets_out = :prev_packets_out
, prev_bytes_in = :prev_bytes_in
, prev_bytes_out = :prev_bytes_out
, packets_in = packets_in + :packets_in
, packets_out = packets_out + :packets_out
, bytes_in = bytes_in + :bytes_in
@ -320,27 +313,10 @@ class DB(object):
"""
# add usage to session
record['last_accessed'] = details[record['ip_address']]['last_accessed']
if record['prev_packets_in'] <= details[record['ip_address']]['in_pkts'] and \
record['prev_packets_out'] <= details[record['ip_address']]['out_pkts']:
# ipfw data is still valid, add difference to use
record['packets_in'] = (
details[record['ip_address']]['in_pkts'] - record['prev_packets_in'])
record['packets_out'] = (
details[record['ip_address']]['out_pkts'] - record['prev_packets_out'])
record['bytes_in'] = (details[record['ip_address']]['in_bytes'] - record['prev_bytes_in'])
record['bytes_out'] = (
details[record['ip_address']]['out_bytes'] - record['prev_bytes_out'])
else:
# the data has been reset (reloading rules), add current packet count
record['packets_in'] = details[record['ip_address']]['in_pkts']
record['packets_out'] = details[record['ip_address']]['out_pkts']
record['bytes_in'] = details[record['ip_address']]['in_bytes']
record['bytes_out'] = details[record['ip_address']]['out_bytes']
record['prev_packets_in'] = details[record['ip_address']]['in_pkts']
record['prev_packets_out'] = details[record['ip_address']]['out_pkts']
record['prev_bytes_in'] = details[record['ip_address']]['in_bytes']
record['prev_bytes_out'] = details[record['ip_address']]['out_bytes']
cur2.execute(sql_update, record)
prev_record = record

View File

@ -1,188 +0,0 @@
"""
Copyright (c) 2015-2019 Ad Schellevis <ad@opnsense.org>
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.
"""
import os
import subprocess
class IPFW(object):
def __init__(self):
pass
@staticmethod
def list_table(table_number):
""" list ipfw table
:param table_number: ipfw table number
:return: dict (key value address + rule_number)
"""
devnull = open(os.devnull, 'w')
result = dict()
sp = subprocess.run(['/sbin/ipfw', 'table', str(table_number), 'list'], capture_output=True, text=True)
for line in sp.stdout.split('\n'):
if line.split(' ')[0].strip() != "":
parts = line.split()
address = parts[0]
rulenum = parts[1] if len(parts) > 1 else None
# process / 32 nets as single addresses to align better with the rule syntax
# and local administration.
if address.split('/')[-1] == '32':
# single IPv4 address
result[address.split('/')[0]] = rulenum
elif not line.startswith('-'):
# network
result[address] = rulenum
return result
def ip_or_net_in_table(self, table_number, address):
""" check if address or net is in this zone's table
:param table_number: ipfw table number to query
:param address: ip address or net
:return: boolean
"""
ipfw_tbl = self.list_table(table_number)
if address.strip() in ipfw_tbl:
return True
return False
def add_to_table(self, table_number, address):
""" add/update entry to ipfw table
:param table_number: ipfw table number
:param address: ip address or net to add to table
:return:
"""
ipfw_tbl = self.list_table(table_number)
rule_number = str(self._add_accounting(address))
if address not in ipfw_tbl:
subprocess.run(['/sbin/ipfw', 'table', str(table_number), 'add', address, rule_number], capture_output=True)
elif str(ipfw_tbl[address]) != str(table_number):
# update table when accounting rule mismatches table entry
subprocess.run(['/sbin/ipfw', 'table', str(table_number), 'del', address], capture_output=True)
subprocess.run(['/sbin/ipfw', 'table', str(table_number), 'add', address, rule_number], capture_output=True)
@staticmethod
def delete_from_table(table_number, address):
""" remove entry from ipfw table
:param table_number: ipfw table number
:param address: ip address or net to add to table
:return:
"""
subprocess.run(['/sbin/ipfw', 'table', str(table_number), 'delete', address], capture_output=True)
@staticmethod
def list_accounting_info():
""" list accounting info per ip address, addresses can't overlap in zone's so we just output all we know here
instead of trying to map addresses back to zones.
:return: list accounting info per ip address
"""
result = dict()
sp = subprocess.run(['/sbin/ipfw', '-aT', 'list'], capture_output=True, text=True)
for line in sp.stdout.split('\n'):
parts = line.split()
if len(parts) > 5 and 30000 <= int(parts[0]) <= 50000 and parts[4] == 'count':
line_pkts = int(parts[1])
line_bytes = int(parts[2])
last_accessed = int(parts[3])
if parts[7] != 'any':
ip_address = parts[7]
else:
ip_address = parts[9]
if ip_address not in result:
result[ip_address] = {'rule': int(parts[0]),
'last_accessed': 0,
'in_pkts': 0,
'in_bytes': 0,
'out_pkts': 0,
'out_bytes': 0
}
result[ip_address]['last_accessed'] = max(result[ip_address]['last_accessed'],
last_accessed)
if parts[7] != 'any':
# count input
result[ip_address]['in_pkts'] = line_pkts
result[ip_address]['in_bytes'] = line_bytes
else:
# count output
result[ip_address]['out_pkts'] = line_pkts
result[ip_address]['out_bytes'] = line_bytes
return result
def _add_accounting(self, address):
""" add ip address for accounting
:param address: ip address
:return: added or known rule number
"""
# search for unused rule number
acc_info = self.list_accounting_info()
if address not in acc_info:
rule_ids = list()
for ip_address in acc_info:
if acc_info[ip_address]['rule'] not in rule_ids:
rule_ids.append(acc_info[ip_address]['rule'])
new_rule_id = -1
for ruleId in range(30000, 50000):
if ruleId not in rule_ids:
new_rule_id = ruleId
break
# add accounting rule
if new_rule_id != -1:
subprocess.run(['/sbin/ipfw', 'add', str(new_rule_id), 'count', 'ip', 'from', address, 'to', 'any'],
capture_output=True)
subprocess.run(['/sbin/ipfw', 'add', str(new_rule_id), 'count', 'ip', 'from', 'any', 'to', address],
capture_output=True)
# end of accounting block lives at rule number 50000
subprocess.run(
['/sbin/ipfw', 'add', str(new_rule_id), 'skipto', '60000', 'ip', 'from', 'any', 'to', 'any'],
capture_output=True
)
return new_rule_id
else:
return acc_info[address]['rule']
def _del_accounting(self, address):
""" remove ip address from accounting rules
:param address: ip address
:return: None
"""
acc_info = self.list_accounting_info()
if address in acc_info:
subprocess.run(['/sbin/ipfw', 'delete', str(acc_info[address]['rule'])], capture_output=True)
def delete(self, table_number, address):
""" remove entry from both ipfw table and accounting rules
:param table_number: ipfw table number
:param address: ip address or net to add to table
:return:
"""
self.delete_from_table(table_number, address)
self._del_accounting(address)

View File

@ -0,0 +1,101 @@
"""
Copyright (c) 2025 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.
"""
import subprocess
import tempfile
import time
class PF(object):
def __init__(self):
pass
@staticmethod
def list_table(zoneid):
pfctl_cmd = ['/sbin/pfctl', '-t', f'__captiveportal_zone_{zoneid}', '-T', 'show']
for line in subprocess.run(pfctl_cmd, capture_output=True, text=True).stdout.split('\n'):
# split('\n') on an empty string will return an empty string, we need to make sure to suppress these
tmp = line.strip()
if len(tmp) > 0:
yield tmp
@staticmethod
def add_to_table(zoneid, address):
subprocess.run(['/sbin/pfctl', '-t', f'__captiveportal_zone_{zoneid}', '-T', 'add', address])
@staticmethod
def remove_from_table(zoneid, address):
subprocess.run(['/sbin/pfctl', '-t', f'__captiveportal_zone_{zoneid}', '-T', 'del', address])
# kill associated states to and from this host
subprocess.run(['/sbin/pfctl', '-k', f'{address}'])
subprocess.run(['/sbin/pfctl', '-k', '0.0.0.0/0', '-k', f'{address}'])
@staticmethod
def sync_accounting(zoneid):
rules = ''
for entry in PF.list_table(zoneid):
rules += f'ether pass in quick proto {{ 0x0800 }} l3 from {entry} to any label "{entry}-in"\n'
rules += f'ether pass out quick proto {{ 0x0800 }} l3 from any to {entry} label "{entry}-out"\n'
with tempfile.NamedTemporaryFile(mode="w", delete=True) as tmp_file:
tmp_file.write(rules)
tmp_file.flush()
subprocess.run(
['/sbin/pfctl', '-a', f'captiveportal_zone_{zoneid}', '-f', tmp_file.name],
text=True,
capture_output=True
)
@staticmethod
def list_accounting_info(zoneid):
sp = subprocess.run(['/sbin/pfctl', '-a', f'captiveportal_zone_{zoneid}', '-vvse'], capture_output=True, text=True)
results = {}
stats = {}
prev_line = ''
for line in sp.stdout.split('\n'):
line = line.strip()
if not line or line[0] != '[':
if prev_line.find(' label ') > -1:
lbl = prev_line.split(' label ')[-1]
if '"' in lbl and lbl.count('"') >= 2:
ip, out_flag = lbl.split('"')[1].split('-')
out = (out_flag == 'out')
stats_key = ('out' if out else 'in')
results.setdefault(ip, {'in_pkts': 0, 'in_bytes': 0, 'out_pkts': 0, 'out_bytes': 0, 'last_accessed': None})
results[ip][f'{stats_key}_pkts'] += stats.get('packets', 0)
results[ip][f'{stats_key}_bytes'] += stats.get('bytes', 0)
results[ip]['last_accessed'] = stats.get('last_accessed', 0)
prev_line = line
elif line[0] == '[' and line.find('Evaluations') > 0:
parts = line.strip('[ ]').replace(':', ' ').split()
stats.update({parts[i].lower(): int(parts[i+1]) for i in range(0, len(parts)-1, 2) if parts[i+1].isdigit()})
elif line[0] == '[' and line.find('Last Active Time') > 0:
date_str = line.strip('[ ]').split('Time:')[1].strip()
if date_str != 'N/A':
stats.update({'last_accessed': int(time.mktime(time.strptime(date_str, "%a %b %d %H:%M:%S %Y")))})
return results

View File

@ -55,10 +55,5 @@ if len(sys.argv) > 1:
with open(target_filename, 'wb') as f_out:
f_out.write(zf_in.read(zf_info.filename))
os.chmod(target_filename, 0o444)
# write zone settings
filename = '%sjs/zone.js' % target_directory
with open(filename, 'wb') as f_out:
f_out.write(('var zoneid = %s' % zoneid).encode())
os.chmod(filename, 0o444)
sys.exit(0)

View File

@ -104,6 +104,7 @@ $SERVER["socket"] == "[::]:{{ cp_zone_item.zoneid|int + 9000 }}" {
ssl.engine = "disable"
}
setenv.set-request-header = ("zoneid" => "{{cp_zone_item.zoneid}}")
proxy.server = ( "/api/captiveportal/access/" => (
( "host" => "127.0.0.1",
"port" => 8999 )
@ -168,7 +169,7 @@ ssl.engine = "disable"
#### compress module
deflate.cache-dir = "/tmp/"
deflate.mimetypes = ("text/plain", "text/html", "text/css", "image/png")
deflate.mimetypes = ("text/plain", "text/html", "text/css", "image/png", "image/svg+xml")
#### expire module
expire.url = ( "" => "access plus 6 hours")
@ -214,6 +215,7 @@ mimetype.assign = (
".jpg" => "image/jpeg",
".jpeg" => "image/jpeg",
".png" => "image/png",
".svg" => "image/svg+xml",
".xbm" => "image/x-xbitmap",
".xpm" => "image/x-xpixmap",
".xwd" => "image/x-xwindowdump",

View File

@ -1,31 +1,3 @@
{# Macro import #}
{% from 'OPNsense/IPFW/rules.macro' import convert_address %}
{# collect interfaces list (with / without captive portal enabled) #}
{% set cp_interface_list = [] %}
{% set no_cp_interface_list = [] %}
{% if helpers.exists('OPNsense.captiveportal.zones.zone') %}
{% for intf_key,interface in interfaces.items()%}
{% set is_cp=[] %}
{% for cp_item in helpers.toList('OPNsense.captiveportal.zones.zone') %}
{% for cp_intf in cp_item.interfaces.split(',') %}
{% if intf_key == cp_intf %}
{% if cp_item.enabled|default('0') == '1' %}
{% do cp_interface_list.append({'zone':cp_item.description, 'zoneid':cp_item.zoneid,'if':interface.if, 'obj':cp_item}) %}
{% do is_cp.append(1) %}
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
{% if not is_cp%}
{% do no_cp_interface_list.append(interface) %}
{% endif %}
{% endfor %}
{% else %}
{% for intf_key,interface in interfaces.items() %}
{% do no_cp_interface_list.append(interface) %}
{% endfor %}
{% endif %}
#======================================================================================
# flush ruleset
#======================================================================================
@ -98,62 +70,6 @@ add 201 skipto 60000 ipv4 from 127.0.0.0/8 to any
add 202 skipto 60000 ipv6 from any to ::1
add 203 skipto 60000 ipv4 from any to 127.0.0.0/8
#======================================================================================
# Allow traffic to this host
#======================================================================================
{% for item in cp_interface_list %}
add {{loop.index + 1000}} skipto 60000 udp from any to me dst-port 53 via {{item.if}} keep-state
add {{loop.index + 1000}} skipto 60000 ip from any to { 255.255.255.255 or me } in via {{item.if}}
add {{loop.index + 1000}} skipto 60000 ip from { 255.255.255.255 or me } to any out via {{item.if}}
add {{loop.index + 1000}} skipto 60000 icmp from { 255.255.255.255 or me } to any out via {{item.if}} icmptypes 0
add {{loop.index + 1000}} skipto 60000 icmp from any to { 255.255.255.255 or me } in via {{item.if}} icmptypes 8
{% endfor %}
{% for item in cp_interface_list %}
#===================================================================================
# zone {{item.zone}} ({{item.zoneid}}) / {{item.if}} configuration
#===================================================================================
{# authenticated clients #}
add {{3000 + item.zoneid|int }} skipto tablearg ip from table({{item.zoneid|int}}) to any via {{item.if}}
add {{3000 + item.zoneid|int }} skipto tablearg ip from any to table({{item.zoneid|int}}) via {{item.if}}
# Allowed traffic heading into this zone #
{% if item.obj.interfaces_inbound|default('') != '' %}
{% for inbound_if in item.obj.interfaces_inbound.split(',') if helpers.physical_interface(inbound_if)%}
add {{3000 + item.zoneid|int }} skipto 60000 ip from any to any recv {{helpers.physical_interface(inbound_if)}} xmit {{item.if}} keep-state
{% endfor %}
{% endif %}
{% endfor %}
#======================================================================================
# redirect non-authenticated clients to captive portal @ local port 8000 + zoneid
#======================================================================================
{% for item in cp_interface_list %}
add {{5000 + item.zoneid|int }} fwd 127.0.0.1,{{ item.zoneid|int + 8000 }} tcp from any to any dst-port 443 in via {{item.if}}
add {{5000 + item.zoneid|int }} allow ip from any to any dst-port 443 via {{item.if}}
add {{5000 + item.zoneid|int }} fwd 127.0.0.1,{{ item.zoneid|int + 9000 }} tcp from any to any dst-port 80 in via {{item.if}}
add {{5000 + item.zoneid|int }} allow ip from any to any dst-port 80 via {{item.if}}
{% endfor %}
#======================================================================================
# accept traffic from all interfaces not used by captive portal
#======================================================================================
# let the responses from the captive portal web server back out
add 6000 skipto 60000 tcp from any to any out
# forward unauthorized traffic from captiveportal interfaces to block rule
{% for item in cp_interface_list %}
add {{6001 + loop.index }} skipto 65534 all from any to any via {{item.if}}
{% endfor %}
# send all the rest to the traffic shaper rules
add 6199 skipto 60000 all from any to any
#======================================================================================
# 30000 .... 49999 reserved for captive portal accounting rules
#======================================================================================
#======================================================================================
# traffic shaping section, authorized traffic
#======================================================================================