Files

436 lines
18 KiB
Nix

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# services.ianitor: ianitor-edge (the only public listener), ianitor-control (loopback),
# caddy-fallback (the same routes as Caddy JSON), the engine-select unit, the per-boot UI proof,
# and a polkit rule that lets control start and stop exactly the two engine units. While Caddy
# serves, control loads changes into it through its admin socket (/run/caddy-fallback/admin.sock,
# group ianitor, 0660).
#
# Secrets never enter the Nix store: every credential is a *path string* to a file outside the
# store (sops-nix, agenix, Custos provisioning, ...), loaded with systemd LoadCredential; an
# assertion refuses any /nix/store path.
self:
{ config, lib, pkgs, ... }:
let
cfg = config.services.ianitor;
inherit (lib) mkOption mkEnableOption mkIf types;
pkg = cfg.package;
stateRoot = "/var/lib/ianitor";
runProof = "/run/ianitor-proof";
toml = pkgs.formats.toml { };
isStore = p: lib.hasPrefix builtins.storeDir (toString p);
# Every credential file the units load, by credential name.
edgeCreds =
cfg.credentials
// lib.optionalAttrs (cfg.shareLinkKeyFile != null) { "share-link-key" = cfg.shareLinkKeyFile; };
controlCreds =
lib.optionalAttrs (cfg.shareLinkKeyFile != null) { "share-link-key" = cfg.shareLinkKeyFile; }
// lib.optionalAttrs (cfg.pki.enable) { "pki-password" = cfg.pki.passwordFile; }
// lib.optionalAttrs (cfg.routes.pushCredentialFile != null) { push = cfg.routes.pushCredentialFile; };
userCreds = edgeCreds // controlCreds;
loadCreds = creds: lib.mapAttrsToList (n: p: "${n}:${p}") creds;
compile = {
http_listen = cfg.edge.httpListen;
https_listen = cfg.edge.httpsListen;
cert_dir = "${stateRoot}/certs";
state_dir = "${stateRoot}/edge-state";
access_log = "/var/log/ianitor/access.log";
caddy_credentials_dir = "/run/credentials/caddy-fallback.service";
trusted_proxies = cfg.edge.trustedProxies;
};
controlToml = toml.generate "control.toml" (
{
listen = cfg.control.listen;
state_dir = "${stateRoot}/control";
git = "${pkgs.git}/bin/git";
watch_secs = cfg.watchSeconds;
routes =
{
repo = "${stateRoot}/control/routes.git";
remote_name = cfg.routes.remoteName;
push_username = cfg.routes.pushUsername;
}
// lib.optionalAttrs (cfg.routes.remote != null) { remote = cfg.routes.remote; }
// lib.optionalAttrs (cfg.routes.pushCredentialFile != null) { push_credential = "push"; };
edge = {
config = "${stateRoot}/edge/edge.json";
admin_socket = "/run/ianitor-edge/admin.sock";
share_revocations = "${stateRoot}/edge/share-revocations.json";
};
caddy.config = "${stateRoot}/caddy/caddy.json";
inherit compile;
# Caddy keeps its own storage and access log; the listeners and certificates are the same.
compile_caddy = compile // {
state_dir = "${stateRoot}/caddy-state";
access_log = "/var/log/ianitor/caddy-access.log";
# Changes keep working under Caddy: control loads them through this socket.
caddy_admin_socket = "/run/caddy-fallback/admin.sock";
};
ui =
{
proof_credential = "ui-proof";
static_dir = "${pkg}/share/ianitor/web";
}
// lib.optionalAttrs (cfg.ui.hostname != null) { hostname = cfg.ui.hostname; }
// lib.optionalAttrs (cfg.ui.logoutUrl != null) { logout_url = cfg.ui.logoutUrl; };
engine = {
file = "${stateRoot}/engine";
systemctl = "${config.systemd.package}/bin/systemctl";
};
}
// lib.optionalAttrs cfg.pki.enable {
pki = {
root_cert = toString cfg.pki.rootCertificate;
password_credential = "pki-password";
};
}
);
hardening = {
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
ProtectHome = true;
ProtectKernelTunables = true;
ProtectKernelModules = true;
ProtectControlGroups = true;
ProtectClock = true;
ProtectHostname = true;
RestrictSUIDSGID = true;
RestrictNamespaces = true;
LockPersonality = true;
MemoryDenyWriteExecute = true;
SystemCallArchitectures = "native";
RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
UMask = "0027";
};
in
{
options.services.ianitor = {
enable = mkEnableOption "Ianitor Domi, the reverse proxy on Pingora with its control plane";
package = mkOption {
type = types.package;
default = self.packages.${pkgs.stdenv.hostPlatform.system}.ianitor;
defaultText = lib.literalExpression "ianitor.packages.\${system}.ianitor";
description = "The release build (test hooks off).";
};
caddyPackage = mkOption {
type = types.package;
# The Caddy the differential tests run against (Ianitor's own pinned nixpkgs), not the host's:
# the Caddy JSON is only proven equal for that version.
default = self.inputs.nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system}.caddy;
defaultText = lib.literalExpression "ianitor.inputs.nixpkgs.legacyPackages.<system>.caddy";
description = "The Caddy that runs the fallback.";
};
edge = {
httpListen = mkOption {
type = types.str;
default = "0.0.0.0:80";
description = "Plain-HTTP listener (ACME HTTP-01, redirects). The only public listeners are edge's.";
};
httpsListen = mkOption {
type = types.str;
default = "0.0.0.0:443";
description = "TLS listener serving every host by SNI.";
};
openFirewall = mkOption {
type = types.bool;
default = false;
description = "Open edge's two ports in the firewall.";
};
trustedProxies = mkOption {
type = types.listOf types.str;
default = [ ];
example = [ "127.0.0.1" ];
description = "Proxies in front of edge whose X-Forwarded-For names the client (beside Caddy: 127.0.0.1), for the share-link throttle and the access log. Off by default: on a loopback listener any local process could then claim any address (docs/deploy/beside-caddy.md).";
};
};
control.listen = mkOption {
type = types.str;
default = "127.0.0.1:7878";
description = "The API and UI. Loopback only (an assertion refuses anything else).";
};
watchSeconds = mkOption {
type = types.ints.between 1 3600;
default = 60;
description = "How long the health watch after an apply lasts.";
};
defaultEngine = mkOption {
type = types.enum [ "pingora" "caddy" ];
default = "pingora";
description = "The engine at first boot; afterwards the UI's choice in ${stateRoot}/engine.";
};
routes = {
remote = mkOption {
type = types.nullOr types.str;
default = null;
example = "https://gitea.example/mnovak/ianitor-routes.git";
description = "Where kept changes are pushed.";
};
remoteName = mkOption {
type = types.str;
default = "Gitea";
description = "Shown in the UI.";
};
pushUsername = mkOption {
type = types.str;
default = "ianitor";
description = "User name for HTTPS pushes.";
};
pushCredentialFile = mkOption {
type = types.nullOr types.str;
default = null;
description = "File (outside the Nix store) holding the push token.";
};
};
shareLinkKeyFile = mkOption {
type = types.nullOr types.str;
default = null;
description = "File (outside the Nix store) with the share-link key, at least 32 characters. Without it, share links are off.";
};
credentials = mkOption {
type = types.attrsOf types.str;
default = { };
example = { wiki_token = "/run/secrets/wiki-token"; };
description = "Secrets that header rules reference, by name: files outside the Nix store, loaded into edge and caddy-fallback with LoadCredential.";
};
pki = {
enable = mkEnableOption "the Domi CA (docs/pki.md)";
rootCertificate = mkOption {
type = types.path;
description = "The Domi root certificate (public; it may be in the store). The root key never comes to the server.";
};
passwordFile = mkOption {
type = types.str;
description = "File (outside the Nix store) with the password that encrypts the intermediate and device keys at rest.";
};
};
ui = {
hostname = mkOption {
type = types.nullOr types.str;
default = null;
example = "ianitor.example";
description = "The admin host edge serves the UI on (a host in the routes repository with forward-auth and the X-Ianitor-Proof rule, docs/api.md).";
};
logoutUrl = mkOption {
type = types.nullOr types.str;
default = null;
example = "https://auth.example/logout";
description = "Authelia's logout address, for the UI's Sign out.";
};
};
};
config = mkIf cfg.enable {
assertions =
[
{
assertion = lib.any (p: lib.hasPrefix p cfg.control.listen) [ "127." "[::1]:" "localhost:" ];
message = "services.ianitor.control.listen must be a loopback address; only ianitor-edge binds public ports.";
}
]
++ lib.mapAttrsToList (n: p: {
assertion = !isStore p;
message = "services.ianitor: the credential ${n} points into the Nix store (${toString p}); secrets must come from systemd credentials, never the store.";
}) userCreds;
users.groups.ianitor = { };
# Only control (and Caddy itself) may reach Caddy's admin socket; edge is not in it.
users.groups.ianitor-caddy-admin = { };
users.users.ianitor-control = { isSystemUser = true; group = "ianitor"; extraGroups = [ "ianitor-caddy-admin" ]; home = "${stateRoot}/control"; };
users.users.ianitor-edge = { isSystemUser = true; group = "ianitor"; };
users.users.caddy-fallback = { isSystemUser = true; group = "ianitor"; };
systemd.tmpfiles.rules = [
"d ${stateRoot} 0755 ianitor-control ianitor - -"
"d ${stateRoot}/control 0700 ianitor-control ianitor - -"
"d ${stateRoot}/edge 0750 ianitor-control ianitor - -"
"d ${stateRoot}/caddy 0750 ianitor-control ianitor - -"
"d ${stateRoot}/certs 0750 ianitor-control ianitor - -"
"d ${stateRoot}/edge-state 0700 ianitor-edge ianitor - -"
"d ${stateRoot}/caddy-state 0700 caddy-fallback ianitor - -"
"f ${stateRoot}/engine 0644 ianitor-control ianitor - ${cfg.defaultEngine}"
"d /var/log/ianitor 0770 ianitor-edge ianitor - -"
];
environment.systemPackages = [ pkg ];
# The non-secret config, so the CLI (token, pki) finds it: --config /etc/ianitor/control.toml.
environment.etc."ianitor/control.toml".source = controlToml;
# A new secret every boot, readable by root only; edge and control load it as a credential.
systemd.services.ianitor-ui-proof = {
description = "Ianitor: per-boot proof for the admin host";
before = [ "ianitor-edge.service" "ianitor-control.service" "caddy-fallback.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
RuntimeDirectory = "ianitor-proof";
RuntimeDirectoryMode = "0700";
RuntimeDirectoryPreserve = true;
UMask = "0077";
};
script = ''
head -c 32 /dev/urandom | ${pkgs.coreutils}/bin/base64 -w0 > ${runProof}/ui-proof
'';
};
systemd.services.ianitor-control = {
description = "Ianitor control (API and UI on loopback)";
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" "ianitor-ui-proof.service" ];
wants = [ "network-online.target" ];
requires = [ "ianitor-ui-proof.service" ];
environment.IANITOR_LOG = "info";
serviceConfig = hardening // {
User = "ianitor-control";
Group = "ianitor";
ExecStart = "${pkg}/bin/ianitor-control --config ${controlToml}";
# After every stop, a crash included: a trial still loaded into Caddy goes back to the
# last good caddy.json at once (ianitor_control::caddy_guard). It runs after a crash
# too, so no separate OnFailure= unit is needed.
ExecStopPost = "${pkg}/bin/ianitor-control caddy-revert --config ${controlToml}";
LoadCredential = loadCreds controlCreds ++ [ "ui-proof:${runProof}/ui-proof" ];
ReadWritePaths = [ stateRoot ];
Restart = "on-failure";
RestartSec = 2;
};
};
systemd.services.ianitor-edge = {
description = "Ianitor edge (Pingora)";
# Never give up restarting the only public listener.
startLimitIntervalSec = 0;
after = [ "network-online.target" "ianitor-control.service" "ianitor-ui-proof.service" ];
wants = [ "network-online.target" ];
requires = [ "ianitor-ui-proof.service" ];
conflicts = [ "caddy-fallback.service" ];
environment.IANITOR_LOG = "info";
serviceConfig = hardening // {
User = "ianitor-edge";
Group = "ianitor";
ExecStart = lib.concatStringsSep " " [
"${pkg}/bin/ianitor-edge"
"--config ${stateRoot}/edge/edge.json"
"--admin-socket /run/ianitor-edge/admin.sock"
"--share-revocations ${stateRoot}/edge/share-revocations.json"
];
LoadCredential = loadCreds edgeCreds ++ [ "ui-proof:${runProof}/ui-proof" ];
RuntimeDirectory = "ianitor-edge";
RuntimeDirectoryMode = "0750";
ReadWritePaths = [ "${stateRoot}/edge-state" "/var/log/ianitor" ];
AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ];
CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ];
# The first start may come before control has written edge.json.
Restart = "always";
RestartSec = 2;
# The Pingora runtime needs W^X off for nothing; keep the default hardening.
LimitNOFILE = 65536;
};
};
systemd.services.caddy-fallback = {
description = "Ianitor fallback: Caddy with the same routes";
after = [ "network-online.target" "ianitor-ui-proof.service" ];
wants = [ "network-online.target" ];
requires = [ "ianitor-ui-proof.service" ];
conflicts = [ "ianitor-edge.service" ];
environment = {
XDG_DATA_HOME = "${stateRoot}/caddy-state";
XDG_CONFIG_HOME = "${stateRoot}/caddy-state";
HOME = "${stateRoot}/caddy-state";
};
serviceConfig = hardening // {
User = "caddy-fallback";
# The admin socket (and its runtime directory) belong to this group; "ianitor" for the
# certificates and logs.
Group = "ianitor-caddy-admin";
SupplementaryGroups = [ "ianitor" ];
ExecStart = "${cfg.caddyPackage}/bin/caddy run --config ${stateRoot}/caddy/caddy.json";
LoadCredential = loadCreds cfg.credentials ++ [ "ui-proof:${runProof}/ui-proof" ];
RuntimeDirectory = "caddy-fallback";
RuntimeDirectoryMode = "0750";
ReadWritePaths = [ "${stateRoot}/caddy-state" "/var/log/ianitor" ];
AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ];
CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ];
# Go needs W^X for its runtime on some platforms.
MemoryDenyWriteExecute = false;
Restart = "on-failure";
RestartSec = 2;
};
};
# The deadline of a trial under Caddy, outside control (a hung control included): once a
# second it reverts a trial past its deadline to the last good caddy.json. Runs with Caddy.
systemd.services.ianitor-caddy-guard = {
description = "Ianitor: deadline for changes tried on Caddy";
partOf = [ "caddy-fallback.service" ];
after = [ "caddy-fallback.service" ];
wantedBy = [ "caddy-fallback.service" ];
environment.IANITOR_LOG = "info";
serviceConfig = hardening // {
User = "ianitor-control";
Group = "ianitor";
ExecStart = "${pkg}/bin/ianitor-control caddy-guard --config ${controlToml}";
ReadWritePaths = [ "${stateRoot}/control" ];
Restart = "always";
RestartSec = 1;
};
};
# At boot: start the engine the UI chose last (ROADMAP §3).
systemd.services.ianitor-engine-select = {
description = "Ianitor: start the chosen engine";
wantedBy = [ "multi-user.target" ];
after = [ "ianitor-control.service" "systemd-tmpfiles-setup.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
};
script = ''
engine=$(cat ${stateRoot}/engine 2>/dev/null || echo ${cfg.defaultEngine})
case "$engine" in
caddy) exec ${config.systemd.package}/bin/systemctl start --no-block caddy-fallback.service ;;
*) exec ${config.systemd.package}/bin/systemctl start --no-block ianitor-edge.service ;;
esac
'';
};
# Control may start and stop exactly the two engine units, nothing else. (polkit is new on a
# server that had no other use for it.)
security.polkit.enable = true;
security.polkit.extraConfig = ''
polkit.addRule(function (action, subject) {
if (action.id == "org.freedesktop.systemd1.manage-units" && subject.user == "ianitor-control") {
var unit = action.lookup("unit");
var verb = action.lookup("verb");
if ((unit == "ianitor-edge.service" || unit == "caddy-fallback.service") &&
(verb == "start" || verb == "stop")) {
return polkit.Result.YES;
}
}
});
'';
networking.firewall.allowedTCPPorts = mkIf cfg.edge.openFirewall (
map (a: lib.toInt (lib.last (lib.splitString ":" a))) [ cfg.edge.httpListen cfg.edge.httpsListen ]
);
};
}