feat(dhcp): dhcp configuration

limit to 300 vlans because of freeRadius limitation
This commit is contained in:
catvayor 2024-05-13 18:03:00 +02:00
parent f9250e8886
commit e9c5489bc2
6 changed files with 571 additions and 23 deletions

View file

@ -1,4 +1,9 @@
{ config, lib, ... }:
{
config,
lib,
pkgs,
...
}:
{
imports = [ ./module.nix ];
@ -52,6 +57,26 @@
);
radiusClients = { };
extra-mods = {
dhcp_sql = import ./mod-dhcp_sql.nix {
inherit pkgs;
vlans = import ../user_vlans.nix;
};
dhcp_sqlippool = ./mod-dhcp_sqlippool;
};
extra-sites = {
dhcp = import ./site-dhcp.nix {
inherit pkgs;
vlans = import ../user_vlans.nix;
};
};
dictionary = {
Client-Vlan = "integer";
Server-IP = "ipaddr";
Broadcast-IP = "ipaddr";
};
checkConfiguration = true;
};
age-secrets.autoMatch = [ "radius" ];

View file

@ -0,0 +1,101 @@
{ pkgs, vlans }:
let
mkVlan =
{
vlan,
prefix24nb,
prefix27nb,
...
}:
let
mkIp =
idx:
let
id = 256 * prefix24nb + prefix27nb + 2 + idx;
in
"(${toString id}, 'pool-${toString vlan}', '10.0.${toString prefix24nb}.${
toString (prefix27nb + 2 + idx)
}', 1)";
ipList = builtins.genList mkIp 29;
in
''
INSERT INTO dhcpippool (id, pool_name, framedipaddress, status_id) VALUES
${builtins.concatStringsSep ", " ipList};
'';
in
pkgs.writeText "dhcp-schema.sql" ''
-----------------------------------------------------------------------------
-- $Id: 54a9abbf01d4161cadb304cdd3755856c6f15442 $ --
-- --
-- schema.sql rlm_sql - FreeRADIUS SQLite Module --
-- --
-- Database schema for SQLite rlm_sql module for DHCP --
-- --
-----------------------------------------------------------------------------
--
-- Table structure for table 'dhcpgroupreply'
--
CREATE TABLE dhcpgroupreply (
id INTEGER PRIMARY KEY AUTOINCREMENT,
groupname varchar(64) NOT NULL default ''',
attribute varchar(64) NOT NULL default ''',
op char(2) NOT NULL DEFAULT '=',
value varchar(253) NOT NULL default ''',
context varchar(16) NOT NULL default '''
);
CREATE INDEX dhcpgroupreply_groupname ON dhcpgroupreply(context,groupname);
--
-- Table structure for table 'dhcpreply'
--
CREATE TABLE dhcpreply (
id INTEGER PRIMARY KEY AUTOINCREMENT,
identifier varchar(253) NOT NULL default ''',
attribute varchar(64) NOT NULL default ''',
op char(2) NOT NULL DEFAULT '=',
value varchar(253) NOT NULL default ''',
context varchar(16) NOT NULL default '''
);
CREATE INDEX dhcpreply_identifier ON dhcpreply(context,identifier);
--
-- Table structure for table 'dhcpgroup'
--
CREATE TABLE dhcpgroup (
id INTEGER PRIMARY KEY AUTOINCREMENT,
identifier varchar(253) NOT NULL default ''',
groupname varchar(64) NOT NULL default ''',
priority int(11) NOT NULL default '1',
context varchar(16) NOT NULL default '''
);
CREATE INDEX dhcpgroup_identifier ON dhcpgroup(context,identifier);
--
-- Table structure for table 'dhcpippool'
--
CREATE TABLE dhcpstatus (
status_id int PRIMARY KEY,
status varchar(10) NOT NULL
);
INSERT INTO dhcpstatus (status_id, status) VALUES (1, 'dynamic'), (2, 'static'), (3, 'declined'), (4, 'disabled');
CREATE TABLE dhcpippool (
id int(11) PRIMARY KEY,
pool_name varchar(30) NOT NULL,
framedipaddress varchar(15) NOT NULL,
pool_key varchar(30) NOT NULL default ''',
gateway varchar(15) NOT NULL default ''',
expiry_time DATETIME NOT NULL default (DATETIME('now')),
status_id int NOT NULL default 1,
counter int NOT NULL default 0,
FOREIGN KEY(status_id) REFERENCES dhcpstatus(status_id)
);
CREATE INDEX dhcpippool_poolname_expire ON dhcpippool(pool_name, expiry_time);
CREATE INDEX dhcpippool_framedipaddress ON dhcpippool(framedipaddress);
CREATE INDEX dhcpippool_poolname_poolkey_ipaddress ON dhcpippool(pool_name, pool_key, framedipaddress);
${builtins.concatStringsSep "\n" (map mkVlan vlans)}
''

View file

@ -0,0 +1,83 @@
{ pkgs, ... }@args:
pkgs.writeText "mod-dhcp_sql" ''
sql dhcp_sql {
dialect = "sqlite"
driver = "rlm_sql_''${dialect}"
sqlite {
filename = "/tmp/freeradius.db"
busy_timeout = 200
bootstrap = "${import ./dhcp-sqlsquema.nix args}"
}
radius_db = "radius"
read_groups = no
pool {
start = ''${thread[pool].start_servers}
min = ''${thread[pool].min_spare_servers}
max = ''${thread[pool].max_servers}
spare = ''${thread[pool].max_spare_servers}
uses = 0
retry_delay = 30
lifetime = 0
idle_timeout = 60
}
group_attribute = "''${.:instance}-SQL-Group"
# -*- text -*-
#
# dhcp/sqlite/queries.conf -- SQLite configuration for DHCP schema (schema.sql)
#
# $Id: 0cc720220d237d98934dd23173ccb4e09bd0cb01 $
# Safe characters list for sql queries. Everything else is replaced
# with their mime-encoded equivalents.
# The default list should be ok
# safe_characters = "@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_: /"
#######################################################################
# Query config: Identifier
#######################################################################
# This is the identifier that will get substituted, escaped, and added
# as attribute 'SQL-User-Name'. '%{SQL-User-Name}' should be used
# below everywhere an identifier substitution is needed so you you can
# be sure the identifier passed from the client is escaped properly.
#
sql_user_name = "%{control:DHCP-SQL-Option-Identifier}"
#######################################################################
# Attribute Lookup Queries
#######################################################################
# These queries setup the reply items in ''${dhcpreply_table} and
# ''${group_reply_query}. You can use any query/tables you want, but
# the return data for each row MUST be in the following order:
#
# 0. Row ID (currently unused)
# 1. Identifier
# 2. Item Attr Name
# 3. Item Attr Value
# 4. Item Attr Operation
#######################################################################
authorize_reply_query = "\
SELECT id, identifier, attribute, value, op \
FROM dhcpreply \
WHERE identifier = '%{SQL-User-Name}' AND context = '%{control:DHCP-SQL-Option-Context}' \
ORDER BY id"
authorize_group_reply_query = "\
SELECT id, groupname, attribute, value, op \
FROM dhcpgroupreply \
WHERE groupname = '%{''${group_attribute}}' AND context = '%{control:DHCP-SQL-Option-Context}' \
ORDER BY id"
group_membership_query = "\
SELECT groupname \
FROM dhcpgroup \
WHERE identifier='%{SQL-User-Name}' AND context = '%{control:DHCP-SQL-Option-Context}' \
ORDER BY priority"
}
''

View file

@ -0,0 +1,329 @@
# Configuration for DHCP for the SQL based IP Pools module (rlm_sqlippool).
#
# See raddb/mods-available/sqlippool for common configuration explanation
#
# See raddb/policy.d/dhcp_sqlippool for the "glue" code that allows
# the RADIUS based "sqlippool" module to be used for DHCP.
#
# See raddb/sites-available/dhcp for instructions on how to configure
# the DHCP server.
#
# The database schemas are available at:
#
# raddb/mods-config/sql/ippool-dhcp/<DB>/schema.sql
#
# $Id: 909b93c7ebcbbeb16b123ca38e696790b5771dda $
sqlippool dhcp_sqlippool {
# SQL instance to use (from mods-available/sql)
#
# If you have multiple sql instances, such as "sql sql1 {...}",
# use the *instance* name here: sql1.
sql_module_instance = "dhcp_sql"
# This is duplicative of info available in the SQL module, but
# we have to list it here as we do not yet support nested
# reference expansions.
dialect = "mysql"
# The duration for which a lease is reserved whilst under offer
offer_duration = 10
# IP lease duration. (Leases expire even if no DHCP-Release packet is received)
# Either use the value to be sent to the client or a hard coded one.
#lease_duration = "%{reply:DHCP-IP-Address-Lease-Time}"
lease_duration = 7200
# The attribute in which the IP address is returned in the reply
attribute_name = "DHCP-Your-IP-Address"
# Assign the IP address, even if the above attribute already exists in
# the reply.
#
# allow_duplicates = no
# The attribute in which an IP address hint may be supplied
req_attribute_name = "DHCP-Requested-IP-Address"
#
# RFC 2132 allows the DHCP client to supply a unique
# identifier ("uid") using Option 61 (DHCP-Client-Identifier)
# in which case it must be used as the lookup key for
# configuration data.
#
pool_key = "%{%{DHCP-Client-Identifier}:-%{DHCP-Client-Hardware-Address}}"
#
# The "uid" is generated by the OS which means that clients
# whose BMC piggybacks on the main interface (sharing its MAC,
# but generating a distinct uid) and dual-booting clients can
# be allocated multiple IPs, consuming more pool entries. To
# avoid this you can ignore the RFCs and key the configuration
# data based only on the client MAC address.
#
# pool_key = "%{DHCP-Client-Hardware-Address}"
################################################################
#
# WARNING: MySQL (MyISAM) has certain limitations that means it can
# hand out the same IP address to 2 different users.
#
# We suggest using an SQL DB with proper transaction
# support, such as PostgreSQL, or using MySQL
# with InnoDB.
#
################################################################
# These messages are added to the "control" items, as
# Module-Success-Message. They are not logged anywhere else,
# unlike previous versions. If you want to have them logged
# to a file, see the "linelog" module, and create an entry
# which writes Module-Success-Message message.
#
messages {
exists = "DHCP: Existing IP: %{reply:${..attribute_name}} (cid %{DHCP-Client-Identifier} chaddr %{DHCP-Client-Hardware-Address} giaddr %{DHCP-Gateway-IP-Address})"
success = "DHCP: Allocated IP: %{reply:${..attribute_name}} from %{control:Pool-Name} (cid %{DHCP-Client-Identifier} chaddr %{DHCP-Client-Hardware-Address} giaddr %{DHCP-Gateway-IP-Address})"
clear = "DHCP: Released IP %{DHCP-Client-IP-Address} (cid %{DHCP-Client-Identifier} chaddr %{DHCP-Client-Hardware-Address} giaddr %{DHCP-Gateway-IP-Address})"
failed = "DHCP: IP Allocation FAILED from %{control:Pool-Name} (cid %{DHCP-Client-Identifier} chaddr %{DHCP-Client-Hardware-Address} giaddr %{DHCP-Gateway-IP-Address})"
nopool = "DHCP: No Pool-Name defined (cid %{DHCP-Client-Identifier} chaddr %{DHCP-Client-Hardware-Address} giaddr %{DHCP-Gateway-IP-Address})"
}
# -*- text -*-
#
# ippool-dhcp/sqlite/queries.conf -- SQLite queries for rlm_sqlippool
#
# $Id: d99e09bfc8559eaf5584c32fb6a94c99e689fee3 $
# *****************
# * DHCP DISCOVER *
# *****************
#
# SQLite does not implement SELECT FOR UPDATE which is normally used to place
# an exclusive lock over rows to prevent the same address from being
# concurrently selected for allocation to multiple users.
#
# The most granular read-blocking lock that SQLite has is an exclusive lock
# over the database, so that's what we use. All locking in SQLite is performed
# over the entire database and we perform a row update for any IP that we
# allocate, requiring an exclusive lock. Taking the exclusive lock from the
# start of the transaction (even if it were not required to guard the SELECT)
# is actually quicker than if we deferred it causing SQLite to "upgrade" the
# automatic shared lock for the transaction to an exclusive lock for the
# subsequent UPDATE.
#
allocate_begin = "BEGIN EXCLUSIVE"
allocate_commit = "COMMIT"
#
# Attempt to find the most recent existing IP address for the client
#
allocate_existing = "\
SELECT framedipaddress \
FROM dhcpippool \
JOIN dhcpstatus \
ON dhcpippool.status_id = dhcpstatus.status_id \
WHERE pool_name = '%{control:Pool-Name}' \
AND pool_key = '${pool_key}' \
AND status IN ('dynamic', 'static') \
ORDER BY expiry_time DESC \
LIMIT 1"
#
# Determine whether the requested IP address is available
#
allocate_requested = "\
SELECT framedipaddress \
FROM dhcpippool \
JOIN dhcpstatus \
ON dhcpippool.status_id = dhcpstatus.status_id \
WHERE pool_name = '%{control:Pool-Name}' \
AND framedipaddress = '%{%{${req_attribute_name}}:-0.0.0.0}' \
AND status = 'dynamic' \
AND expiry_time < datetime('now')"
#
# If the existing address can't be found this query will be run to
# find a free address
#
#allocate_find = "\
# SELECT framedipaddress \
# FROM dhcpippool \
# JOIN dhcpstatus \
# ON dhcpippool.status_id = dhcpstatus.status_id \
# WHERE pool_name = '%{control:Pool-Name}' \
# AND expiry_time < datetime('now') \
# AND status = 'dynamic' \
# ORDER BY expiry_time LIMIT 1"
#
# This series of queries allocates an IP address
#
# Either pull the most recent allocated IP for this client or the
# oldest expired one. The first sub query returns the most recent
# lease for the client (if there is one), the second returns the
# oldest expired one.
# Sorting the result by expiry_time DESC will return the client specific
# IP if it exists, otherwise an expired one.
#
allocate_find = "\
SELECT framedipaddress, 1 AS o \
FROM ( \
SELECT framedipaddress \
FROM dhcpippool \
JOIN dhcpstatus \
ON dhcpippool.status_id = dhcpstatus.status_id \
WHERE pool_name = '%{control:Pool-Name}' \
AND pool_key = '${pool_key}' \
AND status IN ('dynamic', 'static') \
ORDER BY expiry_time DESC \
LIMIT 1 \
) UNION \
SELECT framedipaddress, 2 AS o \
FROM ( \
SELECT framedipaddress \
FROM dhcpippool \
JOIN dhcpstatus \
ON dhcpippool.status_id = dhcpstatus.status_id \
WHERE pool_name = '%{control:Pool-Name}' \
AND framedipaddress = '%{%{${req_attribute_name}}:-0.0.0.0}' \
AND status = 'dynamic' \
AND ( pool_key = '${pool_key}' OR expiry_time < datetime('now') ) \
) UNION \
SELECT framedipaddress, 3 AS o \
FROM ( \
SELECT framedipaddress \
FROM dhcpippool \
JOIN dhcpstatus \
ON dhcpippool.status_id = dhcpstatus.status_id \
WHERE pool_name = '%{control:Pool-Name}' \
AND expiry_time < datetime('now') \
AND status = 'dynamic' \
ORDER BY expiry_time LIMIT 1 \
) \
ORDER BY o \
LIMIT 1"
#
# If you prefer to allocate a random IP address every time, i
# use this query instead
# Note: This is very slow if you have a lot of free IPs.
#
#allocate_find = "\
# SELECT framedipaddress \
# FROM dhcpippool \
# JOIN dhcpstatus \
# ON dhcpippool.status_id = dhcpstatus.status_id \
# WHERE pool_name = '%{control:Pool-Name}' \
# AND expiry_time < datetime('now') \
# AND status = 'dynamic' \
# ORDER BY RAND() \
#
# If an IP could not be allocated, check to see if the pool exists or not
# This allows the module to differentiate between a full pool and no pool
# Note: If you are not running redundant pool modules this query may be
# commented out to save running this query every time an ip is not allocated.
#
pool_check = "\
SELECT id \
FROM dhcpippool \
WHERE pool_name='%{control:Pool-Name}' \
LIMIT 1"
#
# This is the final IP Allocation query, which saves the allocated ip details
#
allocate_update = "\
UPDATE dhcpippool \
SET \
gateway = '%{DHCP-Gateway-IP-Address}', \
pool_key = '${pool_key}', \
expiry_time = datetime(strftime('%%s', 'now') + ${offer_duration}, 'unixepoch') \
WHERE framedipaddress = '%I'"
# ****************
# * DHCP REQUEST *
# ****************
#
# This query revokes any active offers for addresses that a client is not
# requesting when a DHCP REQUEST packet arrives
#
start_update = "\
UPDATE dhcpippool \
SET \
gateway = ''', \
pool_key = ''', \
expiry_time = datetime('now') \
WHERE pool_name = '%{control:Pool-Name}' \
AND pool_key = '${pool_key}' \
AND framedipaddress <> '%{DHCP-Requested-IP-Address}' \
AND expiry_time > datetime('now') \
AND dhcpippool.status_id IN \
(SELECT status_id FROM dhcpstatus WHERE status = 'dynamic')"
#
# This query extends an existing lease (or offer) when a DHCP REQUEST packet
# arrives. This query must update a row when a lease is succesfully requested
# - queries that update no rows will result in a "notfound" response to
# the module which by default will give a DHCP-NAK reply. In this example
# incrementing "counter" is used to achieve this.
#
alive_update = "\
UPDATE dhcpippool \
SET \
expiry_time = datetime(strftime('%%s', 'now') + ${lease_duration}, 'unixepoch'), \
counter = counter + 1 \
WHERE pool_name = '%{control:Pool-Name}' \
AND pool_key = '${pool_key}' \
AND framedipaddress = '%{%{DHCP-Requested-IP-Address}:-%{DHCP-Client-IP-Address}}'"
# ****************
# * DHCP RELEASE *
# ****************
#
# This query frees an IP address when a DHCP RELEASE packet arrives
#
stop_clear = "\
UPDATE dhcpippool \
SET \
gateway = ''', \
pool_key = ''', \
expiry_time = datetime('now') \
WHERE pool_name = '%{control:Pool-Name}' \
AND pool_key = '${pool_key}' \
AND framedipaddress = '%{DHCP-Client-IP-Address}' \
AND dhcpippool.status_id IN \
(SELECT status_id FROM dhcpstatus WHERE status = 'dynamic')"
#
# This query is not applicable to DHCP
#
on_clear = ""
# ****************
# * DHCP DECLINE *
# ****************
#
# This query marks an IP address as declined when a DHCP Decline
# packet arrives
#
off_clear = "\
UPDATE dhcpippool \
SET status_id = (SELECT status_id FROM dhcpstatus WHERE status = 'declined') \
WHERE pool_name = '%{control:Pool-Name}' \
AND pool_key = '${pool_key}' \
AND framedipaddress = '%{DHCP-Requested-IP-Address}'"
}

View file

@ -1,28 +1,38 @@
{ pkgs, vlans }:
let
listen = vlan: ''
listen =
{
vlan,
servIP,
broadIP,
interfaceName,
...
}:
''
listen {
type = dhcp
ipaddr = 10.0.0.1
src_ipaddr = 10.0.0.1
ipaddr = ${servIP}
src_ipaddr = ${servIP}
port = 67
interface = vlan-user-${vlan}
interface = ${interfaceName}
broadcast = no #?
performance {
skip_duplicate_checks = no
}
# we store servIP so that latter modules can know with wich IP reply
update control {
&Client-Vlan = ${vlan}
&Client-Vlan = ${toString vlan}
&Server-IP = ${servIP}
&Broadcast-IP = ${broadIP}
}
}
'';
dhcpCommon = ''
update reply {
&DHCP-Domain-Name-Server = 10.0.0.1
&DHCP-Subnet-Mask = 255.255.128.0 # /17 ?????????
&DHCP-Subnet-Mask = 255.255.255.224
&DHCP-Router-Address = &control:Server-IP
&DHCP-Broadcast-Address = 10.0.127.255 # ???????
&DHCP-IP-Address-Lease-Time = 7200
&DHCP-Broadcast-Address = &control:Broadcast-IP
&DHCP-DHCP-Server-Identifier = 10.0.0.1
}
'';
@ -57,10 +67,10 @@ let
}
'';
in
''
pkgs.writeText "site-dhcp" ''
server dhcp {
${builtins.concatStringsSep "\n\n" (map listen [ ])}
${builtins.concatStringsSep "\n\n" (map listen vlans)}
${dhcpDiscover}

View file

@ -11,4 +11,4 @@ let
interfaceName = "vlan-user-${toString vlan}";
};
in
builtins.genList mkUserVlan 850
builtins.genList mkUserVlan 300 # 850