{ self }: { config, lib, pkgs, ... }: let inherit (lib) escapeShellArg mkEnableOption mkIf mkOption optionals types; cfg = config.services.seiugw; hostProvisioningRequest = "${cfg.dataDir}/provisioning/host.json"; komariInstalledMarker = "${cfg.dataDir}/provisioning/komari-installed"; komariRuntimeToken = "/run/seiugw-komari/token"; bacnetStackServer = pkgs.callPackage ./bacnet.nix { }; manageHostNetwork = config.networking.useDHCP && config.networking.dhcpcd.enable && !config.networking.useNetworkd && !config.networking.networkmanager.enable; dhcpcdBase = builtins.head (builtins.match ".* --config ([^ ]+).*" config.systemd.services.dhcpcd.serviceConfig.ExecStart); networkHelper = "${pkgs.python3}/bin/python3 ${./host-network.py}"; updateSocket = "/run/seiugw-update/request.sock"; updateAvailability = pkgs.writeShellScript "seiugw-update-availability" '' export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.git ]} export SEIUGW_UPDATE_REMOTE=${escapeShellArg cfg.updates.remote} export SEIUGW_UPDATE_BRANCH=${escapeShellArg cfg.updates.branch} ${builtins.readFile ./system-update-availability.sh} ''; updateWorker = pkgs.writeShellScript "seiugw-system-update" '' export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.git pkgs.util-linux pkgs.systemd pkgs.curl pkgs.jq pkgs.sqlite pkgs.nix ]}:/run/current-system/sw/bin export NIX_PATH=${escapeShellArg "nixos-config=/etc/nixos/configuration.nix:nixpkgs=${pkgs.path}"} export SEIUGW_UPDATE_REPO=${escapeShellArg cfg.updates.checkout} export SEIUGW_UPDATE_REMOTE=${escapeShellArg cfg.updates.remote} export SEIUGW_UPDATE_BRANCH=${escapeShellArg cfg.updates.branch} export SEIUGW_UPDATE_DATA=${escapeShellArg cfg.dataDir} export SEIUGW_UPDATE_HEALTH=${escapeShellArg "http://127.0.0.1:${toString cfg.webPort}"} ${builtins.readFile ./system-update.sh} ''; updateTrigger = pkgs.writeShellScript "seiugw-request-update" '' if ${pkgs.systemd}/bin/systemd-run --quiet --collect --unit=seiugw-update-worker \ --property=Type=exec ${updateWorker} >&2; then printf 'accepted\n' else printf 'unavailable\n' fi ''; in { options.services.seiugw = { enable = mkEnableOption "SEIU Gateway"; package = mkOption { type = types.package; default = self.packages.${pkgs.stdenv.hostPlatform.system}.default; description = "SEIU Gateway package to run."; }; dataDir = mkOption { type = types.str; default = "/var/lib/seiugw"; description = "Persistent SQLite database, gateway key and later PKI storage."; }; listenAddress = mkOption { type = types.str; default = "0.0.0.0"; description = "Address for the local web administration service."; }; webPort = mkOption { type = types.port; default = 8088; description = "TCP port for the local web administration service."; }; openFirewall = mkOption { type = types.bool; default = true; description = "Open the configured web and BACnet/IP ports in the NixOS firewall."; }; updates = { enable = mkEnableOption "local-root system updates requested by the Gateway administrator"; checkout = mkOption { type = types.str; default = "/etc/nixos/seiugw"; description = "Root-owned checkout already used by the NixOS host configuration."; }; remote = mkOption { type = types.str; default = ""; description = "Trusted HTTPS Git URL used by the update worker."; }; branch = mkOption { type = types.str; default = "main"; description = "Branch allowed for fast-forward gateway updates."; }; }; bacnet = { interface = mkOption { type = types.str; example = "ens18"; description = "Linux interface connected to the BACnet/IP field network."; }; deviceInstance = mkOption { type = types.ints.between 0 4194303; default = 23; description = "Configurable BACnet device instance. Vendor ID remains fixed at 815."; }; ipPort = mkOption { type = types.port; default = 47808; description = "BACnet/IP UDP port."; }; }; opcUa.port = mkOption { type = types.port; default = 4840; description = "Reserved OPC UA TCP port passed to the gateway."; }; modbusTcpPorts = mkOption { type = types.listOf types.port; default = [ 502 ]; description = "Modbus-TCP ports opened by the NixOS firewall. Add every non-standard port used by a server instance."; }; trends = { enable = mkOption { type = types.bool; default = true; description = "Run the local MariaDB store for long-term and legacy trend data."; }; databaseName = mkOption { type = types.str; default = "wago"; description = "MariaDB database retaining the legacy SE-LTD table format."; }; }; komari = { enable = mkOption { type = types.bool; default = true; description = "Register the gateway with a Komari server once the one-time commissioning request and secret token exist."; }; endpoint = mkOption { type = types.str; default = "https://komari.cloud.se-inno.de"; description = "Komari endpoint passed to the agent."; }; enrollmentTokenFile = mkOption { type = types.str; default = "${cfg.dataDir}/komari-enrollment-token"; description = "Root-only import file for a replacement Komari token. Imported into encrypted gateway storage, then removed. Never put plaintext tokens into Nix or Git."; }; installDir = mkOption { type = types.str; default = "/opt/komari"; description = "Mutable location used by the upstream Komari installer for its agent binary."; }; installerUrl = mkOption { type = types.str; default = "https://raw.githubusercontent.com/komari-monitor/komari-agent/refs/heads/main/install.sh"; description = "Upstream Komari installer URL. It is deliberately only fetched during one-time commissioning."; }; ignoreUnsafeCertificateErrors = mkOption { type = types.bool; default = true; description = "Pass --ignore-unsafe-cert to the Komari agent as requested for the controlled Komari endpoint."; }; }; }; config = mkIf cfg.enable { assertions = optionals cfg.updates.enable [ { assertion = builtins.match "https://[^/@]+/[^?#]+" cfg.updates.remote != null; message = "Gateway system updates require an HTTPS Git remote without embedded credentials."; } ]; users.groups.seiugw = { }; users.groups.dialout = { }; users.users.seiugw = { isSystemUser = true; group = "seiugw"; extraGroups = [ "dialout" ]; home = cfg.dataDir; createHome = true; }; systemd.tmpfiles.rules = [ "d ${cfg.dataDir} 0750 seiugw seiugw -" "d ${cfg.dataDir}/provisioning 0750 seiugw seiugw -" ] ++ optionals manageHostNetwork [ "d /run/seiugw-network 0750 root seiugw -" "d /var/lib/seiugw-network 0700 root root -" ] ++ optionals cfg.komari.enable [ "d ${cfg.komari.installDir} 0750 root root -" ] ++ optionals cfg.updates.enable [ "d /var/lib/seiugw-updater 0755 root root -" ]; systemd.sockets.seiugw-update = mkIf cfg.updates.enable { description = "Local Gateway system update requests"; wantedBy = [ "sockets.target" ]; socketConfig = { ListenStream = updateSocket; SocketUser = "root"; SocketGroup = "seiugw"; SocketMode = "0660"; Accept = true; RemoveOnStop = true; }; }; systemd.services."seiugw-update@" = mkIf cfg.updates.enable { description = "Start the independent Gateway update worker"; serviceConfig = { ExecStart = updateTrigger; StandardInput = "socket"; StandardOutput = "socket"; StandardError = "journal"; }; }; networking.firewall = mkIf cfg.openFirewall { allowedTCPPorts = [ cfg.webPort cfg.opcUa.port ] ++ cfg.modbusTcpPorts; allowedUDPPorts = [ cfg.bacnet.ipPort ]; }; # dhcpcd sees the composed file only in its own mount namespace. # The NixOS base config and options remain the source for unmanaged cards. systemd.services.dhcpcd = mkIf manageHostNetwork { requires = [ "seiugw-network-prepare.service" ]; after = [ "seiugw-network-prepare.service" ]; serviceConfig.BindReadOnlyPaths = [ "/run/seiugw-network/dhcpcd.conf:${dhcpcdBase}" ]; }; systemd.services.seiugw-network-prepare = mkIf manageHostNetwork { description = "Load confirmed SE-Inno IPv4 profiles"; serviceConfig = { Type = "oneshot"; RemainAfterExit = true; ExecStart = "${networkHelper} prepare ${dhcpcdBase} ${pkgs.iproute2}/bin/ip ${pkgs.systemd}/bin/systemctl"; }; }; systemd.sockets.seiugw-network = mkIf manageHostNetwork { wantedBy = [ "sockets.target" ]; socketConfig = { ListenStream = "/run/seiugw-network/control.sock"; SocketMode = "0660"; SocketGroup = "seiugw"; RemoveOnStop = true; }; }; systemd.services.seiugw-network = mkIf manageHostNetwork { description = "SE-Inno host IPv4 control and rollback"; after = [ "seiugw-network-prepare.service" ]; requires = [ "seiugw-network-prepare.service" ]; serviceConfig = { ExecStart = "${networkHelper} serve ${dhcpcdBase} ${pkgs.iproute2}/bin/ip ${pkgs.systemd}/bin/systemctl"; Restart = "on-failure"; RestartSec = "1s"; UMask = "0077"; ProtectSystem = "strict"; ProtectHome = true; PrivateTmp = true; NoNewPrivileges = true; ReadWritePaths = [ "/run/seiugw-network" "/var/lib/seiugw-network" ]; }; }; # Keep MariaDB local. The gateway process receives socket-authenticated access; # no database password or network-exposed database account is created. services.mysql = mkIf cfg.trends.enable { enable = true; package = pkgs.mariadb; settings.mysqld.bind-address = "127.0.0.1"; ensureDatabases = [ cfg.trends.databaseName ]; ensureUsers = [ { name = "seiugw"; ensurePermissions = { "${cfg.trends.databaseName}.*" = "ALL PRIVILEGES"; }; } ]; initialDatabases = [ { name = cfg.trends.databaseName; schema = ./legacy-schema.sql; } ]; }; systemd.services.seiugw = { description = "SEIU industrial protocol gateway"; wantedBy = [ "multi-user.target" ]; wants = [ "network-online.target" ]; after = [ "network-online.target" ] ++ optionals cfg.trends.enable [ "mysql.service" ]; requires = optionals cfg.trends.enable [ "mysql.service" ]; environment = { ASPNETCORE_URLS = "http://${cfg.listenAddress}:${toString cfg.webPort}"; Gateway__DataDirectory = cfg.dataDir; Gateway__ProtocolDataPlane = "native-bacnet-ip"; Gateway__Bacnet__Interface = cfg.bacnet.interface; Gateway__Bacnet__DeviceInstance = toString cfg.bacnet.deviceInstance; Gateway__Bacnet__IpPort = toString cfg.bacnet.ipPort; Gateway__OpcUa__Port = toString cfg.opcUa.port; Gateway__RunningCommit = cfg.package.sourceRevision or ""; } // lib.optionalAttrs cfg.updates.enable { Gateway__UpdateSocketPath = updateSocket; Gateway__UpdateStatusPath = "/var/lib/seiugw-updater/status.json"; Gateway__UpdateAvailabilityCommand = updateAvailability; Gateway__UpdateBranch = cfg.updates.branch; }; serviceConfig = { ExecStart = "${cfg.package}/bin/Gateway.Api"; User = "seiugw"; Group = "seiugw"; WorkingDirectory = cfg.dataDir; UMask = "0077"; Restart = "on-failure"; RestartSec = "5s"; AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ]; CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ]; NoNewPrivileges = true; PrivateTmp = true; ProtectHome = true; ProtectSystem = "strict"; ReadWritePaths = [ cfg.dataDir ]; }; }; # Native BACnet/IP device. This is a separate, supervised C process from # the upstream BACnet stack; it owns UDP/47808 rather than relying on a # web process or Docker networking. Objects and durable priority slots # are materialised from SQLite by the native bridge. systemd.services.seiugw-bacnet = { description = "SEIU native BACnet/IP device"; wantedBy = [ "multi-user.target" ]; wants = [ "network-online.target" "seiugw.service" ]; after = [ "network-online.target" "seiugw.service" ]; # The web unit is Type=simple: ordering alone does not mean its schema # migration has finished. Wait for the bridge tables on a first upgrade. preStart = '' for attempt in {1..30}; do if [ -f ${escapeShellArg "${cfg.dataDir}/seiugw.db"} ] && \ [ "$(${pkgs.sqlite}/bin/sqlite3 ${escapeShellArg "${cfg.dataDir}/seiugw.db"} "SELECT (SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ('bacnet_commands','bacnet_properties','bacnet_observations','bacnet_runtime','bacnet_discovery','bacnet_discovered_devices'))+(SELECT COUNT(*) FROM pragma_table_info('bacnet_discovered_devices') WHERE name IN ('network','mac'))+(SELECT COUNT(*) FROM pragma_table_info('points') WHERE name='deleted_at_utc');" 2>/dev/null)" = 9 ]; then exit 0 fi sleep 1 done echo "Gateway database schema is not ready" >&2 exit 1 ''; environment = { BACNET_DATALINK = "bip"; SEIUGW_DATABASE = "${cfg.dataDir}/seiugw.db"; BACNET_IFACE = cfg.bacnet.interface; BACNET_IP_PORT = toString cfg.bacnet.ipPort; BACNET_IP_BROADCAST_PORT = toString cfg.bacnet.ipPort; }; serviceConfig = { ExecStart = "${bacnetStackServer}/bin/bacserv ${toString cfg.bacnet.deviceInstance} SEIU-Gateway"; User = "seiugw"; Group = "seiugw"; WorkingDirectory = cfg.dataDir; UMask = "0077"; Restart = "on-failure"; RestartSec = "5s"; NoNewPrivileges = true; PrivateTmp = true; ProtectHome = true; ProtectSystem = "strict"; ReadWritePaths = [ cfg.dataDir ]; }; }; # The web process writes only project number and ISP as JSON after its first # successful commissioning. This root helper validates both values again # before applying the runtime hostname. The data is retained so the name is # re-applied after every later boot without changing NixOS configuration. systemd.services.seiugw-apply-hostname = { description = "Apply SEIU Gateway commissioning hostname"; wantedBy = [ "multi-user.target" ]; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; serviceConfig = { Type = "oneshot"; }; path = [ pkgs.coreutils pkgs.gnugrep pkgs.hostname pkgs.jq ]; script = '' set -euo pipefail request=${escapeShellArg hostProvisioningRequest} [ -s "$request" ] || exit 0 project="$(${pkgs.jq}/bin/jq -er '.projectNumber' "$request")" || exit 0 isp="$(${pkgs.jq}/bin/jq -er '.ispNumber' "$request")" || exit 0 if ! ${pkgs.gnugrep}/bin/grep -Eq '^P[A-Z0-9_-]{1,32}$' <<<"$project"; then exit 0 fi case "$isp" in *[!0-9]*|"") exit 0 ;; esac if [ "$isp" -lt 1 ] || [ "$isp" -gt 99 ]; then exit 0 fi host_name="SE-UGW-$project-ISP$(printf '%02d' "$isp")" [ "''${#host_name}" -le 63 ] || exit 0 [ "$(${pkgs.hostname}/bin/hostname)" != "$host_name" ] || exit 0 ${pkgs.hostname}/bin/hostname "$host_name" ''; }; systemd.paths.seiugw-apply-hostname = { wantedBy = [ "multi-user.target" ]; pathConfig = { PathChanged = hostProvisioningRequest; Unit = "seiugw-apply-hostname.service"; }; }; systemd.services.seiugw-komari-token = mkIf cfg.komari.enable { description = "Import and materialize encrypted Komari credential"; wantedBy = [ "multi-user.target" ]; after = [ "seiugw.service" ]; requires = [ "seiugw.service" ]; environment.Gateway__DataDirectory = cfg.dataDir; serviceConfig = { Type = "oneshot"; UMask = "0077"; Restart = "on-failure"; RestartSec = "10s"; }; script = '' set -euo pipefail ${pkgs.coreutils}/bin/install -d -m 0700 -o seiugw -g seiugw /run/seiugw-komari # Stage root's input for the unprivileged database owner. Never print it. if [ -s ${escapeShellArg cfg.komari.enrollmentTokenFile} ]; then ${pkgs.coreutils}/bin/install -m 0600 -o seiugw -g seiugw ${escapeShellArg cfg.komari.enrollmentTokenFile} /run/seiugw-komari/import ${pkgs.util-linux}/bin/runuser -u seiugw -- ${cfg.package}/bin/Gateway.Api --import-komari-token /run/seiugw-komari/import ${pkgs.coreutils}/bin/rm -f /run/seiugw-komari/import ${escapeShellArg cfg.komari.enrollmentTokenFile} fi if ${pkgs.util-linux}/bin/runuser -u seiugw -- ${cfg.package}/bin/Gateway.Api --materialize-komari-token /run/seiugw-komari/next; then if ! ${pkgs.diffutils}/bin/cmp -s /run/seiugw-komari/next ${komariRuntimeToken}; then ${pkgs.coreutils}/bin/mv /run/seiugw-komari/next ${komariRuntimeToken} ${pkgs.systemd}/bin/systemctl --no-block try-restart seiugw-komari-agent.service ${pkgs.systemd}/bin/systemctl --no-block restart seiugw-komari-bootstrap.service else ${pkgs.coreutils}/bin/rm -f /run/seiugw-komari/next fi fi ''; }; systemd.paths.seiugw-komari-token = mkIf cfg.komari.enable { wantedBy = [ "multi-user.target" ]; pathConfig = { PathChanged = [ "${cfg.dataDir}/provisioning/komari-token.request" cfg.komari.enrollmentTokenFile ]; Unit = "seiugw-komari-token.service"; }; }; systemd.services.seiugw-komari-bootstrap = mkIf cfg.komari.enable { description = "One-time Komari agent installer for SEIU Gateway"; after = [ "network-online.target" "seiugw-apply-hostname.service" "seiugw-komari-token.service" ]; requires = [ "seiugw-apply-hostname.service" "seiugw-komari-token.service" ]; wants = [ "network-online.target" ]; serviceConfig = { Type = "oneshot"; # Both prerequisites are already watched by the commissioning path. # A completed installer must remain active; otherwise PathExists can # repeatedly start this successful no-op and hit systemd's start limit. RemainAfterExit = true; Restart = "on-failure"; RestartSec = "30s"; }; path = [ pkgs.bash pkgs.coreutils pkgs.curl ]; script = '' set -euo pipefail marker=${escapeShellArg komariInstalledMarker} token_file=${escapeShellArg komariRuntimeToken} install_dir=${escapeShellArg cfg.komari.installDir} agent="$install_dir/agent" [ -e "$marker" ] && exit 0 [ -s ${escapeShellArg hostProvisioningRequest} ] || exit 0 [ -r "$token_file" ] || exit 0 token="$(${pkgs.coreutils}/bin/cat "$token_file")" [ -n "$token" ] || exit 0 if [ ! -x "$agent" ]; then ${pkgs.curl}/bin/curl --fail --location --silent --show-error --proto '=https' ${escapeShellArg cfg.komari.installerUrl} \ | ${pkgs.bash}/bin/bash -s -- --install-dir "$install_dir" --install-no-mirror -e ${escapeShellArg cfg.komari.endpoint} --auto-discovery "$token" ${lib.optionalString cfg.komari.ignoreUnsafeCertificateErrors "--ignore-unsafe-cert"} fi [ -x "$agent" ] ${pkgs.systemd}/bin/systemctl try-restart seiugw-komari-agent.service || ${pkgs.systemd}/bin/systemctl start seiugw-komari-agent.service ${pkgs.coreutils}/bin/touch "$marker" ${pkgs.coreutils}/bin/chmod 0600 "$marker" ''; }; systemd.paths.seiugw-komari-request = mkIf cfg.komari.enable { wantedBy = [ "multi-user.target" ]; pathConfig = { PathExists = hostProvisioningRequest; PathChanged = hostProvisioningRequest; Unit = "seiugw-komari-bootstrap.service"; }; }; # The upstream installer deliberately does not create a NixOS unit. NixOS # owns this unit instead, while the binary remains in the upstream mutable # install directory. The enrollment token is read at service start and is # never placed in the Nix store. systemd.services.seiugw-komari-agent = mkIf cfg.komari.enable { description = "Komari monitoring agent"; after = [ "network-online.target" "seiugw-apply-hostname.service" "seiugw-komari-token.service" ]; wants = [ "network-online.target" "seiugw-komari-token.service" ]; wantedBy = [ "multi-user.target" ]; unitConfig.ConditionPathExists = "${cfg.komari.installDir}/agent"; serviceConfig = { Type = "simple"; WorkingDirectory = cfg.komari.installDir; Restart = "always"; RestartSec = "10s"; }; path = [ pkgs.bash pkgs.coreutils ]; script = '' set -euo pipefail token="$(${pkgs.coreutils}/bin/cat ${escapeShellArg komariRuntimeToken})" [ -n "$token" ] exec ${escapeShellArg "${cfg.komari.installDir}/agent"} -e ${escapeShellArg cfg.komari.endpoint} --auto-discovery "$token" ${lib.optionalString cfg.komari.ignoreUnsafeCertificateErrors "--ignore-unsafe-cert"} ''; }; }; }