Services: Kea: DHCPv4: allow sending any DHCP option as raw hex or string payload (#9958)

This uses csv-false to force kea to send option data as hexadecimal value, instead of enforcing types on them.

This means theoretically you can now send any byte coded option out, meaning the user can construct whatever value they need. This also means encapsulated options like 43 can be sent in the format any vendor might require, as binary that is.

There is also another possibility, a very specific format of data can automatically convert strings into hex (bytes), kea handles this conversion internally. "data": "'convert this text to binary'"
This commit is contained in:
Monviech 2026-03-16 11:47:47 +01:00 committed by GitHub
parent c0d5331e1f
commit 8350fcb73b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 330 additions and 0 deletions

3
plist
View file

@ -410,6 +410,7 @@
/usr/local/opnsense/mvc/app/controllers/OPNsense/Kea/DhcpController.php
/usr/local/opnsense/mvc/app/controllers/OPNsense/Kea/forms/agentSettings.xml
/usr/local/opnsense/mvc/app/controllers/OPNsense/Kea/forms/ddnsSettings.xml
/usr/local/opnsense/mvc/app/controllers/OPNsense/Kea/forms/dialogOption4.xml
/usr/local/opnsense/mvc/app/controllers/OPNsense/Kea/forms/dialogPDPool6.xml
/usr/local/opnsense/mvc/app/controllers/OPNsense/Kea/forms/dialogPeer4.xml
/usr/local/opnsense/mvc/app/controllers/OPNsense/Kea/forms/dialogPeer6.xml
@ -838,6 +839,7 @@
/usr/local/opnsense/mvc/app/models/OPNsense/Interfaces/VxLan.xml
/usr/local/opnsense/mvc/app/models/OPNsense/Kea/ACL/ACL.xml
/usr/local/opnsense/mvc/app/models/OPNsense/Kea/FieldTypes/KeaClasslessStaticRouteField.php
/usr/local/opnsense/mvc/app/models/OPNsense/Kea/FieldTypes/KeaOptionDataField.php
/usr/local/opnsense/mvc/app/models/OPNsense/Kea/FieldTypes/KeaPoolsField.php
/usr/local/opnsense/mvc/app/models/OPNsense/Kea/FieldTypes/KeaStaticRoutesField.php
/usr/local/opnsense/mvc/app/models/OPNsense/Kea/KeaCtrlAgent.php
@ -1294,6 +1296,7 @@
/usr/local/opnsense/scripts/ipsec/spddelete.py
/usr/local/opnsense/scripts/ipsec/updown_event.py
/usr/local/opnsense/scripts/kea/get_kea_leases.py
/usr/local/opnsense/scripts/kea/kea_dhcp_options.py
/usr/local/opnsense/scripts/kea/kea_prefix_watcher.py
/usr/local/opnsense/scripts/monit/carp_status.php
/usr/local/opnsense/scripts/monit/gateway_alert.php

View file

@ -137,6 +137,31 @@ class Dhcpv4Controller extends ApiMutableModelControllerBase
}
}
public function searchOptionAction()
{
return $this->searchBase("options.option", null, "option");
}
public function setOptionAction($uuid)
{
return $this->setBase("option", "options.option", $uuid);
}
public function addOptionAction()
{
return $this->addBase("option", "options.option");
}
public function getOptionAction($uuid = null)
{
return $this->getBase("option", "options.option", $uuid);
}
public function delOptionAction($uuid)
{
return $this->delBase("options.option", $uuid);
}
public function searchPeerAction()
{
return $this->searchBase("ha_peers.peer", null, "name");

View file

@ -63,6 +63,9 @@ class DhcpController extends \OPNsense\Base\IndexController
$this->view->formDialogReservation = $this->getForm("dialogReservation4");
$this->view->formGridReservation = $this->getFormGrid("dialogReservation4", 'reservation', null, 'reservation');
$this->view->formDialogOption = $this->getForm("dialogOption4");
$this->view->formGridOption = $this->getFormGrid("dialogOption4", 'option', null, 'option');
$this->view->formDialogPeer = $this->getForm("dialogPeer4");
$this->view->formGridPeer = $this->getFormGrid("dialogPeer4", 'peer');
}

View file

@ -0,0 +1,37 @@
<form>
<field>
<id>option.code</id>
<label>Code</label>
<type>dropdown</type>
<help>DHCPv4 option to offer to the client.</help>
</field>
<field>
<id>option.encoding</id>
<label>Encoding</label>
<type>dropdown</type>
<help>Choose between auto-converting string data to binary, or providing hexadecimal data yourself. For encapsulated and other complex options, constructing your own binary payload can be a requirement.</help>
</field>
<field>
<id>option.data</id>
<label>Data</label>
<type>text</type>
<help>Payload to send to a client.</help>
</field>
<field>
<id>option.force</id>
<label>Force</label>
<type>checkbox</type>
<help>Always send the option, also when the client does not ask for it in the parameter request list.</help>
<grid_view>
<type>boolean</type>
<formatter>boolean</formatter>
<visible>false</visible>
</grid_view>
</field>
<field>
<id>option.description</id>
<label>Description</label>
<type>text</type>
<help>You may enter a description here for your reference.</help>
</field>
</form>

View file

@ -143,4 +143,13 @@
<visible>false</visible>
</grid_view>
</field>
<field>
<id>reservation.option</id>
<label>Options</label>
<type>select_multiple</type>
<help>Select custom DHCPv4 options that were created in the options tab.</help>
<grid_view>
<visible>false</visible>
</grid_view>
</field>
</form>

View file

@ -173,6 +173,15 @@
</grid_view>
<advanced>true</advanced>
</field>
<field>
<id>subnet4.option</id>
<label>Options</label>
<type>select_multiple</type>
<help>Select custom DHCPv4 options that were created in the options tab.</help>
<grid_view>
<visible>false</visible>
</grid_view>
</field>
<field>
<type>header</type>
<label>Dynamic DNS</label>

View file

@ -0,0 +1,67 @@
<?php
/*
* Copyright (C) 2026 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\Kea\FieldTypes;
use OPNsense\Base\FieldTypes\BaseField;
use OPNsense\Base\Validators\CallbackValidator;
class KeaOptionDataField extends BaseField
{
protected $internalIsContainer = false;
protected $internalValidationMessage = "Invalid option data";
public function getValidators()
{
$validators = parent::getValidators();
if (!empty($this->internalValue)) {
$validators[] = new CallbackValidator([
"callback" => function ($data) {
$messages = [];
$encoding = $this->getParentNode()->encoding->getValue();
if ($encoding === "hex") {
if (!preg_match('/^([0-9A-F]{2})+$/', $data)) {
$messages[] = gettext("Hex value must contain uppercase hexadecimal byte pairs.");
}
}
if ($encoding === "string") {
if (preg_match('/[\'"]/', $data)) {
$messages[] = gettext("String value must not contain quotes.");
}
}
return $messages;
}
]);
}
return $validators;
}
}

View file

@ -196,12 +196,53 @@ class KeaDhcpv4 extends BaseModel
// Add DHCP option-data elements for reservations
$optdata = $this->collectOptionData($reservation->option_data);
// Append raw options
foreach ($reservation->option->getValues() as $uuid) {
$option = $this->getNodeByReference("options.option.$uuid");
if ($option === null) {
continue;
}
// Kea autoconverts strings to binary when providing 'data' => "'data to convert'"
$data = $option->data->getValue();
if ($option->encoding->isEqual('string')) {
$data = "'{$data}'";
}
$optdata[] = [
'code' => $option->code->asInt(),
'csv-format' => false,
'data' => $data,
'always-send' => !$option->force->isEmpty(),
];
}
if (!empty($optdata)) {
$res['option-data'] = $optdata;
}
$record['reservations'][] = $res;
}
/* append raw options */
foreach ($subnet->option->getValues() as $uuid) {
$option = $this->getNodeByReference("options.option.$uuid");
if ($option === null) {
continue;
}
// Kea autoconverts strings to binary when providing 'data' => "'data to convert'"
$data = $option->data->getValue();
if ($option->encoding->isEqual('string')) {
$data = "'{$data}'";
}
$entry = [
'code' => $option->code->asInt(),
'csv-format' => false,
'data' => $data,
'always-send' => !$option->force->isEmpty(),
];
$record['option-data'][] = $entry;
}
$result[] = $record;
}
return $result;

View file

@ -129,6 +129,16 @@
<Mask>/^([^\n"])*$/u</Mask>
</v4_dnr>
</option_data>
<option type="ModelRelationField">
<Model>
<options>
<source>OPNsense.Kea.KeaDhcpv4</source>
<items>options.option</items>
<display>description</display>
</options>
</Model>
<Multiple>Y</Multiple>
</option>
<match-client-id type="BooleanField">
<Default>1</Default>
<Required>Y</Required>
@ -286,8 +296,46 @@
<Mask>/^([^\n"])*$/u</Mask>
</boot_file_name>
</option_data>
<option type="ModelRelationField">
<Model>
<options>
<source>OPNsense.Kea.KeaDhcpv4</source>
<items>options.option</items>
<display>description</display>
</options>
</Model>
<Multiple>Y</Multiple>
</option>
</reservation>
</reservations>
<options>
<option type="ArrayField">
<code type="JsonKeyValueStoreField">
<Required>Y</Required>
<ConfigdPopulateAct>kea list dhcp_options</ConfigdPopulateAct>
<OptionValues>
<!-- mock option groups returned by JSON -->
<optgroup1>Assigned</optgroup1>
<optgroup2>Unassigned</optgroup2>
</OptionValues>
</code>
<encoding type="OptionField">
<Required>Y</Required>
<Default>hex</Default>
<OptionValues>
<hex>hex</hex>
<string>string</string>
</OptionValues>
</encoding>
<data type=".\KeaOptionDataField">
<Required>Y</Required>
</data>
<force type="BooleanField"/>
<description type="DescriptionField">
<Required>Y</Required>
</description>
</option>
</options>
<ha_peers>
<peer type="ArrayField">
<name type="TextField">

View file

@ -52,6 +52,9 @@
case '#reservations':
grid_ids = ["{{formGridReservation['table_id']}}"];
break;
case '#options':
grid_ids = ["{{formGridOption['table_id']}}"];
break;
case '#ha-peers':
grid_ids = ["{{formGridPeer['table_id']}}"];
break;
@ -203,6 +206,7 @@
<li><a data-toggle="tab" href="#settings" id="tab_settings">{{ lang._('Settings') }}</a></li>
<li><a data-toggle="tab" href="#subnets" id="tab_pools" class="is_managed"> {{ lang._('Subnets') }} </a></li>
<li><a data-toggle="tab" href="#reservations" id="tab_reservations" class="is_managed"> {{ lang._('Reservations') }} </a></li>
<li><a data-toggle="tab" href="#options" id="tab_options">{{ lang._('Options') }}</a></li>
<li><a data-toggle="tab" href="#ha-peers" id="tab_ha-peers" class="is_managed"> {{ lang._('HA Peers') }} </a></li>
</ul>
<div class="tab-content content-box">
@ -220,6 +224,10 @@
partial('layout_partials/base_bootgrid_table', formGridReservation)
}}
</div>
<!-- options -->
<div id="options" class="tab-pane fade in">
{{ partial('layout_partials/base_bootgrid_table', formGridOption)}}
</div>
<!-- HA - peers -->
<div id="ha-peers" class="tab-pane fade in">
{{ partial('layout_partials/base_bootgrid_table', formGridPeer)}}
@ -229,4 +237,5 @@
{{ partial('layout_partials/base_apply_button', {'data_endpoint': '/api/kea/service/reconfigure', 'data_service_widget': 'kea'}) }}
{{ partial("layout_partials/base_dialog",['fields':formDialogSubnet,'id':formGridSubnet['edit_dialog_id'],'label':lang._('Edit Subnet')])}}
{{ partial("layout_partials/base_dialog",['fields':formDialogReservation,'id':formGridReservation['edit_dialog_id'],'label':lang._('Edit Reservation')])}}
{{ partial("layout_partials/base_dialog",['fields':formDialogOption,'id':formGridOption['edit_dialog_id'],'label':lang._('Edit Option')])}}
{{ partial("layout_partials/base_dialog",['fields':formDialogPeer,'id':formGridPeer['edit_dialog_id'],'label':lang._('Edit Peer')])}}

View file

@ -0,0 +1,73 @@
#!/usr/local/bin/python3
"""
Copyright (c) 2026 Deciso B.V.
Copyright (c) 2025 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 csv
import json
import argparse
option_src = {
'dhcp': 'iana/dhcpv4-options.csv', # https://www.iana.org/assignments/bootp-dhcp-parameters/
'dhcp6': 'iana/dhcpv6-parameters-2.csv' # https://www.iana.org/assignments/dhcpv6-parameters/
}
parser = argparse.ArgumentParser()
parser.add_argument("mode", nargs="?", default="dhcp", choices=["dhcp", "dhcp6"])
args = parser.parse_args()
assigned = {}
unassigned = {}
# load IANA data
with open('/usr/local/opnsense/contrib/' + option_src[args.mode], 'r') as csvfile:
for r in csv.reader(csvfile, delimiter=',', quotechar='"'):
if not r or not r[0]:
continue
r_range = [int(x) for x in r[0].split('-') if x.isdigit()]
if not r_range or len(r) < 2:
continue
name = r[1].strip().lower()
for code in range(r_range[0], (r_range[1] if len(r_range) > 1 else r_range[0]) + 1):
key = str(code)
if name in ['unassigned', 'removed/unassigned']:
# Only track unassigned for DHCPv4 (256 total), not DHCPv6 (65535 total)
if args.mode == 'dhcp':
unassigned[key] = f"{name} [{code}]"
elif name not in ['pad', 'end']:
cleaned_name = name.replace('\n', ' ')
assigned[key] = f"{cleaned_name} [{code}]"
print(json.dumps({
"Assigned": assigned,
"Unassigned": unassigned
}))

View file

@ -23,6 +23,12 @@ parameters:
type:script_output
message:get kea daemon status
[list.dhcp_options]
command:/usr/local/opnsense/scripts/kea/kea_dhcp_options.py dhcp
type:script_output
message:request dhcp options
cache_ttl:86400
[list.leases4]
command:/usr/local/opnsense/scripts/kea/get_kea_leases.py
parameters:--proto inet