2 Commits

Author SHA1 Message Date
a10c2de01d add cicd
Some checks failed
Release VPS agent / Build and publish Linux agent (push) Failing after 22s
Deploy control plane / Build, push, and deploy production (push) Failing after 22s
2026-09-23 22:46:01 +03:00
0fc35589e6 update 2026-09-22 23:37:05 +03:00
35 changed files with 3359 additions and 248 deletions

View File

@@ -0,0 +1,163 @@
name: Deploy control plane
on:
push:
tags:
- "v*.*.*"
permissions:
contents: read
packages: write
jobs:
deploy-production:
name: Build, push, and deploy production
runs-on: ubuntu-latest
timeout-minutes: 45
env:
REGISTRY_HOST: ${{ vars.REGISTRY_HOST }}
REGISTRY_USERNAME: ${{ vars.REGISTRY_USERNAME }}
DEPLOY_HOST: ${{ vars.DEPLOY_HOST }}
DEPLOY_PORT: ${{ vars.DEPLOY_PORT }}
DEPLOY_USER: ${{ vars.DEPLOY_USER }}
DEPLOY_PATH: ${{ vars.DEPLOY_PATH }}
DEPLOY_PROFILES: ${{ vars.DEPLOY_PROFILES }}
steps:
- name: Checkout tag
uses: https://gitea.com/actions/checkout@v4
with:
fetch-depth: 1
- name: Validate deployment configuration
shell: bash
env:
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
DEPLOY_SSH_KNOWN_HOSTS: ${{ secrets.DEPLOY_SSH_KNOWN_HOSTS }}
run: |
set -Eeuo pipefail
[[ "$GITHUB_REF_NAME" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || {
printf 'invalid deployment tag: %s\n' "$GITHUB_REF_NAME" >&2
exit 1
}
[[ "$REGISTRY_HOST" =~ ^[A-Za-z0-9.-]+(:[0-9]+)?$ ]] || {
printf 'REGISTRY_HOST must be a registry hostname with an optional port\n' >&2
exit 1
}
[[ "$REGISTRY_USERNAME" =~ ^[A-Za-z0-9._@-]+$ ]] || {
printf 'REGISTRY_USERNAME is invalid\n' >&2
exit 1
}
[[ -n "$REGISTRY_PASSWORD" ]] || { printf 'REGISTRY_PASSWORD is missing\n' >&2; exit 1; }
[[ "$DEPLOY_HOST" =~ ^[A-Za-z0-9.-]+$ ]] || { printf 'DEPLOY_HOST is invalid\n' >&2; exit 1; }
DEPLOY_PORT="${DEPLOY_PORT:-22}"
[[ "$DEPLOY_PORT" =~ ^[0-9]{1,5}$ ]] || { printf 'DEPLOY_PORT is invalid\n' >&2; exit 1; }
[[ "$DEPLOY_USER" =~ ^[A-Za-z_][A-Za-z0-9_-]*$ ]] || { printf 'DEPLOY_USER is invalid\n' >&2; exit 1; }
[[ "$DEPLOY_PATH" =~ ^/[A-Za-z0-9._/-]+$ ]] || { printf 'DEPLOY_PATH must be an absolute path without spaces\n' >&2; exit 1; }
[[ -z "$DEPLOY_PROFILES" || "$DEPLOY_PROFILES" == observability ]] || {
printf 'DEPLOY_PROFILES must be empty or observability\n' >&2
exit 1
}
[[ -n "$DEPLOY_SSH_KEY" ]] || { printf 'DEPLOY_SSH_KEY is missing\n' >&2; exit 1; }
[[ -n "$DEPLOY_SSH_KNOWN_HOSTS" ]] || { printf 'DEPLOY_SSH_KNOWN_HOSTS is missing\n' >&2; exit 1; }
repository_name="${GITHUB_REPOSITORY#*/}"
image_prefix="${REGISTRY_HOST}/${GITHUB_REPOSITORY_OWNER}/${repository_name}"
image_prefix="$(printf '%s' "$image_prefix" | tr '[:upper:]' '[:lower:]')"
printf 'DEPLOY_PORT=%s\n' "$DEPLOY_PORT" >> "$GITHUB_ENV"
printf 'IMAGE_PREFIX=%s\n' "$image_prefix" >> "$GITHUB_ENV"
- name: Login to container registry
shell: bash
env:
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
run: |
set -Eeuo pipefail
printf '%s' "$REGISTRY_PASSWORD" | docker login "$REGISTRY_HOST" \
--username "$REGISTRY_USERNAME" \
--password-stdin
- name: Test control plane
shell: bash
run: |
set -Eeuo pipefail
docker build --target test control-plane/backend
docker build --target test control-plane/frontend
- name: Build and push immutable images
shell: bash
run: |
set -Eeuo pipefail
docker build --pull \
--tag "${IMAGE_PREFIX}-backend:${GITHUB_REF_NAME}" \
control-plane/backend
docker build --pull \
--tag "${IMAGE_PREFIX}-frontend:${GITHUB_REF_NAME}" \
control-plane/frontend
docker build --pull \
--tag "${IMAGE_PREFIX}-grafana:${GITHUB_REF_NAME}" \
control-plane/grafana
docker push "${IMAGE_PREFIX}-backend:${GITHUB_REF_NAME}"
docker push "${IMAGE_PREFIX}-frontend:${GITHUB_REF_NAME}"
docker push "${IMAGE_PREFIX}-grafana:${GITHUB_REF_NAME}"
- name: Deploy on production server
shell: bash
env:
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
DEPLOY_SSH_KNOWN_HOSTS: ${{ secrets.DEPLOY_SSH_KNOWN_HOSTS }}
run: |
set -Eeuo pipefail
ssh_directory="$(mktemp -d "${RUNNER_TEMP:-/tmp}/vps-control-ssh.XXXXXX")"
trap 'rm -rf "$ssh_directory"' EXIT
printf '%s\n' "$DEPLOY_SSH_KEY" > "$ssh_directory/id_ed25519"
printf '%s\n' "$DEPLOY_SSH_KNOWN_HOSTS" > "$ssh_directory/known_hosts"
chmod 0700 "$ssh_directory"
chmod 0600 "$ssh_directory/id_ed25519" "$ssh_directory/known_hosts"
ssh_options=(
-i "$ssh_directory/id_ed25519"
-o BatchMode=yes
-o IdentitiesOnly=yes
-o StrictHostKeyChecking=yes
-o "UserKnownHostsFile=$ssh_directory/known_hosts"
-o ConnectTimeout=10
-p "$DEPLOY_PORT"
)
scp_options=(
-i "$ssh_directory/id_ed25519"
-o BatchMode=yes
-o IdentitiesOnly=yes
-o StrictHostKeyChecking=yes
-o "UserKnownHostsFile=$ssh_directory/known_hosts"
-o ConnectTimeout=10
-P "$DEPLOY_PORT"
)
remote="${DEPLOY_USER}@${DEPLOY_HOST}"
ssh "${ssh_options[@]}" "$remote" "mkdir -p '$DEPLOY_PATH'"
scp "${scp_options[@]}" \
control-plane/docker-compose.yml \
"$remote:$DEPLOY_PATH/docker-compose.yml.next"
scp "${scp_options[@]}" \
control-plane/docker-compose.prod.yml \
"$remote:$DEPLOY_PATH/docker-compose.prod.yml.next"
scp "${scp_options[@]}" \
scripts/deploy-control-plane.sh \
"$remote:$DEPLOY_PATH/deploy-control-plane.sh.next"
ssh "${ssh_options[@]}" "$remote" \
"install -m 0644 '$DEPLOY_PATH/docker-compose.yml.next' '$DEPLOY_PATH/docker-compose.yml' && \
install -m 0644 '$DEPLOY_PATH/docker-compose.prod.yml.next' '$DEPLOY_PATH/docker-compose.prod.yml' && \
install -m 0755 '$DEPLOY_PATH/deploy-control-plane.sh.next' '$DEPLOY_PATH/deploy-control-plane.sh' && \
rm -f '$DEPLOY_PATH/docker-compose.yml.next' '$DEPLOY_PATH/docker-compose.prod.yml.next' '$DEPLOY_PATH/deploy-control-plane.sh.next'"
printf '%s\n' "$REGISTRY_PASSWORD" | ssh "${ssh_options[@]}" "$remote" \
"set -eu; \
auth_dir='$DEPLOY_PATH/.docker-ci'; \
trap 'rm -rf \"\$auth_dir\"' EXIT; \
mkdir -p \"\$auth_dir\"; chmod 0700 \"\$auth_dir\"; \
IFS= read -r registry_password; \
printf '%s' \"\$registry_password\" | docker --config \"\$auth_dir\" login '$REGISTRY_HOST' --username '$REGISTRY_USERNAME' --password-stdin; \
cd '$DEPLOY_PATH'; \
CONTROL_PLANE_PROFILES='$DEPLOY_PROFILES' DOCKER_CONFIG=\"\$auth_dir\" ./deploy-control-plane.sh '$GITHUB_REF_NAME' '$IMAGE_PREFIX'"

View File

@@ -0,0 +1,83 @@
name: Release VPS agent
on:
push:
tags:
- "v*.*.*"
permissions:
contents: read
releases: write
jobs:
release-agent:
name: Build and publish Linux agent
runs-on: ubuntu-latest
timeout-minutes: 45
env:
CARGO_TERM_COLOR: always
RUST_TOOLCHAIN: "1.85.1"
CROSS_VERSION: "0.2.5"
steps:
- name: Checkout tag
uses: https://gitea.com/actions/checkout@v4
with:
fetch-depth: 1
- name: Validate tag and package version
shell: bash
run: |
set -Eeuo pipefail
tag="${GITHUB_REF_NAME}"
if [[ ! "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
printf 'invalid release tag: %s\n' "$tag" >&2
exit 1
fi
package_version="$(awk -F ' *= *' '$1 == "version" {gsub(/"/, "", $2); print $2; exit}' agent/Cargo.toml)"
if [[ "v$package_version" != "$tag" ]]; then
printf 'tag %s does not match agent/Cargo.toml version %s\n' "$tag" "$package_version" >&2
exit 1
fi
- name: Prepare Rust and cross
shell: bash
run: |
set -Eeuo pipefail
for command_name in cargo rustup docker curl jq file sha256sum; do
command -v "$command_name" >/dev/null || {
printf 'runner prerequisite is missing: %s\n' "$command_name" >&2
exit 1
}
done
rustup toolchain install "$RUST_TOOLCHAIN" --profile minimal --no-self-update
rustup override set "$RUST_TOOLCHAIN"
cargo install cross --version "$CROSS_VERSION" --locked
docker info >/dev/null
- name: Build static Linux binaries
shell: bash
run: |
set -Eeuo pipefail
cross build --locked --release --manifest-path agent/Cargo.toml --target x86_64-unknown-linux-musl
cross build --locked --release --manifest-path agent/Cargo.toml --target aarch64-unknown-linux-musl
- name: Package and verify assets
shell: bash
run: |
set -Eeuo pipefail
./scripts/package-agent-release.sh \
--output dist \
--amd64 agent/target/x86_64-unknown-linux-musl/release/vps-agent \
--arm64 agent/target/aarch64-unknown-linux-musl/release/vps-agent
file dist/vps-agent-linux-amd64 dist/vps-agent-linux-arm64
grep -q 'statically linked' < <(file -b dist/vps-agent-linux-amd64)
grep -q 'statically linked' < <(file -b dist/vps-agent-linux-arm64)
- name: Publish Gitea release
shell: bash
env:
GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
set -Eeuo pipefail
./scripts/publish-gitea-release.sh "$GITHUB_REF_NAME" dist

View File

@@ -76,4 +76,8 @@ Grafana. Grafana never receives an agent address or agent credential.
## Development
See [docs/development.md](docs/development.md). CI-compatible commands are also
listed in [AGENTS.md](AGENTS.md). This repository is licensed under Apache-2.0.
listed in [AGENTS.md](AGENTS.md), and the tag-based Gitea release pipeline is
documented in [docs/gitea-release.md](docs/gitea-release.md). Production
control-plane delivery is documented in
[docs/gitea-deploy.md](docs/gitea-deploy.md). This repository is licensed under
Apache-2.0.

View File

@@ -35,7 +35,7 @@ and returns liveness only. The complete route table is in
`../docs/architecture.md`. Limits default to 64 KiB bodies, 32 concurrent calls,
five-second requests, 10 read rps, 2 write rps, and burst 20.
System data comes from `/proc` and `/sys`; fixed `ip`, `nft`/`iptables`,
System data comes from `/proc` and `/sys`; fixed `ip`, `iptables`,
`fail2ban-client`, `wg`, and `systemctl` invocations augment it. User input is
never part of a command string. Jail names and IPs are validated, and systemd
names must exactly match the configuration allow-list.
@@ -49,15 +49,17 @@ administrator must opt in after review.
## systemd and privilege
Install `packaging/vps-agent.service`. It caps memory at 64 MiB, CPU at 10%,
Install `packaging/vps-agent.service`, `vps-agent-helper.socket`, and
`vps-agent-helper@.service`. The daemon unit caps memory at 64 MiB, CPU at 10%,
tasks at 64, removes all capabilities, sets `NoNewPrivileges`, and enables
filesystem/kernel/namespace hardening. The agent logs to journald and does not
write successful polls or metrics to disk.
Read APIs work unprivileged on ordinary supported distributions. Process owners
may be absent due to `/proc` permissions. Fail2Ban changes and service restarts
will return an error unless the administrator adds narrowly scoped polkit/sudo
policy; the installer deliberately grants none. Firewall is read-only in v1.
may be absent due to `/proc` permissions. The socket-activated root helper runs
one typed request at a time and has no shell/command endpoint. Writes remain off
until their local allow-lists and `management_enabled` flags are configured.
Firewall persistence requires `iptables-persistent`/`netfilter-persistent`.
## Lifecycle and troubleshooting

View File

@@ -15,13 +15,25 @@ burst = 20.0
command_timeout_seconds = 4
[services]
allowed = ["nginx", "fail2ban", "wg-quick@wg0"]
allowed = ["nginx.service", "fail2ban.service", "wg-quick@wg0.service"]
inventory_limit = 512
install_enabled = false
install_timeout_seconds = 300
packages = { "nginx.service" = "nginx", "fail2ban.service" = "fail2ban" }
[firewall]
management_enabled = false
persistence_enabled = true
allowed_interfaces = []
allowed_sources = []
allowed_ports = []
rollback_timeout_seconds = 60
max_snapshots = 5
[fail2ban]
management_enabled = false
allowed_jails = ["sshd"]
[logging]
level = "info"

View File

@@ -0,0 +1,15 @@
[Unit]
Description=VPS Control privileged helper socket
[Socket]
ListenStream=/run/vps-agent-helper/control.sock
Accept=yes
MaxConnections=1
SocketUser=vps-agent
SocketGroup=vps-agent
SocketMode=0600
DirectoryMode=0750
RemoveOnStop=yes
[Install]
WantedBy=sockets.target

View File

@@ -0,0 +1,26 @@
[Unit]
Description=VPS Control privileged helper request
Documentation=https://github.com/example/vps-control
[Service]
Type=oneshot
ExecStart=/usr/local/bin/vps-agent --privileged-helper --config /etc/vps-agent/config.toml
StandardInput=socket
StandardOutput=socket
StandardError=journal
User=root
Group=root
TimeoutStartSec=330
UMask=0077
PrivateTmp=true
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
ProtectClock=true
ProtectHostname=true
RestrictSUIDSGID=true
LockPersonality=true
RestrictRealtime=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK

View File

@@ -10,7 +10,7 @@ use axum::{
http::{header::AUTHORIZATION, Method, Request, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::{get, post},
routing::{delete, get, post},
Json, Router,
};
use serde_json::{json, Value};
@@ -113,13 +113,22 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/network/listeners", get(network_listeners))
.route("/v1/network/connections", get(network_connections))
.route("/v1/firewall/rules", get(firewall_rules))
.route("/v1/firewall/rules", post(firewall_add))
.route("/v1/firewall/rules/:id", delete(firewall_delete))
.route(
"/v1/firewall/transactions/:id/confirm",
post(firewall_confirm),
)
.route("/v1/rate-limits", get(rate_limits).post(rate_limit_add))
.route("/v1/rate-limits/:id", delete(rate_limit_delete))
.route("/v1/fail2ban/status", get(fail2ban_status))
.route("/v1/fail2ban/jails/:jail", get(fail2ban_jail))
.route("/v1/fail2ban/ban", post(fail2ban_ban))
.route("/v1/fail2ban/unban", post(fail2ban_unban))
.route("/v1/fail2ban/configure", post(fail2ban_configure))
.route("/v1/wireguard/status", get(wireguard_status))
.route("/v1/services", get(service_list))
.route("/v1/services/:name/restart", post(service_restart))
.route("/v1/services/:name/:operation", post(service_mutation))
.route("/v1/logs", get(log_entries))
.layer(DefaultBodyLimit::max(max_body))
.layer(middleware::from_fn_with_state(
@@ -286,11 +295,74 @@ async fn network_connections(
}
async fn firewall_rules(State(state): State<Arc<AppState>>) -> Json<firewall::FirewallStatus> {
Json(firewall::status(command_timeout(&state)).await)
Json(firewall::status(&state.config, command_timeout(&state)).await)
}
async fn firewall_add(
State(state): State<Arc<AppState>>,
Json(request): Json<firewall::AddRuleRequest>,
) -> Result<Json<Value>, ApiError> {
let transaction_id = firewall::add(&state.config, request, command_timeout(&state)).await?;
tracing::info!("managed firewall rule added");
Ok(Json(
json!({"status":"pending_confirmation","transaction_id":transaction_id}),
))
}
async fn firewall_delete(
State(state): State<Arc<AppState>>,
Path(id): Path<String>,
) -> Result<Json<Value>, ApiError> {
let transaction_id = firewall::delete(&state.config, &id, command_timeout(&state)).await?;
tracing::info!(rule_id = id, "managed firewall rule deleted");
Ok(Json(
json!({"status":"pending_confirmation","transaction_id":transaction_id}),
))
}
async fn rate_limits(State(state): State<Arc<AppState>>) -> Json<Vec<firewall::FirewallRule>> {
let mut rules = firewall::status(&state.config, command_timeout(&state))
.await
.rules;
rules.retain(|rule| rule.rate_limit && rule.managed);
Json(rules)
}
async fn rate_limit_add(
State(state): State<Arc<AppState>>,
Json(request): Json<firewall::RateLimitRequest>,
) -> Result<Json<Value>, ApiError> {
let transaction_id =
firewall::add_rate_limit(&state.config, request, command_timeout(&state)).await?;
tracing::info!("managed L4 rate-limit policy added");
Ok(Json(
json!({"status":"pending_confirmation","transaction_id":transaction_id}),
))
}
async fn rate_limit_delete(
State(state): State<Arc<AppState>>,
Path(id): Path<String>,
) -> Result<Json<Value>, ApiError> {
let transaction_id =
firewall::delete_rate_limit(&state.config, &id, command_timeout(&state)).await?;
tracing::info!(policy_id = id, "managed L4 rate-limit policy deleted");
Ok(Json(
json!({"status":"pending_confirmation","transaction_id":transaction_id}),
))
}
async fn firewall_confirm(
State(state): State<Arc<AppState>>,
Path(id): Path<String>,
) -> Result<Json<Value>, ApiError> {
firewall::confirm(&id, command_timeout(&state)).await?;
tracing::info!(transaction_id = id, "firewall transaction confirmed");
Ok(Json(json!({"status":"ok"})))
}
async fn fail2ban_status(State(state): State<Arc<AppState>>) -> Json<fail2ban::Status> {
Json(fail2ban::status(command_timeout(&state)).await)
Json(fail2ban::status(&state.config, command_timeout(&state)).await)
}
async fn fail2ban_jail(
@@ -326,7 +398,7 @@ async fn mutate_ban(
.ip
.parse::<std::net::IpAddr>()
.map_err(|_| ApiError::bad_request("invalid IP address"))?;
fail2ban::ban(&request, unban, command_timeout(state)).await?;
fail2ban::ban(&state.config, &request, unban, command_timeout(state)).await?;
let action = if unban { "unban" } else { "ban" };
tracing::info!(
action,
@@ -337,6 +409,15 @@ async fn mutate_ban(
Ok(Json(json!({"status": "ok"})))
}
async fn fail2ban_configure(
State(state): State<Arc<AppState>>,
Json(request): Json<fail2ban::ConfigureRequest>,
) -> Result<Json<Value>, ApiError> {
fail2ban::configure(&state.config, request, command_timeout(&state)).await?;
tracing::info!("managed Fail2Ban configuration updated");
Ok(Json(json!({"status":"ok"})))
}
async fn wireguard_status(
State(state): State<Arc<AppState>>,
) -> Result<Json<Vec<wireguard::Interface>>, ApiError> {
@@ -344,33 +425,34 @@ async fn wireguard_status(
}
async fn service_list(State(state): State<Arc<AppState>>) -> Json<Vec<services::ServiceStatus>> {
Json(services::list(&state.config.services.allowed, command_timeout(&state)).await)
Json(services::list(&state.config.services, command_timeout(&state)).await)
}
async fn service_restart(
async fn service_mutation(
State(state): State<Arc<AppState>>,
Path(name): Path<String>,
Path((name, operation)): Path<(String, String)>,
) -> Result<Json<Value>, ApiError> {
if !state
.config
.services
.allowed
.iter()
.any(|item| item == &name)
{
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"service is not allow-listed",
"not_allowed",
));
}
services::restart(
if operation == "install" {
services::install(
&name,
&state.config.services.allowed,
&state.config.services,
Duration::from_secs(state.config.services.install_timeout_seconds),
)
.await?;
} else {
services::action(
&name,
&operation,
&state.config.services,
command_timeout(&state),
)
.await?;
tracing::info!(service = name, "allow-listed service restarted");
}
tracing::info!(
service = name,
operation,
"allow-listed service mutation completed"
);
Ok(Json(json!({"status": "ok"})))
}

View File

@@ -1,6 +1,6 @@
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use std::{net::SocketAddr, path::Path};
use std::{collections::HashMap, net::SocketAddr, path::Path};
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
@@ -10,6 +10,7 @@ pub struct Config {
pub limits: Limits,
pub services: Services,
pub firewall: Firewall,
pub fail2ban: Fail2Ban,
pub logging: Logging,
pub telemetry: Telemetry,
pub logs: Logs,
@@ -41,20 +42,35 @@ pub struct Limits {
pub command_timeout_seconds: u64,
}
#[derive(Clone, Debug, Default, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Services {
pub allowed: Vec<String>,
pub inventory_limit: usize,
pub install_enabled: bool,
pub install_timeout_seconds: u64,
pub packages: HashMap<String, String>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Firewall {
pub management_enabled: bool,
pub persistence_enabled: bool,
pub allowed_interfaces: Vec<String>,
pub allowed_sources: Vec<String>,
pub allowed_ports: Vec<u16>,
pub rollback_timeout_seconds: u64,
pub max_snapshots: usize,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Fail2Ban {
pub management_enabled: bool,
pub allowed_jails: Vec<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Logging {
@@ -118,10 +134,35 @@ impl Default for Limits {
}
}
impl Default for Services {
fn default() -> Self {
Self {
allowed: Vec::new(),
inventory_limit: 512,
install_enabled: false,
install_timeout_seconds: 300,
packages: HashMap::new(),
}
}
}
impl Default for Fail2Ban {
fn default() -> Self {
Self {
management_enabled: false,
allowed_jails: vec!["sshd".into()],
}
}
}
impl Default for Firewall {
fn default() -> Self {
Self {
management_enabled: false,
persistence_enabled: true,
allowed_interfaces: Vec::new(),
allowed_sources: Vec::new(),
allowed_ports: Vec::new(),
rollback_timeout_seconds: 60,
max_snapshots: 5,
}
@@ -190,6 +231,9 @@ impl Config {
if self.services.allowed.len() > 128 {
bail!("at most 128 services may be allow-listed")
}
if !(1..=2048).contains(&self.services.inventory_limit) {
bail!("services.inventory_limit must be between 1 and 2048")
}
if self.logs.allowed_units.len() > 128
|| !(1..=1000).contains(&self.logs.max_entries_per_request)
|| !(1024..=65_536).contains(&self.logs.max_message_bytes)
@@ -209,8 +253,68 @@ impl Config {
bail!("invalid allow-listed service name")
}
}
if self.firewall.management_enabled {
bail!("firewall management requires the v2 privileged helper and is unavailable")
if !(30..=1800).contains(&self.services.install_timeout_seconds) {
bail!("services.install_timeout_seconds must be between 30 and 1800")
}
if self.services.packages.len() > 128 {
bail!("at most 128 service packages may be configured")
}
for (service, package) in &self.services.packages {
if !self.services.allowed.iter().any(|name| name == service)
|| !valid_package_name(package)
{
bail!("invalid service package mapping")
}
}
if self.services.install_enabled && self.services.packages.is_empty() {
bail!("services.packages must not be empty when installation is enabled")
}
if self.firewall.allowed_interfaces.len() > 32
|| self.firewall.allowed_sources.len() > 128
|| self.firewall.allowed_ports.len() > 512
{
bail!("firewall allow-list is too large")
}
for interface in &self.firewall.allowed_interfaces {
if !valid_interface_name(interface) {
bail!("invalid firewall interface")
}
}
for source in &self.firewall.allowed_sources {
if !valid_cidr(source)
|| !source
.split_once('/')
.and_then(|(address, _)| address.parse::<std::net::IpAddr>().ok())
.is_some_and(|address| address.is_ipv4())
{
bail!("invalid IPv4 firewall source CIDR")
}
}
if self.firewall.allowed_ports.contains(&0) {
bail!("firewall ports must be between 1 and 65535")
}
if self.firewall.management_enabled
&& (self.firewall.allowed_interfaces.is_empty()
|| self.firewall.allowed_sources.is_empty()
|| self.firewall.allowed_ports.is_empty())
{
bail!("firewall allow-lists must not be empty when management is enabled")
}
if !(10..=300).contains(&self.firewall.rollback_timeout_seconds)
|| !(1..=20).contains(&self.firewall.max_snapshots)
{
bail!("firewall rollback or snapshot limits are invalid")
}
if self.fail2ban.allowed_jails.len() > 64 {
bail!("at most 64 Fail2Ban jails may be allow-listed")
}
for jail in &self.fail2ban.allowed_jails {
if !valid_simple_name(jail) {
bail!("invalid allow-listed Fail2Ban jail")
}
}
if self.fail2ban.management_enabled && self.fail2ban.allowed_jails.is_empty() {
bail!("fail2ban.allowed_jails must not be empty when management is enabled")
}
if !matches!(
self.logging.level.as_str(),
@@ -235,6 +339,43 @@ pub fn valid_service_name(name: &str) -> bool {
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.' | b'@' | b':'))
}
pub fn valid_simple_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.'))
}
pub fn valid_package_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 128
&& name.bytes().all(|c| {
c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, b'+' | b'.' | b'-')
})
}
pub fn valid_interface_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 15
&& name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.'))
}
pub fn valid_cidr(value: &str) -> bool {
let Some((address, prefix)) = value.split_once('/') else {
return false;
};
let Ok(address) = address.parse::<std::net::IpAddr>() else {
return false;
};
let Ok(prefix) = prefix.parse::<u8>() else {
return false;
};
prefix <= if address.is_ipv4() { 32 } else { 128 }
}
#[cfg(test)]
mod tests {
use super::*;
@@ -260,4 +401,15 @@ mod tests {
assert!(!valid_service_name("nginx;reboot"));
assert!(!valid_service_name("../../etc/passwd"));
}
#[test]
fn validates_privileged_allow_lists() {
assert!(valid_package_name("nginx-core"));
assert!(!valid_package_name("nginx;reboot"));
assert!(valid_interface_name("wg-home"));
assert!(!valid_interface_name("../../eth0"));
assert!(valid_cidr("192.168.50.4/32"));
assert!(valid_cidr("2001:db8::/64"));
assert!(!valid_cidr("192.168.50.4/99"));
}
}

View File

@@ -1,4 +1,4 @@
use crate::command;
use crate::{command, config::Config, privileged};
use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use std::{net::IpAddr, time::Duration};
@@ -9,6 +9,9 @@ pub struct Status {
pub running: bool,
pub version: Option<String>,
pub jails: Vec<String>,
pub jail_statuses: Vec<JailStatus>,
pub management_enabled: bool,
pub manageable_jails: Vec<String>,
}
#[derive(Debug, Default, Serialize, PartialEq)]
@@ -28,7 +31,7 @@ pub struct BanRequest {
pub ip: String,
}
pub async fn status(timeout: Duration) -> Status {
pub async fn status(config: &Config, timeout: Duration) -> Status {
let version = match command::run("fail2ban-client", &["--version"], timeout).await {
Ok(output) => Some(output.stdout.trim().to_owned()),
Err(_) => {
@@ -37,21 +40,47 @@ pub async fn status(timeout: Duration) -> Status {
running: false,
version: None,
jails: vec![],
jail_statuses: vec![],
management_enabled: false,
manageable_jails: config.fail2ban.allowed_jails.clone(),
}
}
};
match command::run("fail2ban-client", &["status"], timeout).await {
Ok(output) => Status {
Ok(output) => {
let jails = parse_jail_list(&output.stdout);
let mut jail_statuses = Vec::new();
let mut tasks = tokio::task::JoinSet::new();
for name in jails.iter().take(64) {
let name = name.clone();
tasks.spawn(async move { jail(&name, timeout).await });
}
while let Some(result) = tasks.join_next().await {
if let Ok(Ok(status)) = result {
jail_statuses.push(status);
}
}
jail_statuses.sort_by(|left, right| left.jail.cmp(&right.jail));
Status {
installed: true,
running: true,
version,
jails: parse_jail_list(&output.stdout),
},
jails,
jail_statuses,
management_enabled: config.fail2ban.management_enabled
&& privileged::socket_available(),
manageable_jails: config.fail2ban.allowed_jails.clone(),
}
}
Err(_) => Status {
installed: true,
running: false,
version,
jails: vec![],
jail_statuses: vec![],
management_enabled: config.fail2ban.management_enabled
&& privileged::socket_available(),
manageable_jails: config.fail2ban.allowed_jails.clone(),
},
}
}
@@ -62,21 +91,71 @@ pub async fn jail(name: &str, timeout: Duration) -> Result<JailStatus> {
Ok(parse_jail_status(name, &output.stdout))
}
pub async fn ban(request: &BanRequest, unban: bool, timeout: Duration) -> Result<()> {
pub async fn ban(
config: &Config,
request: &BanRequest,
unban: bool,
timeout: Duration,
) -> Result<()> {
validate_jail(&request.jail)?;
let ip: IpAddr = request
.ip
.parse()
.map_err(|_| anyhow::anyhow!("invalid IP address"))?;
let operation = if unban { "unbanip" } else { "banip" };
command::run(
"fail2ban-client",
&[
"set",
request.jail.as_str(),
operation,
ip.to_string().as_str(),
],
if !config
.fail2ban
.allowed_jails
.iter()
.any(|value| value == &request.jail)
{
bail!("jail is not allow-listed")
}
privileged::call(
&privileged::Request::Fail2BanAction {
jail: request.jail.clone(),
ip: ip.to_string(),
operation: if unban { "unban".into() } else { "ban".into() },
},
timeout,
)
.await?;
Ok(())
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConfigureRequest {
pub jail: String,
pub enabled: bool,
pub bantime_seconds: u32,
pub findtime_seconds: u32,
pub maxretry: u16,
}
pub async fn configure(
config: &Config,
request: ConfigureRequest,
timeout: Duration,
) -> Result<()> {
validate_jail(&request.jail)?;
if !config
.fail2ban
.allowed_jails
.iter()
.any(|value| value == &request.jail)
{
bail!("jail is not allow-listed")
}
privileged::call(
&privileged::Request::Fail2BanConfigure {
settings: privileged::Fail2BanSettings {
jail: request.jail,
enabled: request.enabled,
bantime_seconds: request.bantime_seconds,
findtime_seconds: request.findtime_seconds,
maxretry: request.maxretry,
},
},
timeout,
)
.await?;

View File

@@ -1,68 +1,379 @@
use crate::command;
use serde::Serialize;
use serde_json::Value;
use crate::{command, config::Config, privileged};
use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use std::time::Duration;
pub const MANAGED_CHAIN: &str = "VPS_CONTROL_INPUT";
pub const RATE_CHAIN: &str = "VPS_CONTROL_RATE";
#[derive(Debug, Serialize)]
pub struct FirewallStatus {
pub backend: String,
pub management_enabled: bool,
pub managed_table: String,
pub ruleset: Value,
pub persistence_enabled: bool,
pub managed_chain: String,
pub allowed_interfaces: Vec<String>,
pub allowed_sources: Vec<String>,
pub allowed_ports: Vec<u16>,
pub rules: Vec<FirewallRule>,
pub warning: Option<String>,
}
pub async fn status(timeout: Duration) -> FirewallStatus {
if command::run("nft", &["--version"], timeout).await.is_ok() {
return match command::run("nft", &["--json", "list", "ruleset"], timeout).await {
Ok(output) => FirewallStatus {
backend: "nftables".into(),
management_enabled: false,
managed_table: "inet vps_control".into(),
ruleset: serde_json::from_str(&output.stdout).unwrap_or(Value::Null),
warning: None,
},
Err(error) => FirewallStatus {
backend: "nftables".into(),
management_enabled: false,
managed_table: "inet vps_control".into(),
ruleset: Value::Null,
warning: Some(format!("rules unavailable: {error}")),
},
};
#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct FirewallRule {
pub id: String,
pub table: String,
pub chain: String,
pub protocol: String,
pub source: String,
pub destination: String,
pub in_interface: String,
pub out_interface: String,
pub destination_port: Option<u16>,
pub target: String,
pub packets: u64,
pub bytes: u64,
pub comment: String,
pub managed: bool,
pub rate_limit: bool,
}
for (program, backend) in [
("iptables-nft", "iptables-nft"),
("iptables", "iptables-legacy"),
] {
if let Ok(version) = command::run(program, &["--version"], timeout).await {
let detected = if version.stdout.contains("nf_tables") {
"iptables-nft"
} else {
backend
};
let rules = command::run(program, &["-S"], timeout)
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AddRuleRequest {
pub interface: String,
pub source: String,
pub protocol: String,
pub port: u16,
pub target: String,
#[serde(default)]
pub comment: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RateLimitRequest {
pub interface: String,
pub source: String,
pub protocol: String,
pub port: u16,
pub rate_per_second: u32,
pub burst: u32,
#[serde(default)]
pub comment: String,
}
pub async fn status(config: &Config, timeout: Duration) -> FirewallStatus {
let helper_available = privileged::socket_available();
let management_enabled = config.firewall.management_enabled && helper_available;
let dump = if helper_available {
privileged::call(&privileged::Request::FirewallDump, timeout)
.await
.ok()
.map(|v| v.stdout);
return FirewallStatus {
backend: detected.into(),
management_enabled: false,
managed_table: "inet vps_control".into(),
ruleset: rules.map(Value::String).unwrap_or(Value::Null),
warning: Some(
"legacy-compatible firewall view is read-only and has limited structure".into(),
),
.and_then(|response| response.data)
.and_then(|value| value.as_str().map(str::to_owned))
} else {
command::run("iptables-save", &["-c"], timeout)
.await
.ok()
.map(|output| output.stdout)
};
match dump {
Some(text) => FirewallStatus {
backend: "iptables".into(),
management_enabled,
persistence_enabled: config.firewall.persistence_enabled,
managed_chain: MANAGED_CHAIN.into(),
allowed_interfaces: config.firewall.allowed_interfaces.clone(),
allowed_sources: config.firewall.allowed_sources.clone(),
allowed_ports: config.firewall.allowed_ports.clone(),
rules: parse_iptables_save(&text),
warning: if config.firewall.management_enabled && !helper_available {
Some("privileged helper socket is unavailable; writes are disabled".into())
} else {
None
},
},
None => FirewallStatus {
backend: "unavailable".into(),
management_enabled: false,
persistence_enabled: config.firewall.persistence_enabled,
managed_chain: MANAGED_CHAIN.into(),
allowed_interfaces: config.firewall.allowed_interfaces.clone(),
allowed_sources: config.firewall.allowed_sources.clone(),
allowed_ports: config.firewall.allowed_ports.clone(),
rules: Vec::new(),
warning: Some("iptables-save is unavailable or access was denied".into()),
},
}
}
FirewallStatus {
backend: "unavailable".into(),
management_enabled: false,
managed_table: "inet vps_control".into(),
ruleset: Value::Null,
warning: Some("no supported firewall userspace utility found".into()),
pub async fn add(config: &Config, request: AddRuleRequest, timeout: Duration) -> Result<String> {
validate_common(
config,
&request.interface,
&request.source,
&request.protocol,
request.port,
)?;
if !matches!(request.target.as_str(), "ACCEPT" | "DROP" | "REJECT") {
bail!("target must be ACCEPT, DROP, or REJECT")
}
let response = privileged::call(
&privileged::Request::FirewallAdd {
rule: privileged::FirewallRuleRequest {
interface: request.interface,
source: request.source,
protocol: request.protocol,
port: request.port,
target: request.target,
comment: request.comment,
},
},
timeout,
)
.await?;
transaction_id(response)
}
pub async fn delete(config: &Config, id: &str, timeout: Duration) -> Result<String> {
if !config.firewall.management_enabled || !valid_id(id) {
bail!("firewall management disabled or invalid rule id")
}
let response = privileged::call(
&privileged::Request::FirewallDelete { id: id.into() },
timeout,
)
.await?;
transaction_id(response)
}
pub async fn add_rate_limit(
config: &Config,
request: RateLimitRequest,
timeout: Duration,
) -> Result<String> {
validate_common(
config,
&request.interface,
&request.source,
&request.protocol,
request.port,
)?;
if !(1..=100_000).contains(&request.rate_per_second) || !(1..=10_000).contains(&request.burst) {
bail!("rate_per_second or burst is outside the supported range")
}
let response = privileged::call(
&privileged::Request::RateLimitAdd {
policy: privileged::RateLimitRequest {
interface: request.interface,
source: request.source,
protocol: request.protocol,
port: request.port,
rate_per_second: request.rate_per_second,
burst: request.burst,
comment: request.comment,
},
},
timeout,
)
.await?;
transaction_id(response)
}
pub async fn delete_rate_limit(config: &Config, id: &str, timeout: Duration) -> Result<String> {
if !config.firewall.management_enabled || !valid_id(id) {
bail!("policy management disabled or invalid policy id")
}
let response = privileged::call(
&privileged::Request::RateLimitDelete { id: id.into() },
timeout,
)
.await?;
transaction_id(response)
}
pub async fn confirm(id: &str, timeout: Duration) -> Result<()> {
if !valid_id(id) {
bail!("invalid transaction id")
}
privileged::call(
&privileged::Request::FirewallConfirm { id: id.into() },
timeout,
)
.await?;
Ok(())
}
fn transaction_id(response: privileged::Response) -> Result<String> {
let id = response
.data
.and_then(|value| {
value
.get("transaction_id")
.and_then(|value| value.as_str())
.map(str::to_owned)
})
.ok_or_else(|| anyhow::anyhow!("helper did not return a transaction id"))?;
if !valid_id(&id) {
bail!("helper returned an invalid transaction id")
}
Ok(id)
}
fn validate_common(
config: &Config,
interface: &str,
source: &str,
protocol: &str,
port: u16,
) -> Result<()> {
if !config.firewall.management_enabled {
bail!("firewall management is disabled")
}
if !config
.firewall
.allowed_interfaces
.iter()
.any(|value| value == interface)
|| !config
.firewall
.allowed_sources
.iter()
.any(|value| value == source)
|| !config.firewall.allowed_ports.contains(&port)
|| !matches!(protocol, "tcp" | "udp")
{
bail!("firewall request is outside the configured allow-list")
}
Ok(())
}
pub fn valid_id(value: &str) -> bool {
value.len() == 16 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
}
fn parse_iptables_save(text: &str) -> Vec<FirewallRule> {
let mut table = "filter".to_owned();
let mut result = Vec::new();
for (index, line) in text.lines().enumerate() {
if let Some(name) = line.strip_prefix('*') {
table = name.to_owned();
continue;
}
if let Some(definition) = line.strip_prefix(':') {
let fields: Vec<_> = definition.split_whitespace().collect();
if fields.len() >= 3 {
let (packets, bytes) = fields[2]
.strip_prefix('[')
.and_then(|value| value.strip_suffix(']'))
.and_then(|value| value.split_once(':'))
.map(|(left, right)| (left.parse().unwrap_or(0), right.parse().unwrap_or(0)))
.unwrap_or((0, 0));
result.push(FirewallRule {
id: format!("policy-{}-{}", table, fields[0]),
table: table.clone(),
chain: fields[0].into(),
protocol: "all".into(),
source: "all".into(),
destination: "all".into(),
in_interface: String::new(),
out_interface: String::new(),
destination_port: None,
target: format!("POLICY {}", fields[1]),
packets,
bytes,
comment: String::new(),
managed: false,
rate_limit: false,
});
}
continue;
}
if !line.contains(" -A ") && !line.starts_with("-A ") {
continue;
}
let tokens = split_arguments(line);
let chain = option(&tokens, "-A").unwrap_or_default();
let comment = option(&tokens, "--comment").unwrap_or_default();
let counters = tokens
.first()
.and_then(|token| token.strip_prefix('['))
.and_then(|token| token.strip_suffix(']'));
let (packets, bytes) = counters
.and_then(|value| value.split_once(':'))
.map(|(a, b)| (a.parse().unwrap_or(0), b.parse().unwrap_or(0)))
.unwrap_or((0, 0));
let managed = matches!(chain.as_str(), MANAGED_CHAIN | RATE_CHAIN)
&& comment.starts_with("vps-control:");
let id = comment
.strip_prefix("vps-control:")
.and_then(|value| value.split(':').next())
.filter(|value| valid_id(value))
.map(str::to_owned)
.unwrap_or_else(|| format!("rule-{index}"));
result.push(FirewallRule {
id,
table: table.clone(),
chain: chain.clone(),
protocol: option(&tokens, "-p").unwrap_or_else(|| "all".into()),
source: option(&tokens, "-s").unwrap_or_else(|| "0.0.0.0/0".into()),
destination: option(&tokens, "-d").unwrap_or_else(|| "0.0.0.0/0".into()),
in_interface: option(&tokens, "-i").unwrap_or_default(),
out_interface: option(&tokens, "-o").unwrap_or_default(),
destination_port: option(&tokens, "--dport").and_then(|value| value.parse().ok()),
target: option(&tokens, "-j").unwrap_or_default(),
packets,
bytes,
rate_limit: tokens.iter().any(|token| token == "hashlimit") || chain == RATE_CHAIN,
comment,
managed,
});
}
result
}
fn option(tokens: &[String], name: &str) -> Option<String> {
tokens
.iter()
.position(|token| token == name)
.and_then(|index| tokens.get(index + 1))
.cloned()
}
fn split_arguments(line: &str) -> Vec<String> {
let mut result = Vec::new();
let mut current = String::new();
let mut quoted = false;
for character in line.chars() {
match character {
'"' => quoted = !quoted,
' ' | '\t' if !quoted => {
if !current.is_empty() {
result.push(std::mem::take(&mut current));
}
}
_ => current.push(character),
}
}
if !current.is_empty() {
result.push(current);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_structured_rules_and_counters() {
let input = "*filter\n[12:840] -A INPUT -i wg0 -s 10.20.0.0/24 -p tcp -m tcp --dport 9105 -j ACCEPT\n[3:180] -A VPS_CONTROL_INPUT -i wg0 -s 10.20.0.2/32 -p tcp --dport 22 -m comment --comment \"vps-control:0123456789abcdef:ssh\" -j ACCEPT\nCOMMIT\n";
let rules = parse_iptables_save(input);
assert_eq!(rules.len(), 2);
assert_eq!(rules[0].packets, 12);
assert_eq!(rules[0].destination_port, Some(9105));
assert!(rules[1].managed);
assert_eq!(rules[1].id, "0123456789abcdef");
}
}

View File

@@ -5,6 +5,7 @@ mod fail2ban;
mod firewall;
mod logs;
mod network;
mod privileged;
mod services;
mod system;
mod wireguard;
@@ -17,7 +18,14 @@ use tracing_subscriber::EnvFilter;
#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() -> Result<()> {
let config_path = parse_args()?;
let arguments = parse_args()?;
if arguments.privileged_helper {
return privileged::serve_once(&arguments.config_path);
}
if let Some(transaction) = arguments.firewall_rollback {
return privileged::rollback_firewall(&arguments.config_path, &transaction);
}
let config_path = arguments.config_path;
let config = Config::load(&config_path)?;
tracing_subscriber::fmt()
.with_env_filter(
@@ -54,9 +62,17 @@ async fn main() -> Result<()> {
Ok(())
}
fn parse_args() -> Result<PathBuf> {
struct Arguments {
config_path: PathBuf,
privileged_helper: bool,
firewall_rollback: Option<String>,
}
fn parse_args() -> Result<Arguments> {
let mut args = env::args().skip(1);
let mut config = PathBuf::from("/etc/vps-agent/config.toml");
let mut privileged_helper = false;
let mut firewall_rollback = None;
while let Some(argument) = args.next() {
match argument.as_str() {
"--config" => {
@@ -65,6 +81,10 @@ fn parse_args() -> Result<PathBuf> {
.map(PathBuf::from)
.context("--config needs a path")?
}
"--privileged-helper" => privileged_helper = true,
"--firewall-rollback" => {
firewall_rollback = Some(args.next().context("--firewall-rollback needs an id")?)
}
"--version" | "-V" => {
println!("vps-agent {}", env!("CARGO_PKG_VERSION"));
std::process::exit(0);
@@ -76,7 +96,11 @@ fn parse_args() -> Result<PathBuf> {
_ => anyhow::bail!("unknown argument: {argument}"),
}
}
Ok(config)
Ok(Arguments {
config_path: config,
privileged_helper,
firewall_rollback,
})
}
async fn wait_for_shutdown() {

915
agent/src/privileged.rs Normal file
View File

@@ -0,0 +1,915 @@
use crate::config::{valid_interface_name, valid_service_name, valid_simple_name, Config};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{
fs::{self, OpenOptions},
io::{BufRead, BufReader, Read, Write},
os::unix::fs::OpenOptionsExt,
path::{Path, PathBuf},
process::{Command, Stdio},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::UnixStream,
};
pub const SOCKET_PATH: &str = "/run/vps-agent-helper/control.sock";
const MANAGED_CHAIN: &str = "VPS_CONTROL_INPUT";
const MAX_MESSAGE_BYTES: usize = 64 * 1024;
const MAX_SNAPSHOT_BYTES: usize = 2 * 1024 * 1024;
const SNAPSHOT_DIRECTORY: &str = "/var/lib/vps-agent/firewall";
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum Request {
FirewallDump,
FirewallAdd {
rule: FirewallRuleRequest,
},
FirewallDelete {
id: String,
},
FirewallConfirm {
id: String,
},
RateLimitAdd {
policy: RateLimitRequest,
},
RateLimitDelete {
id: String,
},
ServiceInstall {
service: String,
},
ServiceAction {
service: String,
operation: String,
},
Fail2BanAction {
jail: String,
ip: String,
operation: String,
},
Fail2BanConfigure {
settings: Fail2BanSettings,
},
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FirewallRuleRequest {
pub interface: String,
pub source: String,
pub protocol: String,
pub port: u16,
pub target: String,
#[serde(default)]
pub comment: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RateLimitRequest {
pub interface: String,
pub source: String,
pub protocol: String,
pub port: u16,
pub rate_per_second: u32,
pub burst: u32,
#[serde(default)]
pub comment: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Fail2BanSettings {
pub jail: String,
pub enabled: bool,
pub bantime_seconds: u32,
pub findtime_seconds: u32,
pub maxretry: u16,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Response {
pub ok: bool,
pub changed: bool,
pub error: Option<String>,
pub data: Option<Value>,
}
impl Response {
fn success(changed: bool) -> Self {
Self {
ok: true,
changed,
error: None,
data: None,
}
}
fn with_data(data: Value) -> Self {
Self {
ok: true,
changed: false,
error: None,
data: Some(data),
}
}
fn transaction(id: &str) -> Self {
Self {
ok: true,
changed: true,
error: None,
data: Some(serde_json::json!({"transaction_id": id})),
}
}
fn failure(error: impl Into<String>) -> Self {
Self {
ok: false,
changed: false,
error: Some(error.into()),
data: None,
}
}
}
pub async fn call(request: &Request, timeout_duration: Duration) -> Result<Response> {
tokio::time::timeout(timeout_duration, async {
let mut stream = UnixStream::connect(SOCKET_PATH)
.await
.context("connect privileged helper")?;
let mut payload = serde_json::to_vec(request).context("encode helper request")?;
if payload.len() > MAX_MESSAGE_BYTES - 1 {
bail!("helper request is too large")
}
payload.push(b'\n');
stream
.write_all(&payload)
.await
.context("write helper request")?;
stream.shutdown().await.context("finish helper request")?;
let mut response = Vec::new();
stream
.take((MAX_MESSAGE_BYTES + 1) as u64)
.read_to_end(&mut response)
.await
.context("read helper response")?;
if response.len() > MAX_MESSAGE_BYTES {
bail!("helper response is too large")
}
let response: Response =
serde_json::from_slice(&response).context("decode helper response")?;
if !response.ok {
bail!(
"privileged helper: {}",
response.error.as_deref().unwrap_or("operation failed")
)
}
Ok(response)
})
.await
.context("privileged helper timed out")?
}
pub fn serve_once(config_path: &Path) -> Result<()> {
let uid = Command::new("id")
.arg("-u")
.output()
.context("determine helper uid")?;
if !uid.status.success() || String::from_utf8_lossy(&uid.stdout).trim() != "0" {
bail!("privileged helper must run as root")
}
let response = match read_request().and_then(|request| execute(config_path, request)) {
Ok(response) => response,
Err(error) => Response::failure(format!("{error:#}")),
};
serde_json::to_writer(std::io::stdout().lock(), &response).context("write helper response")?;
Ok(())
}
fn read_request() -> Result<Request> {
let mut reader = BufReader::new(std::io::stdin().lock()).take((MAX_MESSAGE_BYTES + 1) as u64);
let mut payload = Vec::new();
reader.read_until(b'\n', &mut payload)?;
if payload.len() > MAX_MESSAGE_BYTES {
bail!("helper request is too large")
}
serde_json::from_slice(&payload).context("decode helper request")
}
fn execute(config_path: &Path, request: Request) -> Result<Response> {
let config = Config::load(config_path)?;
match request {
Request::FirewallDump => dump_firewall(),
Request::FirewallAdd { rule } => add_firewall_rule(&config, &rule),
Request::FirewallDelete { id } => delete_managed_rule(&config, MANAGED_CHAIN, &id),
Request::FirewallConfirm { id } => confirm_firewall(&id),
Request::RateLimitAdd { policy } => add_rate_limit(&config, &policy),
Request::RateLimitDelete { id } => delete_managed_rule(&config, "VPS_CONTROL_RATE", &id),
Request::ServiceInstall { service } => install_service(&config, &service),
Request::ServiceAction { service, operation } => {
service_action(&config, &service, &operation)
}
Request::Fail2BanAction {
jail,
ip,
operation,
} => fail2ban_action(&config, &jail, &ip, &operation),
Request::Fail2BanConfigure { settings } => configure_fail2ban(&config, &settings),
}
}
fn dump_firewall() -> Result<Response> {
let output = Command::new("iptables-save")
.arg("-c")
.output()
.context("execute iptables-save")?;
if !output.status.success() || output.stdout.len() > MAX_SNAPSHOT_BYTES {
bail!("iptables-save failed or exceeded size limit")
}
let rules = String::from_utf8(output.stdout).context("iptables-save output is not UTF-8")?;
Ok(Response::with_data(Value::String(rules)))
}
fn add_firewall_rule(config: &Config, rule: &FirewallRuleRequest) -> Result<Response> {
if !config.firewall.management_enabled {
bail!("firewall management is disabled")
}
if !valid_interface_name(&rule.interface)
|| !config
.firewall
.allowed_interfaces
.iter()
.any(|value| value == &rule.interface)
{
bail!("interface is not allow-listed")
}
if !config
.firewall
.allowed_sources
.iter()
.any(|value| value == &rule.source)
{
bail!("source is not allow-listed")
}
if !matches!(rule.protocol.as_str(), "tcp" | "udp") {
bail!("protocol must be tcp or udp")
}
if !matches!(rule.target.as_str(), "ACCEPT" | "DROP" | "REJECT") {
bail!("unsupported firewall target")
}
if rule.port == 0 || !config.firewall.allowed_ports.contains(&rule.port) {
bail!("port is not allow-listed")
}
if rule.comment.len() > 80
|| !rule
.comment
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b' ' | b'.' | b'_' | b'-'))
{
bail!("comment contains unsupported characters")
}
let (transaction, snapshot) = prepare_firewall_transaction(config)?;
let result = apply_firewall_rule(rule).and_then(|changed| {
if config.firewall.persistence_enabled {
run_status("netfilter-persistent", &["save"])
.context("persist firewall with netfilter-persistent")?;
}
if !changed {
bail!("firewall rule was not changed")
}
Ok(Response::transaction(&transaction))
});
rollback_on_error(result, &transaction, &snapshot, config)
}
fn apply_firewall_rule(rule: &FirewallRuleRequest) -> Result<bool> {
if !command_succeeds("iptables", &["-w", "5", "-S", MANAGED_CHAIN]) {
run_status("iptables", &["-w", "5", "-N", MANAGED_CHAIN])?;
}
if !command_succeeds("iptables", &["-w", "5", "-C", "INPUT", "-j", MANAGED_CHAIN]) {
run_status(
"iptables",
&["-w", "5", "-I", "INPUT", "1", "-j", MANAGED_CHAIN],
)?;
}
let port = rule.port.to_string();
let id = random_id()?;
let suffix = if rule.comment.is_empty() {
format!("{}-{}", rule.protocol, rule.port)
} else {
rule.comment.clone()
};
let comment = format!("vps-control:{id}:{suffix}");
let arguments = [
"-w",
"5",
"-C",
MANAGED_CHAIN,
"-i",
&rule.interface,
"-s",
&rule.source,
"-p",
&rule.protocol,
"--dport",
&port,
"-m",
"conntrack",
"--ctstate",
"NEW,ESTABLISHED",
"-m",
"comment",
"--comment",
&comment,
"-j",
&rule.target,
];
if command_succeeds("iptables", &arguments) {
return Ok(false);
}
let mut append_arguments = arguments;
append_arguments[2] = "-A";
run_status("iptables", &append_arguments)?;
Ok(true)
}
fn add_rate_limit(config: &Config, policy: &RateLimitRequest) -> Result<Response> {
validate_firewall_common(
config,
&policy.interface,
&policy.source,
&policy.protocol,
policy.port,
&policy.comment,
)?;
if !(1..=100_000).contains(&policy.rate_per_second) || !(1..=10_000).contains(&policy.burst) {
bail!("rate limit is outside the supported range")
}
let (transaction, snapshot) = prepare_firewall_transaction(config)?;
let result = apply_rate_limit(policy).and_then(|changed| {
persist_if_enabled(config)?;
if !changed {
bail!("rate-limit policy was not changed")
}
Ok(Response::transaction(&transaction))
});
rollback_on_error(result, &transaction, &snapshot, config)
}
fn apply_rate_limit(policy: &RateLimitRequest) -> Result<bool> {
const CHAIN: &str = "VPS_CONTROL_RATE";
ensure_chain(CHAIN, 1)?;
let id = random_id()?;
let suffix = if policy.comment.is_empty() {
format!("{}-{}", policy.protocol, policy.port)
} else {
policy.comment.clone()
};
let allow_comment = format!("vps-control:{id}:rate:{suffix}");
let drop_comment = format!("vps-control:{id}:rate-drop:{suffix}");
let port = policy.port.to_string();
let rate = format!("{}/second", policy.rate_per_second);
let burst = policy.burst.to_string();
let hash_name = format!("vp_{}", &id[..12]);
run_status(
"iptables",
&[
"-w",
"5",
"-A",
CHAIN,
"-i",
&policy.interface,
"-s",
&policy.source,
"-p",
&policy.protocol,
"--dport",
&port,
"-m",
"conntrack",
"--ctstate",
"NEW",
"-m",
"hashlimit",
"--hashlimit-upto",
&rate,
"--hashlimit-burst",
&burst,
"--hashlimit-mode",
"srcip",
"--hashlimit-name",
&hash_name,
"-m",
"comment",
"--comment",
&allow_comment,
"-j",
"ACCEPT",
],
)?;
if let Err(error) = run_status(
"iptables",
&[
"-w",
"5",
"-A",
CHAIN,
"-i",
&policy.interface,
"-s",
&policy.source,
"-p",
&policy.protocol,
"--dport",
&port,
"-m",
"conntrack",
"--ctstate",
"NEW",
"-m",
"comment",
"--comment",
&drop_comment,
"-j",
"DROP",
],
) {
let _ = delete_rules_by_comment(CHAIN, &id);
return Err(error);
}
Ok(true)
}
fn delete_managed_rule(config: &Config, chain: &str, id: &str) -> Result<Response> {
if !config.firewall.management_enabled || !valid_id(id) {
bail!("firewall management disabled or invalid rule id")
}
if !matches!(chain, MANAGED_CHAIN | "VPS_CONTROL_RATE") {
bail!("unmanaged chain")
}
let (transaction, snapshot) = prepare_firewall_transaction(config)?;
let result = delete_rules_by_comment(chain, id).and_then(|changed| {
persist_if_enabled(config)?;
if !changed {
bail!("managed rule was not found")
}
Ok(Response::transaction(&transaction))
});
rollback_on_error(result, &transaction, &snapshot, config)
}
fn delete_rules_by_comment(chain: &str, id: &str) -> Result<bool> {
let output = Command::new("iptables")
.args(["-w", "5", "-S", chain])
.output()
.context("list managed firewall chain")?;
if !output.status.success() {
bail!("list managed firewall chain failed")
}
let marker = format!("vps-control:{id}:");
let text = String::from_utf8(output.stdout).context("iptables output is not UTF-8")?;
let mut matches: Vec<Vec<String>> = text
.lines()
.filter(|line| line.contains(&marker))
.map(split_command_line)
.collect();
let changed = !matches.is_empty();
matches.reverse();
for mut arguments in matches {
if arguments.first().map(String::as_str) != Some("-A") {
bail!("unexpected managed firewall rule")
}
arguments[0] = "-D".into();
let references: Vec<&str> = arguments.iter().map(String::as_str).collect();
run_status("iptables", &[&["-w", "5"], references.as_slice()].concat())?;
}
Ok(changed)
}
fn ensure_chain(chain: &str, input_position: u8) -> Result<()> {
if !command_succeeds("iptables", &["-w", "5", "-S", chain]) {
run_status("iptables", &["-w", "5", "-N", chain])?;
}
if !command_succeeds("iptables", &["-w", "5", "-C", "INPUT", "-j", chain]) {
let position = input_position.to_string();
run_status(
"iptables",
&["-w", "5", "-I", "INPUT", &position, "-j", chain],
)?;
}
Ok(())
}
fn validate_firewall_common(
config: &Config,
interface: &str,
source: &str,
protocol: &str,
port: u16,
comment: &str,
) -> Result<()> {
if !config.firewall.management_enabled
|| !valid_interface_name(interface)
|| !config
.firewall
.allowed_interfaces
.iter()
.any(|value| value == interface)
|| !config
.firewall
.allowed_sources
.iter()
.any(|value| value == source)
|| !config.firewall.allowed_ports.contains(&port)
|| !matches!(protocol, "tcp" | "udp")
{
bail!("firewall request is outside the configured allow-list")
}
if comment.len() > 80
|| !comment
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b' ' | b'.' | b'_' | b'-'))
{
bail!("comment contains unsupported characters")
}
Ok(())
}
fn service_action(config: &Config, service: &str, operation: &str) -> Result<Response> {
if !valid_service_name(service) || !config.services.allowed.iter().any(|value| value == service)
{
bail!("service is not allow-listed")
}
match operation {
"start" | "stop" | "restart" | "enable" | "disable" => {}
_ => bail!("unsupported service operation"),
}
if matches!(operation, "start" | "stop" | "restart") {
run_status("systemctl", &[operation, "--no-block", "--", service])?;
} else {
run_status("systemctl", &[operation, "--", service])?;
}
Ok(Response::success(true))
}
fn fail2ban_action(config: &Config, jail: &str, ip: &str, operation: &str) -> Result<Response> {
if !config.fail2ban.management_enabled
|| !valid_simple_name(jail)
|| !config
.fail2ban
.allowed_jails
.iter()
.any(|value| value == jail)
{
bail!("Fail2Ban jail is not allow-listed")
}
let address: std::net::IpAddr = ip.parse().context("invalid IP address")?;
let command = match operation {
"ban" => "banip",
"unban" => "unbanip",
_ => bail!("unsupported Fail2Ban operation"),
};
run_status(
"fail2ban-client",
&["set", jail, command, &address.to_string()],
)?;
Ok(Response::success(true))
}
fn configure_fail2ban(config: &Config, settings: &Fail2BanSettings) -> Result<Response> {
if !config.fail2ban.management_enabled
|| !valid_simple_name(&settings.jail)
|| !config
.fail2ban
.allowed_jails
.iter()
.any(|value| value == &settings.jail)
|| !(10..=2_592_000).contains(&settings.bantime_seconds)
|| !(10..=86_400).contains(&settings.findtime_seconds)
|| !(1..=100).contains(&settings.maxretry)
{
bail!("invalid or non-allow-listed Fail2Ban settings")
}
let directory = Path::new("/etc/fail2ban/jail.d");
fs::create_dir_all(directory).context("create Fail2Ban jail directory")?;
let path = directory.join(format!("vps-control-{}.local", settings.jail));
let backup = fs::read(&path).ok();
let temporary = directory.join(format!(".vps-control-{}.tmp", settings.jail));
let content = format!(
"# Managed by VPS Control; manual changes will be replaced.\n[{}]\nenabled = {}\nbantime = {}\nfindtime = {}\nmaxretry = {}\n",
settings.jail,
if settings.enabled { "true" } else { "false" },
settings.bantime_seconds,
settings.findtime_seconds,
settings.maxretry
);
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o644)
.open(&temporary)?;
file.write_all(content.as_bytes())?;
file.sync_all()?;
fs::rename(&temporary, &path)?;
if let Err(error) = run_status("fail2ban-client", &["-t"])
.and_then(|_| run_status("systemctl", &["reload", "fail2ban.service"]))
{
match backup {
Some(previous) => fs::write(&path, previous)?,
None => {
let _ = fs::remove_file(&path);
}
}
let _ = run_status("systemctl", &["reload", "fail2ban.service"]);
bail!("Fail2Ban validation failed and configuration was rolled back: {error:#}")
}
Ok(Response::success(true))
}
fn persist_if_enabled(config: &Config) -> Result<()> {
if config.firewall.persistence_enabled {
run_status("netfilter-persistent", &["save"])
.context("persist firewall with netfilter-persistent")?;
}
Ok(())
}
fn prepare_firewall_transaction(config: &Config) -> Result<(String, PathBuf)> {
if fs::read_dir(SNAPSHOT_DIRECTORY)
.ok()
.into_iter()
.flatten()
.filter_map(Result::ok)
.any(|entry| entry.file_name().to_string_lossy().starts_with("pending-"))
{
bail!("another firewall transaction is pending confirmation")
}
let snapshot = create_snapshot(config.firewall.max_snapshots)?;
let id = random_id()?;
let pending = Path::new(SNAPSHOT_DIRECTORY).join(format!("pending-{id}.rules"));
fs::rename(&snapshot, &pending).context("mark firewall snapshot pending")?;
let unit = format!("vps-agent-firewall-rollback-{id}");
let delay = format!("{}s", config.firewall.rollback_timeout_seconds);
let status = Command::new("systemd-run")
.args([
"--unit",
&unit,
"--on-active",
&delay,
"--timer-property=AccuracySec=1s",
"/usr/local/bin/vps-agent",
"--firewall-rollback",
&id,
"--config",
"/etc/vps-agent/config.toml",
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.context("schedule firewall safety rollback")?;
if !status.success() {
let _ = fs::remove_file(&pending);
bail!("firewall safety rollback could not be scheduled")
}
Ok((id, pending))
}
fn confirm_firewall(id: &str) -> Result<Response> {
if !valid_id(id) {
bail!("invalid firewall transaction id")
}
let pending = Path::new(SNAPSHOT_DIRECTORY).join(format!("pending-{id}.rules"));
if !pending.is_file() {
bail!("firewall transaction is not pending")
}
cancel_rollback(id);
fs::remove_file(pending).context("remove confirmed firewall snapshot")?;
Ok(Response::success(true))
}
pub fn rollback_firewall(config_path: &Path, id: &str) -> Result<()> {
if !valid_id(id) {
bail!("invalid firewall transaction id")
}
let config = Config::load(config_path)?;
let pending = Path::new(SNAPSHOT_DIRECTORY).join(format!("pending-{id}.rules"));
if !pending.is_file() {
return Ok(());
}
restore_snapshot(&pending)?;
persist_if_enabled(&config)?;
fs::remove_file(pending)?;
Ok(())
}
fn cancel_rollback(id: &str) {
let timer = format!("vps-agent-firewall-rollback-{id}.timer");
let service = format!("vps-agent-firewall-rollback-{id}.service");
let _ = command_succeeds("systemctl", &["stop", &timer]);
let _ = command_succeeds("systemctl", &["stop", &service]);
}
fn rollback_on_error(
result: Result<Response>,
transaction: &str,
snapshot: &Path,
config: &Config,
) -> Result<Response> {
match result {
Ok(response) => Ok(response),
Err(error) => {
cancel_rollback(transaction);
if let Err(rollback_error) = restore_snapshot(snapshot) {
bail!("operation failed: {error:#}; rollback failed: {rollback_error:#}")
}
let _ = persist_if_enabled(config);
let _ = fs::remove_file(snapshot);
bail!("operation failed and was rolled back: {error:#}")
}
}
}
fn random_id() -> Result<String> {
let mut bytes = [0_u8; 8];
fs::File::open("/dev/urandom")?.read_exact(&mut bytes)?;
Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
}
fn valid_id(value: &str) -> bool {
value.len() == 16 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
}
fn split_command_line(line: &str) -> Vec<String> {
let mut values = Vec::new();
let mut value = String::new();
let mut quoted = false;
for character in line.chars() {
match character {
'"' => quoted = !quoted,
' ' | '\t' if !quoted => {
if !value.is_empty() {
values.push(std::mem::take(&mut value));
}
}
_ => value.push(character),
}
}
if !value.is_empty() {
values.push(value);
}
values
}
fn install_service(config: &Config, service: &str) -> Result<Response> {
if !config.services.install_enabled {
bail!("service installation is disabled")
}
if !valid_service_name(service) || !config.services.allowed.iter().any(|item| item == service) {
bail!("service is not allow-listed")
}
let package = config
.services
.packages
.get(service)
.context("service has no package mapping")?;
let unit = format!("vps-agent-install-{}.service", random_id()?);
let timeout_seconds = format!("{}s", config.services.install_timeout_seconds);
let runtime_property = format!("RuntimeMaxSec={timeout_seconds}");
let status = Command::new("systemd-run")
.args([
"--unit",
&unit,
"--collect",
"--no-block",
"--property",
&runtime_property,
"--setenv=DEBIAN_FRONTEND=noninteractive",
"/usr/bin/apt-get",
"-q",
"-y",
"--no-install-recommends",
"-o",
"DPkg::Lock::Timeout=30",
"install",
package,
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.context("queue allow-listed package installation")?;
if !status.success() {
bail!("package installation could not be queued")
}
Ok(Response::success(true))
}
fn create_snapshot(maximum: usize) -> Result<PathBuf> {
fs::create_dir_all(SNAPSHOT_DIRECTORY).context("create firewall snapshot directory")?;
let output = Command::new("iptables-save")
.arg("-c")
.output()
.context("execute iptables-save")?;
if !output.status.success() || output.stdout.len() > MAX_SNAPSHOT_BYTES {
bail!("iptables snapshot failed or exceeded size limit")
}
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
let path = Path::new(SNAPSHOT_DIRECTORY).join(format!("snapshot-{timestamp}.rules"));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&path)
.context("create firewall snapshot")?;
file.write_all(&output.stdout)?;
file.sync_all()?;
prune_snapshots(maximum)?;
Ok(path)
}
fn prune_snapshots(maximum: usize) -> Result<()> {
let mut snapshots: Vec<_> = fs::read_dir(SNAPSHOT_DIRECTORY)?
.filter_map(Result::ok)
.filter(|entry| entry.file_name().to_string_lossy().starts_with("snapshot-"))
.collect();
snapshots.sort_by_key(|entry| entry.file_name());
let remove_count = snapshots.len().saturating_sub(maximum);
for entry in snapshots.into_iter().take(remove_count) {
fs::remove_file(entry.path())?;
}
Ok(())
}
fn restore_snapshot(path: &Path) -> Result<()> {
let file = fs::File::open(path).context("open firewall snapshot")?;
let mut child = Command::new("iptables-restore")
.arg("-c")
.stdin(Stdio::from(file))
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.context("execute iptables-restore")?;
if !child.wait()?.success() {
bail!("iptables-restore failed")
}
Ok(())
}
fn command_succeeds(program: &str, arguments: &[&str]) -> bool {
Command::new(program)
.args(arguments)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|status| status.success())
}
fn run_status(program: &str, arguments: &[&str]) -> Result<()> {
let status = Command::new(program)
.args(arguments)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.with_context(|| format!("execute {program}"))?;
if !status.success() {
bail!("{program} failed")
}
Ok(())
}
pub fn socket_available() -> bool {
Path::new(SOCKET_PATH).exists()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn helper_request_rejects_unknown_fields() {
let payload = br#"{"action":"firewall_add","rule":{"interface":"wg0","source":"10.0.0.1/32","protocol":"tcp","port":22,"extra":true}}"#;
assert!(serde_json::from_slice::<Request>(payload).is_err());
}
#[test]
fn helper_request_is_typed() {
let payload = br#"{"action":"service_install","service":"nginx.service"}"#;
assert!(matches!(
serde_json::from_slice::<Request>(payload).unwrap(),
Request::ServiceInstall { .. }
));
}
}

View File

@@ -1,4 +1,8 @@
use crate::{command, config::valid_service_name};
use crate::{
command,
config::{valid_service_name, Services},
privileged,
};
use anyhow::{bail, Result};
use serde::Serialize;
use std::{collections::HashMap, time::Duration};
@@ -6,100 +10,190 @@ use std::{collections::HashMap, time::Duration};
#[derive(Debug, Serialize)]
pub struct ServiceStatus {
pub name: String,
pub load_state: String,
pub active_state: String,
pub sub_state: String,
pub pid: u32,
pub memory_bytes: Option<u64>,
pub active_since_monotonic_us: Option<u64>,
pub description: String,
pub unit_file_state: String,
pub managed: bool,
pub install_available: bool,
}
pub async fn list(allowed: &[String], timeout: Duration) -> Vec<ServiceStatus> {
let mut result = Vec::with_capacity(allowed.len());
for name in allowed {
match inspect(name, timeout).await {
Ok(status) => result.push(status),
Err(_) => result.push(ServiceStatus {
name: name.clone(),
active_state: "unavailable".into(),
sub_state: "unknown".into(),
pid: 0,
memory_bytes: None,
active_since_monotonic_us: None,
}),
}
}
result
}
pub async fn restart(name: &str, allowed: &[String], timeout: Duration) -> Result<()> {
if !valid_service_name(name) || !allowed.iter().any(|item| item == name) {
bail!("service is not allow-listed")
}
command::run("systemctl", &["restart", "--", name], timeout).await?;
Ok(())
}
async fn inspect(name: &str, timeout: Duration) -> Result<ServiceStatus> {
if !valid_service_name(name) {
bail!("invalid service name")
}
let output = command::run(
pub async fn list(config: &Services, timeout: Duration) -> Vec<ServiceStatus> {
let units_future = command::run(
"systemctl",
&[
"show",
"list-units",
"--type=service",
"--all",
"--no-legend",
"--no-pager",
"--property=ActiveState,SubState,MainPID,MemoryCurrent,ActiveEnterTimestampMonotonic",
"--",
name,
"--plain",
],
timeout,
);
let files_future = command::run(
"systemctl",
&[
"list-unit-files",
"--type=service",
"--no-legend",
"--no-pager",
],
timeout,
);
let (units_output, files_output) = tokio::join!(units_future, files_future);
let unit_files = files_output
.ok()
.map(|output| parse_unit_files(&output.stdout))
.unwrap_or_default();
let mut rows = match units_output {
Ok(output) => parse_units(&output.stdout, config),
Err(_) => Vec::new(),
};
for row in &mut rows {
row.unit_file_state = unit_files
.get(&row.name)
.cloned()
.unwrap_or_else(|| "unknown".into());
}
for (name, state) in &unit_files {
if !rows.iter().any(|item| &item.name == name) {
let managed = config.allowed.iter().any(|item| item == name);
rows.push(ServiceStatus {
name: name.clone(),
load_state: "loaded".into(),
active_state: "inactive".into(),
sub_state: "dead".into(),
description: "Installed unit file".into(),
unit_file_state: state.clone(),
managed,
install_available: false,
});
}
}
for name in &config.allowed {
if !rows.iter().any(|item| &item.name == name) {
rows.push(ServiceStatus {
name: name.clone(),
load_state: "not-found".into(),
active_state: "inactive".into(),
sub_state: "dead".into(),
description: config
.packages
.get(name)
.map(|package| format!("Not installed (package: {package})"))
.unwrap_or_else(|| "Not installed".into()),
unit_file_state: "not-found".into(),
managed: true,
install_available: config.install_enabled && config.packages.contains_key(name),
});
}
}
rows.sort_by(|left, right| {
right
.managed
.cmp(&left.managed)
.then_with(|| left.name.cmp(&right.name))
});
rows.truncate(config.inventory_limit);
rows
}
pub async fn action(
name: &str,
operation: &str,
config: &Services,
timeout: Duration,
) -> Result<()> {
validate_managed(name, config)?;
if !matches!(
operation,
"start" | "stop" | "restart" | "enable" | "disable"
) {
bail!("unsupported service operation")
}
privileged::call(
&privileged::Request::ServiceAction {
service: name.into(),
operation: operation.into(),
},
timeout,
)
.await?;
let values: HashMap<_, _> = output
.stdout
.lines()
.filter_map(|line| line.split_once('='))
.collect();
Ok(ServiceStatus {
name: name.to_owned(),
active_state: values
.get("ActiveState")
.copied()
.unwrap_or("unknown")
.to_owned(),
sub_state: values
.get("SubState")
.copied()
.unwrap_or("unknown")
.to_owned(),
pid: values
.get("MainPID")
.and_then(|v| v.parse().ok())
.unwrap_or_default(),
memory_bytes: values.get("MemoryCurrent").and_then(|v| v.parse().ok()),
active_since_monotonic_us: values
.get("ActiveEnterTimestampMonotonic")
.and_then(|v| v.parse().ok()),
Ok(())
}
pub async fn install(name: &str, config: &Services, timeout: Duration) -> Result<()> {
validate_managed(name, config)?;
if !config.install_enabled || !config.packages.contains_key(name) {
bail!("service installation is disabled or unavailable")
}
privileged::call(
&privileged::Request::ServiceInstall {
service: name.into(),
},
timeout,
)
.await?;
Ok(())
}
fn validate_managed(name: &str, config: &Services) -> Result<()> {
if !valid_service_name(name) || !config.allowed.iter().any(|item| item == name) {
bail!("service is not allow-listed")
}
Ok(())
}
fn parse_units(text: &str, config: &Services) -> Vec<ServiceStatus> {
text.lines()
.filter_map(|line| {
let mut fields = line.split_whitespace();
let name = fields.next()?.trim_start_matches(['●', ' ']).to_owned();
let load_state = fields.next()?.to_owned();
let active_state = fields.next()?.to_owned();
let sub_state = fields.next()?.to_owned();
let description = fields.collect::<Vec<_>>().join(" ");
let managed = config.allowed.iter().any(|item| item == &name);
Some(ServiceStatus {
install_available: managed
&& config.install_enabled
&& config.packages.contains_key(&name),
name,
load_state,
active_state,
sub_state,
description,
unit_file_state: "unknown".into(),
managed,
})
})
.collect()
}
fn parse_unit_files(text: &str) -> HashMap<String, String> {
text.lines()
.filter_map(|line| {
let mut fields = line.split_whitespace();
Some((fields.next()?.to_owned(), fields.next()?.to_owned()))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn rejects_service_outside_allowlist_without_execution() {
assert!(
restart("postgresql", &["nginx".into()], Duration::from_secs(1))
.await
.is_err()
);
assert!(restart(
"nginx;reboot",
&["nginx;reboot".into()],
Duration::from_secs(1)
)
.await
.is_err());
#[test]
fn parses_systemd_inventory() {
let config = Services {
allowed: vec!["nginx.service".into()],
..Services::default()
};
let rows = parse_units("nginx.service loaded active running A web server\nssh.service loaded inactive dead SSH daemon\n", &config);
assert_eq!(rows.len(), 2);
assert!(rows[0].managed);
assert_eq!(rows[0].description, "A web server");
}
}

View File

@@ -45,8 +45,8 @@ Roles are Viewer (read), Operator (Fail2Ban and service actions), and
Administrator (server/firewall/policy administration). Every current mutation
is audited with actor, target, result, time, and source IP. Secrets are excluded.
The backend creates schema on startup. One-minute metric samples are retained 30
days (`METRICS_RETENTION=720h`) and agent logs seven days
The backend creates schema on startup. One-minute metric and connection samples
are retained 30 days (`METRICS_RETENTION=720h`); agent logs and Fail2Ban history seven days
(`LOGS_RETENTION=168h`). PostgreSQL is the only durable history store.
## Grafana and Loki-compatible access

View File

@@ -7,6 +7,10 @@ COPY . .
RUN --mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/control-plane .
FROM build AS test
RUN --mount=type=cache,target=/root/.cache/go-build go test ./...
RUN --mount=type=cache,target=/root/.cache/go-build go vet ./...
FROM alpine:3.22
RUN apk add --no-cache ca-certificates tzdata && \
addgroup -S -g 65532 control && adduser -S -D -H -u 65532 -G control control
@@ -14,4 +18,3 @@ COPY --from=build --chown=65532:65532 /out/control-plane /usr/local/bin/control-
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/usr/local/bin/control-plane"]

View File

@@ -127,6 +127,9 @@ func (client *AgentClient) Do(ctx context.Context, server Server, method, path s
if err != nil {
return 0, nil, err
}
if method != http.MethodGet && method != http.MethodHead {
request.Close = true
}
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Accept", "application/json")
if len(body) > 0 {

View File

@@ -5,6 +5,7 @@ import (
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
@@ -275,6 +276,7 @@ func (app *App) serverRoute(writer http.ResponseWriter, request *http.Request, u
"listeners": "/v1/network/listeners", "connections": "/v1/network/connections",
"firewall": "/v1/firewall/rules", "fail2ban": "/v1/fail2ban/status",
"wireguard": "/v1/wireguard/status", "services": "/v1/services",
"rate-limits": "/v1/rate-limits",
}
if len(parts) == 2 && request.Method == http.MethodGet {
if parts[1] == "metrics" {
@@ -295,6 +297,25 @@ func (app *App) serverRoute(writer http.ResponseWriter, request *http.Request, u
writeJSON(writer, 200, entries)
return
}
if parts[1] == "connection-history" {
hours := queryHours(request, 24, 24*30)
history, historyErr := app.store.ConnectionHistory(request.Context(), server.ID, time.Now().Add(-time.Duration(hours)*time.Hour))
if historyErr != nil {
writeInternal(writer, historyErr)
return
}
writeJSON(writer, 200, history)
return
}
if parts[1] == "fail2ban-history" {
events, eventErr := app.store.Fail2BanEvents(request.Context(), server.ID, queryLimit(request, 200, 1000))
if eventErr != nil {
writeInternal(writer, eventErr)
return
}
writeJSON(writer, 200, events)
return
}
if agentPath, found := readRoutes[parts[1]]; found {
app.proxyRead(writer, request, server, agentPath)
return
@@ -311,11 +332,51 @@ func (app *App) serverRoute(writer http.ResponseWriter, request *http.Request, u
app.fail2banMutation(writer, request, user, server, parts[2])
return
}
if len(parts) == 4 && request.Method == http.MethodPost && parts[1] == "services" && parts[3] == "restart" && validServiceName(parts[2]) {
if !app.authorize(writer, request, user, csrfHash, RoleOperator) {
if len(parts) == 3 && request.Method == http.MethodPost && parts[1] == "fail2ban" && parts[2] == "configure" {
if !app.authorize(writer, request, user, csrfHash, RoleAdministrator) {
return
}
app.serviceMutation(writer, request, user, server, parts[2])
app.fail2banConfigure(writer, request, user, server)
return
}
if len(parts) == 4 && request.Method == http.MethodPost && parts[1] == "services" && validServiceName(parts[2]) {
operation := parts[3]
requiredRole := RoleOperator
if operation == "install" {
requiredRole = RoleAdministrator
}
if !app.authorize(writer, request, user, csrfHash, requiredRole) {
return
}
app.serviceMutation(writer, request, user, server, parts[2], operation)
return
}
if len(parts) == 3 && parts[1] == "firewall" && parts[2] == "rules" && request.Method == http.MethodPost {
if !app.authorize(writer, request, user, csrfHash, RoleAdministrator) {
return
}
app.firewallAdd(writer, request, user, server)
return
}
if len(parts) == 4 && parts[1] == "firewall" && parts[2] == "rules" && request.Method == http.MethodDelete {
if !app.authorize(writer, request, user, csrfHash, RoleAdministrator) {
return
}
app.managedDelete(writer, request, user, server, "firewall", parts[3])
return
}
if len(parts) == 2 && parts[1] == "rate-limits" && request.Method == http.MethodPost {
if !app.authorize(writer, request, user, csrfHash, RoleAdministrator) {
return
}
app.rateLimitAdd(writer, request, user, server)
return
}
if len(parts) == 3 && parts[1] == "rate-limits" && request.Method == http.MethodDelete {
if !app.authorize(writer, request, user, csrfHash, RoleAdministrator) {
return
}
app.managedDelete(writer, request, user, server, "rate-limits", parts[2])
return
}
writeError(writer, 404, "not found", "not_found")
@@ -352,18 +413,25 @@ func (app *App) fail2banMutation(writer http.ResponseWriter, request *http.Reque
writeError(writer, 502, "agent unavailable", "agent_unavailable")
return
}
if status < 300 {
app.store.AddFail2BanEvent(request.Context(), server.ID, input.Jail, input.IP, action, "operator")
}
writeAgentResponse(writer, status, response)
}
func (app *App) serviceMutation(writer http.ResponseWriter, request *http.Request, user User, server Server, name string) {
func (app *App) serviceMutation(writer http.ResponseWriter, request *http.Request, user User, server Server, name, operation string) {
if !contains([]string{"start", "stop", "restart", "enable", "disable", "install"}, operation) {
writeError(writer, 400, "invalid service operation", "invalid_request")
return
}
status, response, err := app.agent.Do(request.Context(), server, http.MethodPost,
"/v1/services/"+url.PathEscape(name)+"/restart", []byte("{}"))
"/v1/services/"+url.PathEscape(name)+"/"+operation, []byte("{}"))
result := "success"
if err != nil || status >= 300 {
result = "failure"
}
app.store.Audit(request.Context(), &user, server.ID, "service.restart", name, nil,
map[string]string{"requested": "restart"}, result, app.clientIP(request))
app.store.Audit(request.Context(), &user, server.ID, "service."+operation, name, nil,
map[string]string{"requested": operation}, result, app.clientIP(request))
if err != nil {
writeError(writer, 502, "agent unavailable", "agent_unavailable")
return
@@ -371,6 +439,141 @@ func (app *App) serviceMutation(writer http.ResponseWriter, request *http.Reques
writeAgentResponse(writer, status, response)
}
func (app *App) firewallAdd(writer http.ResponseWriter, request *http.Request, user User, server Server) {
var input struct {
Interface string `json:"interface"`
Source string `json:"source"`
Protocol string `json:"protocol"`
Port int `json:"port"`
Target string `json:"target"`
Comment string `json:"comment"`
}
if decodeJSON(writer, request, &input) != nil || !validInterface(input.Interface) || !validIPv4CIDR(input.Source) || !contains([]string{"tcp", "udp"}, input.Protocol) || input.Port < 1 || input.Port > 65535 || !contains([]string{"ACCEPT", "DROP", "REJECT"}, input.Target) || !validComment(input.Comment) {
writeError(writer, 400, "invalid firewall rule", "invalid_request")
return
}
app.forwardMutation(writer, request, user, server, "firewall.add", fmt.Sprintf("%s/%s:%d", input.Source, input.Protocol, input.Port), "/v1/firewall/rules", http.MethodPost, input)
}
func (app *App) rateLimitAdd(writer http.ResponseWriter, request *http.Request, user User, server Server) {
var input struct {
Interface string `json:"interface"`
Source string `json:"source"`
Protocol string `json:"protocol"`
Port int `json:"port"`
Rate int `json:"rate_per_second"`
Burst int `json:"burst"`
Comment string `json:"comment"`
}
if decodeJSON(writer, request, &input) != nil || !validInterface(input.Interface) || !validIPv4CIDR(input.Source) || !contains([]string{"tcp", "udp"}, input.Protocol) || input.Port < 1 || input.Port > 65535 || input.Rate < 1 || input.Rate > 100000 || input.Burst < 1 || input.Burst > 10000 || !validComment(input.Comment) {
writeError(writer, 400, "invalid rate-limit policy", "invalid_request")
return
}
app.forwardMutation(writer, request, user, server, "rate_limit.add", fmt.Sprintf("%s/%s:%d", input.Source, input.Protocol, input.Port), "/v1/rate-limits", http.MethodPost, input)
}
func (app *App) managedDelete(writer http.ResponseWriter, request *http.Request, user User, server Server, kind, id string) {
if len(id) != 16 {
writeError(writer, 400, "invalid managed object id", "invalid_request")
return
}
for _, character := range id {
if !((character >= '0' && character <= '9') || (character >= 'a' && character <= 'f') || (character >= 'A' && character <= 'F')) {
writeError(writer, 400, "invalid managed object id", "invalid_request")
return
}
}
path := "/v1/firewall/rules/" + id
action := "firewall.delete"
if kind == "rate-limits" {
path = "/v1/rate-limits/" + id
action = "rate_limit.delete"
}
app.forwardMutation(writer, request, user, server, action, id, path, http.MethodDelete, map[string]string{"id": id})
}
func (app *App) fail2banConfigure(writer http.ResponseWriter, request *http.Request, user User, server Server) {
var input struct {
Jail string `json:"jail"`
Enabled bool `json:"enabled"`
BanTime int `json:"bantime_seconds"`
FindTime int `json:"findtime_seconds"`
MaxRetry int `json:"maxretry"`
}
if decodeJSON(writer, request, &input) != nil || !validSimpleName(input.Jail) || input.BanTime < 10 || input.BanTime > 2592000 || input.FindTime < 10 || input.FindTime > 86400 || input.MaxRetry < 1 || input.MaxRetry > 100 {
writeError(writer, 400, "invalid Fail2Ban settings", "invalid_request")
return
}
app.forwardMutation(writer, request, user, server, "fail2ban.configure", input.Jail, "/v1/fail2ban/configure", http.MethodPost, input)
}
func (app *App) forwardMutation(writer http.ResponseWriter, request *http.Request, user User, server Server, action, target, path, method string, input any) {
body, _ := json.Marshal(input)
status, response, err := app.agent.Do(request.Context(), server, method, path, body)
if err == nil && status < 300 && (strings.HasPrefix(action, "firewall.") || strings.HasPrefix(action, "rate_limit.")) {
var pending struct {
TransactionID string `json:"transaction_id"`
}
if json.Unmarshal(response, &pending) != nil || len(pending.TransactionID) != 16 {
err = errors.New("agent returned invalid firewall transaction")
} else {
confirmPath := "/v1/firewall/transactions/" + pending.TransactionID + "/confirm"
confirmStatus, confirmResponse, confirmErr := app.agent.Do(request.Context(), server, http.MethodPost, confirmPath, []byte("{}"))
if confirmErr != nil || confirmStatus >= 300 {
err = errors.New("firewall confirmation failed; safety rollback remains armed")
} else {
status = confirmStatus
response = confirmResponse
}
}
}
result := "success"
if err != nil || status >= 300 {
result = "failure"
}
app.store.Audit(request.Context(), &user, server.ID, action, target, nil, input, result, app.clientIP(request))
if err != nil {
writeError(writer, 502, "agent unavailable", "agent_unavailable")
return
}
writeAgentResponse(writer, status, response)
}
func contains(values []string, wanted string) bool {
for _, value := range values {
if value == wanted {
return true
}
}
return false
}
func validInterface(value string) bool {
if len(value) < 1 || len(value) > 15 {
return false
}
for _, c := range value {
if !(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') && !(c >= '0' && c <= '9') && !strings.ContainsRune("_.-", c) {
return false
}
}
return true
}
func validIPv4CIDR(value string) bool {
ip, _, err := net.ParseCIDR(value)
return err == nil && ip.To4() != nil
}
func validComment(value string) bool {
if len(value) > 80 {
return false
}
for _, c := range value {
if !(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') && !(c >= '0' && c <= '9') && !strings.ContainsRune(" ._-", c) {
return false
}
}
return true
}
func (app *App) clientIP(request *http.Request) string {
if app.config.TrustProxy {
if value := request.Header.Get("X-Real-IP"); net.ParseIP(value) != nil {
@@ -434,6 +637,17 @@ func queryLimit(request *http.Request, fallback, maximum int) int {
return value
}
func queryHours(request *http.Request, fallback, maximum int) int {
value, err := strconv.Atoi(request.URL.Query().Get("hours"))
if err != nil || value < 1 {
return fallback
}
if value > maximum {
return maximum
}
return value
}
func writeAgentResponse(writer http.ResponseWriter, status int, payload []byte) {
if status < 100 || status > 599 {
status = http.StatusBadGateway

View File

@@ -54,6 +54,15 @@ func TestValidators(t *testing.T) {
if !validServiceName("wg-quick@wg0") || validServiceName("nginx/restart") {
t.Fatal("service validation failed")
}
if !validInterface("wg0") || validInterface("../../eth0") {
t.Fatal("interface validation failed")
}
if !validIPv4CIDR("192.168.50.0/24") || validIPv4CIDR("2001:db8::/64") || validIPv4CIDR("0.0.0.0/99") {
t.Fatal("firewall CIDR validation failed")
}
if !validComment("web access") || validComment("bad;reboot") {
t.Fatal("firewall comment validation failed")
}
}
func TestPercent(t *testing.T) {

View File

@@ -75,6 +75,35 @@ CREATE TABLE IF NOT EXISTS agent_log_entries (
);
CREATE INDEX IF NOT EXISTS agent_log_entries_time_idx ON agent_log_entries(event_at DESC);
CREATE INDEX IF NOT EXISTS agent_log_entries_server_time_idx ON agent_log_entries(server_id, event_at DESC);
CREATE TABLE IF NOT EXISTS connection_samples (
server_id text NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
sampled_at timestamptz NOT NULL DEFAULT now(),
protocol text NOT NULL,
local_address text NOT NULL,
local_port integer NOT NULL CHECK (local_port BETWEEN 0 AND 65535),
remote_address text NOT NULL,
remote_port integer NOT NULL CHECK (remote_port BETWEEN 0 AND 65535),
state text NOT NULL,
process text NOT NULL DEFAULT '',
connection_count integer NOT NULL CHECK (connection_count > 0)
);
CREATE INDEX IF NOT EXISTS connection_samples_server_time_idx ON connection_samples(server_id, sampled_at DESC);
CREATE TABLE IF NOT EXISTS fail2ban_events (
id bigserial PRIMARY KEY,
server_id text NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
event_at timestamptz NOT NULL DEFAULT now(),
jail text NOT NULL,
ip text NOT NULL,
action text NOT NULL CHECK (action IN ('ban','unban')),
source text NOT NULL
);
CREATE INDEX IF NOT EXISTS fail2ban_events_server_time_idx ON fail2ban_events(server_id, event_at DESC);
CREATE TABLE IF NOT EXISTS fail2ban_ban_state (
server_id text NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
jail text NOT NULL,
ip text NOT NULL,
PRIMARY KEY(server_id,jail,ip)
);
CREATE TABLE IF NOT EXISTS audit_events (
id bigserial PRIMARY KEY,
user_id text REFERENCES users(id) ON DELETE SET NULL,
@@ -139,6 +168,37 @@ type AgentLogEntry struct {
PID *int `json:"pid,omitempty"`
}
type ConnectionHistoryRow struct {
Protocol string `json:"protocol"`
LocalAddress string `json:"local_address"`
LocalPort int `json:"local_port"`
RemoteAddress string `json:"remote_address"`
Process string `json:"process"`
Samples int64 `json:"samples"`
Peak int `json:"peak"`
FirstSeen time.Time `json:"first_seen"`
LastSeen time.Time `json:"last_seen"`
}
type ConnectionTimelinePoint struct {
SampledAt time.Time `json:"sampled_at"`
Count int64 `json:"count"`
}
type ConnectionHistory struct {
Rows []ConnectionHistoryRow `json:"rows"`
Timeline []ConnectionTimelinePoint `json:"timeline"`
}
type Fail2BanEvent struct {
ID int64 `json:"id"`
EventAt time.Time `json:"event_at"`
Jail string `json:"jail"`
IP string `json:"ip"`
Action string `json:"action"`
Source string `json:"source"`
}
type MetricPoint struct {
ServerID string
ServerName string
@@ -372,6 +432,84 @@ func (store *Store) Logs(ctx context.Context, serverID string, limit int) ([]Age
return entries, rows.Err()
}
func (store *Store) ConnectionHistory(ctx context.Context, serverID string, since time.Time) (ConnectionHistory, error) {
result := ConnectionHistory{Rows: []ConnectionHistoryRow{}, Timeline: []ConnectionTimelinePoint{}}
rows, err := store.pool.Query(ctx, `SELECT protocol,local_address,local_port,remote_address,process,
SUM(connection_count),MAX(connection_count),MIN(sampled_at),MAX(sampled_at)
FROM connection_samples WHERE server_id=$1 AND sampled_at >= $2
GROUP BY protocol,local_address,local_port,remote_address,process
ORDER BY SUM(connection_count) DESC LIMIT 500`, serverID, since)
if err != nil {
return result, err
}
defer rows.Close()
for rows.Next() {
var row ConnectionHistoryRow
if err = rows.Scan(&row.Protocol, &row.LocalAddress, &row.LocalPort, &row.RemoteAddress, &row.Process, &row.Samples, &row.Peak, &row.FirstSeen, &row.LastSeen); err != nil {
return result, err
}
result.Rows = append(result.Rows, row)
}
if err = rows.Err(); err != nil {
return result, err
}
timeline, err := store.pool.Query(ctx, `SELECT date_bin(interval '5 minutes',sampled_at,timestamptz 'epoch'),SUM(connection_count)
FROM connection_samples WHERE server_id=$1 AND sampled_at >= $2
GROUP BY 1 ORDER BY 1 LIMIT 9000`, serverID, since)
if err != nil {
return result, err
}
defer timeline.Close()
for timeline.Next() {
var point ConnectionTimelinePoint
if err = timeline.Scan(&point.SampledAt, &point.Count); err != nil {
return result, err
}
result.Timeline = append(result.Timeline, point)
}
return result, timeline.Err()
}
func (store *Store) Fail2BanEvents(ctx context.Context, serverID string, limit int) ([]Fail2BanEvent, error) {
rows, err := store.pool.Query(ctx, `SELECT id,event_at,jail,ip,action,source FROM fail2ban_events
WHERE server_id=$1 ORDER BY event_at DESC LIMIT $2`, serverID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
events := []Fail2BanEvent{}
for rows.Next() {
var event Fail2BanEvent
if err = rows.Scan(&event.ID, &event.EventAt, &event.Jail, &event.IP, &event.Action, &event.Source); err != nil {
return nil, err
}
events = append(events, event)
}
return events, rows.Err()
}
func (store *Store) AddFail2BanEvent(ctx context.Context, serverID, jail, ip, action, source string) {
tx, err := store.pool.Begin(ctx)
if err != nil {
log.Printf("write Fail2Ban event: %v", err)
return
}
defer tx.Rollback(ctx)
if _, err = tx.Exec(ctx, `INSERT INTO fail2ban_events(server_id,jail,ip,action,source) VALUES($1,$2,$3,$4,$5)`, serverID, jail, ip, action, source); err == nil {
if action == "ban" {
_, err = tx.Exec(ctx, `INSERT INTO fail2ban_ban_state(server_id,jail,ip) VALUES($1,$2,$3) ON CONFLICT DO NOTHING`, serverID, jail, ip)
} else {
_, err = tx.Exec(ctx, `DELETE FROM fail2ban_ban_state WHERE server_id=$1 AND jail=$2 AND ip=$3`, serverID, jail, ip)
}
}
if err == nil {
err = tx.Commit(ctx)
}
if err != nil {
log.Printf("write Fail2Ban event: %v", err)
}
}
func (store *Store) MetricSeries(ctx context.Context) ([]map[string]string, error) {
rows, err := store.pool.Query(ctx, "SELECT id,name FROM servers ORDER BY id LIMIT 1000")
if err != nil {

View File

@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"net/url"
"regexp"
@@ -41,6 +42,8 @@ func (poller *Poller) Run(ctx context.Context) {
if _, err := poller.store.pool.Exec(ctx, "DELETE FROM agent_log_entries WHERE event_at < $1", time.Now().Add(-poller.logRetention)); err != nil {
log.Printf("log retention cleanup: %v", err)
}
_, _ = poller.store.pool.Exec(ctx, "DELETE FROM connection_samples WHERE sampled_at < $1", time.Now().Add(-poller.metricRetention))
_, _ = poller.store.pool.Exec(ctx, "DELETE FROM fail2ban_events WHERE event_at < $1", time.Now().Add(-poller.logRetention))
_, _ = poller.store.pool.Exec(ctx, "DELETE FROM sessions WHERE expires_at < now()")
}
}
@@ -119,13 +122,26 @@ func (poller *Poller) pollServer(ctx context.Context, server Server) {
}
}
}
type socket struct {
Protocol string `json:"protocol"`
LocalAddress string `json:"local_address"`
LocalPort int `json:"local_port"`
RemoteAddress string `json:"remote_address"`
RemotePort int `json:"remote_port"`
State string `json:"state"`
Process *string `json:"process"`
}
connections := 0
connectionRows := []socket{}
if code, payload, callErr := poller.agent.Do(ctx, server, http.MethodGet, "/v1/network/connections", nil); callErr == nil && code == 200 {
var items []json.RawMessage
if json.Unmarshal(payload, &items) == nil {
connections = len(items)
if json.Unmarshal(payload, &connectionRows) == nil {
if len(connectionRows) > 10000 {
connectionRows = connectionRows[:10000]
}
connections = len(connectionRows)
}
}
bans := poller.pollFail2Ban(ctx, server)
txDB, err := poller.store.pool.Begin(ctx)
if err != nil {
return
@@ -134,7 +150,41 @@ func (poller *Poller) pollServer(ctx context.Context, server Server) {
_, err = txDB.Exec(ctx, "UPDATE servers SET status='online',hostname=$2,last_seen=now(),updated_at=now() WHERE id=$1", server.ID, status.Hostname)
if err == nil {
_, err = txDB.Exec(ctx, `INSERT INTO metric_samples(server_id,cpu,memory,disk,rx,tx,connections,bans)
VALUES($1,$2,$3,$4,$5,$6,$7,0)`, server.ID, status.CPU, memory, disk, rx, tx, connections)
VALUES($1,$2,$3,$4,$5,$6,$7,$8)`, server.ID, status.CPU, memory, disk, rx, tx, connections, bans)
}
if err == nil {
type aggregate struct {
row socket
count int
}
grouped := map[string]aggregate{}
for _, row := range connectionRows {
if net.ParseIP(row.LocalAddress) == nil || net.ParseIP(row.RemoteAddress) == nil || row.LocalPort < 0 || row.LocalPort > 65535 || row.RemotePort < 0 || row.RemotePort > 65535 || len(row.Protocol) > 8 || len(row.State) > 32 {
continue
}
process := ""
if row.Process != nil {
process = truncateUTF8(*row.Process, 128)
}
key := fmt.Sprintf("%s\x00%s\x00%d\x00%s\x00%d\x00%s\x00%s", row.Protocol, row.LocalAddress, row.LocalPort, row.RemoteAddress, row.RemotePort, row.State, process)
entry := grouped[key]
entry.row = row
entry.row.Process = &process
entry.count++
grouped[key] = entry
}
inserted := 0
for _, entry := range grouped {
if inserted >= 2000 {
break
}
_, err = txDB.Exec(ctx, `INSERT INTO connection_samples(server_id,protocol,local_address,local_port,remote_address,remote_port,state,process,connection_count)
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, server.ID, entry.row.Protocol, entry.row.LocalAddress, entry.row.LocalPort, entry.row.RemoteAddress, entry.row.RemotePort, entry.row.State, *entry.row.Process, entry.count)
if err != nil {
break
}
inserted++
}
}
if err == nil {
err = txDB.Commit(ctx)
@@ -145,6 +195,78 @@ func (poller *Poller) pollServer(ctx context.Context, server Server) {
poller.pollLogs(ctx, server)
}
func (poller *Poller) pollFail2Ban(ctx context.Context, server Server) int {
status, payload, err := poller.agent.Do(ctx, server, http.MethodGet, "/v1/fail2ban/status", nil)
if err != nil || status != http.StatusOK {
return 0
}
var response struct {
JailStatuses []struct {
Jail string `json:"jail"`
Banned []string `json:"banned_ips"`
} `json:"jail_statuses"`
}
if json.Unmarshal(payload, &response) != nil || len(response.JailStatuses) > 64 {
return 0
}
current := map[string][2]string{}
total := 0
for _, jail := range response.JailStatuses {
if !validSimpleName(jail.Jail) || len(jail.Banned) > 10000 {
continue
}
for _, ip := range jail.Banned {
if net.ParseIP(ip) != nil {
current[jail.Jail+"\x00"+ip] = [2]string{jail.Jail, ip}
total++
}
}
}
rows, err := poller.store.pool.Query(ctx, "SELECT jail,ip FROM fail2ban_ban_state WHERE server_id=$1", server.ID)
if err != nil {
return total
}
previous := map[string][2]string{}
for rows.Next() {
var jail, ip string
if rows.Scan(&jail, &ip) == nil {
previous[jail+"\x00"+ip] = [2]string{jail, ip}
}
}
rows.Close()
tx, err := poller.store.pool.Begin(ctx)
if err != nil {
return total
}
defer tx.Rollback(ctx)
for key, value := range current {
if _, found := previous[key]; !found {
_, err = tx.Exec(ctx, "INSERT INTO fail2ban_events(server_id,jail,ip,action,source) VALUES($1,$2,$3,'ban','agent')", server.ID, value[0], value[1])
if err != nil {
return total
}
}
}
for key, value := range previous {
if _, found := current[key]; !found {
_, err = tx.Exec(ctx, "INSERT INTO fail2ban_events(server_id,jail,ip,action,source) VALUES($1,$2,$3,'unban','agent')", server.ID, value[0], value[1])
if err != nil {
return total
}
}
}
if _, err = tx.Exec(ctx, "DELETE FROM fail2ban_ban_state WHERE server_id=$1", server.ID); err != nil {
return total
}
for _, value := range current {
if _, err = tx.Exec(ctx, "INSERT INTO fail2ban_ban_state(server_id,jail,ip) VALUES($1,$2,$3)", server.ID, value[0], value[1]); err != nil {
return total
}
}
_ = tx.Commit(ctx)
return total
}
func (poller *Poller) pollLogs(ctx context.Context, server Server) {
var cursor string
var since time.Time

View File

@@ -0,0 +1,9 @@
services:
backend:
image: ${CONTROL_PLANE_BACKEND_IMAGE:?CONTROL_PLANE_BACKEND_IMAGE is required}
frontend:
image: ${CONTROL_PLANE_FRONTEND_IMAGE:?CONTROL_PLANE_FRONTEND_IMAGE is required}
grafana:
image: ${CONTROL_PLANE_GRAFANA_IMAGE:?CONTROL_PLANE_GRAFANA_IMAGE is required}

View File

@@ -6,8 +6,12 @@ RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
FROM build AS test
RUN npm run lint
RUN npm run typecheck
RUN npm test -- --run
FROM nginxinc/nginx-unprivileged:1.27-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build --chown=101:101 /app/dist /usr/share/nginx/html
EXPOSE 8080

View File

@@ -7,7 +7,7 @@ import {
} from 'lucide-react'
import { api, APIError, formatBytes, formatDuration } from './api'
import type {
AgentLogEntry, AuditEvent, FirewallStatus, Interface, JailStatus, MetricSample, Role, Server, Service,
AgentLogEntry, AuditEvent, ConnectionHistory, Fail2BanEvent, FirewallRule, FirewallStatus, Interface, JailStatus, MetricSample, Role, Server, Service,
SocketInfo, SystemStatus, User, WireGuardInterface,
} from './types'
@@ -108,14 +108,14 @@ function PageContent({page,server,servers,user}:{page:Page;server?:Server;server
switch (page) {
case 'Overview': return <Overview server={server}/>
case 'Network': return <NetworkPage server={server}/>
case 'Firewall': return <FirewallPage server={server}/>
case 'Firewall': return <FirewallPage server={server} role={user.role}/>
case 'Connections': return <ConnectionsPage server={server}/>
case 'Security': return <SecurityPage server={server}/>
case 'Fail2Ban': return <Fail2BanPage server={server} role={user.role}/>
case 'WireGuard': return <WireGuardPage server={server}/>
case 'Services': return <ServicesPage server={server} role={user.role}/>
case 'Logs': return <LogsPage server={server}/>
case 'Rate Limits': return <RateLimitsPage/>
case 'Rate Limits': return <RateLimitsPage server={server} role={user.role}/>
default: return null
}
}
@@ -160,19 +160,28 @@ function NetworkPage({server}:{server:Server}) {
<DataPanel query={routes}><Card title="Kernel routes" badge="Read only"><pre className="code-block">{JSON.stringify(routes.data,null,2)}</pre></Card></DataPanel></div>
}
function FirewallPage({server}:{server:Server}) {
const firewall = useServerData<FirewallStatus>(server,'firewall',30_000)
return <DataPanel query={firewall}><div className="stack"><div className="notice"><Shield/><div><strong>{firewall.data?.backend ?? 'Unknown'} backend</strong><span>Rules are read-only in v1. Unknown and external rules are never mutated.</span></div></div>
<Card title="Managed by VPS Control" badge={firewall.data?.management_enabled?'Enabled':'Disabled'}><EmptyLine text={`Reserved table: ${firewall.data?.managed_table ?? 'inet vps_control'}. Crash-safe privileged helper is required before writes can be enabled.`}/></Card>
<Card title="External / unmanaged rules" badge="Read only">{firewall.data?.warning&&<div className="inline-warning">{firewall.data.warning}</div>}<pre className="code-block tall">{JSON.stringify(firewall.data?.ruleset,null,2)}</pre></Card></div></DataPanel>
function FirewallPage({server,role}:{server:Server;role:Role}) {
const queryClient=useQueryClient(); const firewall=useServerData<FirewallStatus>(server,'firewall',15_000)
const add=useMutation({mutationFn:(body:unknown)=>api(`/servers/${server.id}/firewall/rules`,{method:'POST',body:JSON.stringify(body)}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'firewall']})})
const remove=useMutation({mutationFn:(id:string)=>api(`/servers/${server.id}/firewall/rules/${id}`,{method:'DELETE'}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'firewall']})})
const submit=(event:FormEvent<HTMLFormElement>)=>{event.preventDefault();const data=new FormData(event.currentTarget);add.mutate({interface:data.get('interface'),source:data.get('source'),protocol:data.get('protocol'),port:Number(data.get('port')),target:data.get('target'),comment:data.get('comment')})}
const rules=firewall.data?.rules??[]
return <DataPanel query={firewall}><div className="stack"><div className="notice"><Shield/><div><strong>{firewall.data?.backend??'Unknown'} · persistent {firewall.data?.persistence_enabled?'on':'off'}</strong><span>All chains are visible. VPS Control only mutates rules marked as managed in {firewall.data?.managed_chain}.</span></div></div>
{firewall.data?.warning&&<div className="inline-warning">{firewall.data.warning}</div>}
<Card title="Add managed rule" badge={firewall.data?.management_enabled?'Enabled':'Helper unavailable'}><form className="action-form wide" onSubmit={submit}><select name="interface" required>{firewall.data?.allowed_interfaces.map(value=><option key={value}>{value}</option>)}</select><select name="source" required>{firewall.data?.allowed_sources.map(value=><option key={value}>{value}</option>)}</select><select name="protocol"><option>tcp</option><option>udp</option></select><select name="port" required>{firewall.data?.allowed_ports.map(value=><option key={value}>{value}</option>)}</select><select name="target"><option>ACCEPT</option><option>DROP</option><option>REJECT</option></select><input name="comment" placeholder="control panel"/><button className="primary" disabled={role!=='administrator'||!firewall.data?.management_enabled||add.isPending}>Add rule</button>{add.error&&<small className="danger">{add.error.message}</small>}</form></Card>
<Card title="iptables rules" badge={`${rules.length} rules`}><Table headers={['Managed','Table / chain','Protocol','Source','Interface','Port','Target','Counters','Action']} rows={rules.map(rule=>[rule.managed?'Yes':'External',<code>{rule.table} / {rule.chain}</code>,rule.protocol,<code>{rule.source}</code>,rule.in_interface||'—',rule.destination_port??'—',<Pill text={rule.target||'jump'}/>,`${rule.packets} / ${formatBytes(rule.bytes)}`,rule.managed&&!rule.rate_limit?<button className="table-action" disabled={role!=='administrator'||remove.isPending} onClick={()=>remove.mutate(rule.id)}>Delete</button>:'—'])}/></Card>
</div></DataPanel>
}
function ConnectionsPage({server}:{server:Server}) {
const connections = useServerData<SocketInfo[]>(server,'connections',10_000)
const [filter,setFilter] = useState('')
const [filter,setFilter] = useState(''); const [hours,setHours]=useState(24)
const history=useServerData<ConnectionHistory>(server,`connection-history?hours=${hours}`,30_000)
const rows=(connections.data??[]).filter((item)=>`${item.protocol} ${item.remote_address} ${item.local_port} ${item.state}`.toLowerCase().includes(filter.toLowerCase()))
const states=useMemo(()=>Object.entries(rows.reduce<Record<string,number>>((all,item)=>({...all,[item.state]:(all[item.state]??0)+1}),{})).sort((a,b)=>b[1]-a[1]),[rows])
return <DataPanel query={connections}><div className="stack"><div className="summary-row">{states.slice(0,4).map(([name,count])=><Stat key={name} label={name} value={count}/>)}</div><Card title="Current connections" badge={`${rows.length} sockets`} action={<input className="filter" placeholder="Filter protocol, IP, port…" value={filter} onChange={(e)=>setFilter(e.target.value)}/>}><Table headers={['Protocol','Local','Remote','State','Process']} rows={rows.map(item=>[item.protocol.toUpperCase(),<code>{item.local_address}:{item.local_port}</code>,<code>{item.remote_address}:{item.remote_port}</code>,<Pill text={item.state}/>,item.process?`${item.process} · ${item.pid}`:'—'])}/></Card></div></DataPanel>
return <DataPanel query={connections}><div className="stack"><div className="summary-row">{states.slice(0,4).map(([name,count])=><Stat key={name} label={name} value={count}/>)}</div><Card title="Current connections" badge={`${rows.length} sockets`} action={<input className="filter" placeholder="Filter protocol, IP, port…" value={filter} onChange={(e)=>setFilter(e.target.value)}/>}><Table headers={['Protocol','Destination','Source','State','Process']} rows={rows.map(item=>[item.protocol.toUpperCase(),<code>{item.local_address}:{item.local_port}</code>,<code>{item.remote_address}:{item.remote_port}</code>,<Pill text={item.state}/>,item.process?`${item.process} · ${item.pid}`:'—'])}/></Card>
<DataPanel query={history}><Card title="Connection statistics" badge={`Last ${hours}h`} action={<select value={hours} onChange={event=>setHours(Number(event.target.value))}><option value="1">1 hour</option><option value="24">24 hours</option><option value="168">7 days</option><option value="720">30 days</option></select>}><Table headers={['Source','Destination','Protocol','Process','Observed','Peak','First / last']} rows={(history.data?.rows??[]).map(item=>[<code>{item.remote_address}</code>,<code>{item.local_address}:{item.local_port}</code>,item.protocol.toUpperCase(),item.process||'—',item.samples,item.peak,<span>{new Date(item.first_seen).toLocaleString()}<br/>{new Date(item.last_seen).toLocaleString()}</span>])}/></Card></DataPanel>
</div></DataPanel>
}
function SecurityPage({server}:{server:Server}) {
@@ -183,10 +192,15 @@ function SecurityPage({server}:{server:Server}) {
}
function Fail2BanPage({server,role}:{server:Server;role:Role}) {
const queryClient=useQueryClient(); const status=useServerData<JailStatus>(server,'fail2ban',15_000)
const queryClient=useQueryClient(); const status=useServerData<JailStatus>(server,'fail2ban',15_000); const history=useServerData<Fail2BanEvent[]>(server,'fail2ban-history?limit=500',30_000)
const mutation=useMutation({mutationFn:(input:{action:'ban'|'unban';jail:string;ip:string})=>api(`/servers/${server.id}/fail2ban/${input.action}`,{method:'POST',body:JSON.stringify(input)}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'fail2ban']})})
const configure=useMutation({mutationFn:(body:unknown)=>api(`/servers/${server.id}/fail2ban/configure`,{method:'POST',body:JSON.stringify(body)}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'fail2ban']})})
const submit=(event:FormEvent<HTMLFormElement>)=>{event.preventDefault();const data=new FormData(event.currentTarget);mutation.mutate({action:data.get('action') as 'ban'|'unban',jail:String(data.get('jail')),ip:String(data.get('ip'))})}
return <DataPanel query={status}><div className="split"><Card title="Daemon status" badge={status.data?.running?'Running':'Unavailable'}><div className="details"><Stat label="Installed" value={status.data?.installed?'Yes':'No'}/><Stat label="Version" value={status.data?.version??'—'}/><Stat label="Jails" value={status.data?.jails.length??0}/></div><div className="tag-list">{status.data?.jails.map(jail=><span key={jail}>{jail}</span>)}</div></Card><Card title="Manual action" badge="Audited"><form className="action-form" onSubmit={submit}><select name="action"><option value="ban">Ban</option><option value="unban">Unban</option></select><select name="jail" required>{status.data?.jails.map(jail=><option key={jail}>{jail}</option>)}</select><input name="ip" required placeholder="192.0.2.20"/><button className="primary" disabled={role==='viewer'||mutation.isPending}>Apply</button>{role==='viewer'&&<small>Operator role required.</small>}{mutation.error&&<small className="danger">{mutation.error.message}</small>}</form></Card></div></DataPanel>
const submitConfig=(event:FormEvent<HTMLFormElement>)=>{event.preventDefault();const data=new FormData(event.currentTarget);configure.mutate({jail:data.get('jail'),enabled:data.get('enabled')==='on',bantime_seconds:Number(data.get('bantime')),findtime_seconds:Number(data.get('findtime')),maxretry:Number(data.get('maxretry'))})}
return <DataPanel query={status}><div className="stack"><div className="split"><Card title="Daemon status" badge={status.data?.running?'Running':'Unavailable'}><div className="details"><Stat label="Installed" value={status.data?.installed?'Yes':'No'}/><Stat label="Version" value={status.data?.version??'—'}/><Stat label="Jails" value={status.data?.jails.length??0}/></div><Table headers={['Jail','Failed','Banned now','Banned total','IPs']} rows={(status.data?.jail_statuses??[]).map(jail=>[jail.jail,jail.currently_failed,jail.currently_banned,jail.total_banned,jail.banned_ips.join(', ')||'—'])}/></Card><Card title="Manual action" badge="Audited"><form className="action-form" onSubmit={submit}><select name="action"><option value="ban">Ban</option><option value="unban">Unban</option></select><select name="jail" required>{status.data?.jails.map(jail=><option key={jail}>{jail}</option>)}</select><input name="ip" required placeholder="192.0.2.20"/><button className="primary" disabled={role==='viewer'||mutation.isPending}>Apply</button>{mutation.error&&<small className="danger">{mutation.error.message}</small>}</form></Card></div>
<Card title="Managed jail settings" badge={status.data?.management_enabled?'Enabled':'Helper unavailable'}><form className="action-form wide" onSubmit={submitConfig}><select name="jail" required>{status.data?.manageable_jails.map(jail=><option key={jail}>{jail}</option>)}</select><label><input name="enabled" type="checkbox" defaultChecked/> Enabled</label><input name="bantime" type="number" defaultValue="3600" min="10" max="2592000"/><input name="findtime" type="number" defaultValue="600" min="10" max="86400"/><input name="maxretry" type="number" defaultValue="5" min="1" max="100"/><button className="primary" disabled={role!=='administrator'||!status.data?.management_enabled||configure.isPending}>Save</button>{configure.error&&<small className="danger">{configure.error.message}</small>}</form></Card>
<DataPanel query={history}><Card title="Restriction history" badge={`${history.data?.length??0} events`}><Table headers={['Time','Jail','IP','Action','Source']} rows={(history.data??[]).map(event=>[new Date(event.event_at).toLocaleString(),event.jail,<code>{event.ip}</code>,<Pill text={event.action}/>,event.source])}/></Card></DataPanel>
</div></DataPanel>
}
function WireGuardPage({server}:{server:Server}) {
@@ -196,8 +210,8 @@ function WireGuardPage({server}:{server:Server}) {
function ServicesPage({server,role}:{server:Server;role:Role}) {
const queryClient=useQueryClient(); const query=useServerData<Service[]>(server,'services',15_000)
const mutation=useMutation({mutationFn:(name:string)=>api(`/servers/${server.id}/services/${encodeURIComponent(name)}/restart`,{method:'POST',body:'{}'}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'services']})})
return <DataPanel query={query}><Card title="Allow-listed systemd services" badge={`${query.data?.length??0} configured`}><Table headers={['State','Unit','Sub-state','PID','Memory','Action']} rows={(query.data??[]).map(item=>[<StatusDot status={item.active_state==='active'?'online':'offline'}/>,<code>{item.name}</code>,item.sub_state,item.pid||'—',formatBytes(item.memory_bytes),<button className="table-action" disabled={role==='viewer'||mutation.isPending} onClick={()=>mutation.mutate(item.name)}><ListRestart/>Restart</button>])}/></Card></DataPanel>
const mutation=useMutation({mutationFn:(input:{name:string;operation:string})=>api(`/servers/${server.id}/services/${encodeURIComponent(input.name)}/${input.operation}`,{method:'POST',body:'{}'}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'services']})})
return <DataPanel query={query}><Card title="Systemd service inventory" badge={`${query.data?.length??0} units`}><Table headers={['State','Unit','Load / runtime','Boot','Description','Managed actions']} rows={(query.data??[]).map(item=>[<StatusDot status={item.active_state==='active'?'online':'offline'}/>,<code>{item.name}</code>,`${item.load_state} / ${item.sub_state}`,item.unit_file_state,item.description,item.managed?<div className="table-actions">{item.load_state==='not-found'&&item.install_available?<button className="table-action" disabled={role!=='administrator'||mutation.isPending} onClick={()=>mutation.mutate({name:item.name,operation:'install'})}>Install</button>:<><button className="table-action" disabled={role==='viewer'||mutation.isPending} onClick={()=>mutation.mutate({name:item.name,operation:item.active_state==='active'?'restart':'start'})}><ListRestart/>{item.active_state==='active'?'Restart':'Start'}</button><button className="table-action" disabled={role==='viewer'||mutation.isPending} onClick={()=>mutation.mutate({name:item.name,operation:'stop'})}>Stop</button><button className="table-action" disabled={role==='viewer'||mutation.isPending} onClick={()=>mutation.mutate({name:item.name,operation:item.unit_file_state==='enabled'?'disable':'enable'})}>{item.unit_file_state==='enabled'?'Disable boot':'Enable boot'}</button></>}</div>:'Read only'])}/></Card></DataPanel>
}
function ServersPage({servers,user}:{servers:Server[];user:User}) {
@@ -223,7 +237,13 @@ function LogsPage({server}:{server:Server}) {
])}/></Card>
</div></DataPanel>
}
function RateLimitsPage(){return <div className="notice"><Gauge/><div><strong>Policy engine is not enabled in v1</strong><span>L4 nftables policies require the crash-safe privileged helper. L7 provider configuration is planned separately; arbitrary nginx edits will not be supported.</span></div></div>}
function RateLimitsPage({server,role}:{server:Server;role:Role}){
const queryClient=useQueryClient(); const query=useServerData<FirewallRule[]>(server,'rate-limits',15_000); const firewall=useServerData<FirewallStatus>(server,'firewall',30_000)
const add=useMutation({mutationFn:(body:unknown)=>api(`/servers/${server.id}/rate-limits`,{method:'POST',body:JSON.stringify(body)}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'rate-limits']})})
const remove=useMutation({mutationFn:(id:string)=>api(`/servers/${server.id}/rate-limits/${id}`,{method:'DELETE'}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'rate-limits']})})
const submit=(event:FormEvent<HTMLFormElement>)=>{event.preventDefault();const data=new FormData(event.currentTarget);add.mutate({interface:data.get('interface'),source:data.get('source'),protocol:data.get('protocol'),port:Number(data.get('port')),rate_per_second:Number(data.get('rate')),burst:Number(data.get('burst')),comment:data.get('comment')})}
return <DataPanel query={query}><div className="stack"><div className="notice"><Gauge/><div><strong>L4 policy engine</strong><span>Policies use iptables hashlimit in a dedicated chain. Nginx configuration is not edited.</span></div></div><Card title="Add rate limit" badge="Per source IP"><form className="action-form wide" onSubmit={submit}><select name="interface" required>{firewall.data?.allowed_interfaces.map(value=><option key={value}>{value}</option>)}</select><select name="source" required>{firewall.data?.allowed_sources.map(value=><option key={value}>{value}</option>)}</select><select name="protocol"><option>tcp</option><option>udp</option></select><select name="port" required>{firewall.data?.allowed_ports.map(value=><option key={value}>{value}</option>)}</select><input name="rate" type="number" required min="1" defaultValue="10"/><input name="burst" type="number" required min="1" defaultValue="20"/><input name="comment" placeholder="https-new-connections"/><button className="primary" disabled={role!=='administrator'||!firewall.data?.management_enabled||add.isPending}>Create</button>{add.error&&<small className="danger">{add.error.message}</small>}</form></Card><Card title="Active policies" badge={`${query.data?.length??0}`}><Table headers={['ID','Source','Interface','Protocol / port','Counters','Action']} rows={(query.data??[]).filter(rule=>rule.target==='ACCEPT').map(rule=>[<code>{rule.id}</code>,<code>{rule.source}</code>,rule.in_interface,`${rule.protocol}/${rule.destination_port??'—'}`,`${rule.packets} / ${formatBytes(rule.bytes)}`,<button className="table-action" disabled={role!=='administrator'||remove.isPending} onClick={()=>remove.mutate(rule.id)}>Delete</button>])}/></Card></div></DataPanel>
}
function SettingsPage({user,server}:{user:User;server?:Server}){return <div className="split"><Card title="Current account" badge={user.role}><div className="details"><Stat label="Username" value={user.username}/><Stat label="Role" value={user.role}/><Stat label="Session" value="HttpOnly + CSRF"/></div></Card><Card title="Agent target" badge={server?.status??'none'}><div className="details"><Stat label="Name" value={server?.name??'—'}/><Stat label="Endpoint" value={server?.agent_endpoint??'—'}/><Stat label="Last contact" value={server?.last_seen?new Date(server.last_seen).toLocaleString():'—'}/></div></Card></div>}
function Metric({label,value,sub,level}:{label:string;value:string;sub:string;level?:number}){return <div className="metric"><span className="eyebrow">{label}</span><strong>{value}</strong><small>{sub}</small>{level!==undefined&&<div className="meter"><i style={{width:`${Math.min(100,Math.max(0,level))}%`}}/></div>}</div>}

View File

@@ -5,3 +5,4 @@
@media(max-width:1050px){.metric-grid{grid-template-columns:repeat(2,1fr)}.overview-grid,.split{grid-template-columns:1fr}.action-form{grid-template-columns:1fr 1fr}.action-form button{grid-column:2}.compact{grid-template-columns:repeat(3,1fr)}}
@media(max-width:760px){.shell{display:block}.sidebar{position:fixed;left:-250px;width:236px;transition:left .2s}.sidebar.open{left:0}.scrim{position:fixed;inset:0;background:rgba(0,0,0,.55);border:0;z-index:15}.mobile-close{display:grid;margin-left:auto}.menu-button{display:grid}.topbar{padding:0 14px}.breadcrumb{display:none}.content{padding:20px 14px}.connection{display:none}.page-header{height:auto;min-height:62px}.last-seen{display:none}.metric-grid,.compact{grid-template-columns:1fr}.metric{min-height:115px}.server-form,.action-form{grid-template-columns:1fr}.action-form button{grid-column:auto}.server-grid{grid-template-columns:1fr}.filter{width:160px}.panel-loading{grid-template-columns:1fr}.panel-loading i:nth-child(n+2){display:none}}
.log-message{display:block;min-width:260px;max-width:760px;white-space:pre-wrap;overflow-wrap:anywhere;font-family:'DM Mono',ui-monospace,monospace;color:var(--muted);line-height:1.45}
.action-form.wide{grid-template-columns:repeat(auto-fit,minmax(130px,1fr))}.action-form label{display:flex;align-items:center;gap:7px;color:var(--muted);font-size:11px}.action-form label input[type=checkbox]{width:16px;height:16px}.table-actions{display:flex;align-items:center;gap:6px}

View File

@@ -13,10 +13,15 @@ export interface SystemStatus {
}
export interface Interface { name: string; state: string; addresses: string[]; rx_bytes: number; tx_bytes: number }
export interface SocketInfo { protocol: string; local_address: string; local_port: number; remote_address: string; remote_port: number; state: string; pid?: number; process?: string }
export interface Service { name: string; active_state: string; sub_state: string; pid: number; memory_bytes?: number }
export interface JailStatus { installed: boolean; running: boolean; version?: string; jails: string[] }
export interface Service { name: string; load_state:string; active_state: string; sub_state: string; description:string; unit_file_state:string; managed:boolean; install_available:boolean }
export interface JailDetail { jail:string; currently_failed:number; total_failed:number; currently_banned:number; total_banned:number; banned_ips:string[] }
export interface JailStatus { installed: boolean; running: boolean; version?: string; jails: string[]; jail_statuses:JailDetail[]; management_enabled:boolean; manageable_jails:string[] }
export interface WireGuardInterface { name: string; public_key: string; listen_port: number; peers: Array<{public_key:string;endpoint?:string;allowed_ips:string[];latest_handshake:number;rx_bytes:number;tx_bytes:number}> }
export interface FirewallStatus { backend: string; management_enabled: boolean; managed_table: string; ruleset: unknown; warning?: string }
export interface FirewallRule { id:string; table:string; chain:string; protocol:string; source:string; destination:string; in_interface:string; out_interface:string; destination_port?:number; target:string; packets:number; bytes:number; comment:string; managed:boolean; rate_limit:boolean }
export interface FirewallStatus { backend: string; management_enabled: boolean; persistence_enabled:boolean; managed_chain: string; allowed_interfaces:string[]; allowed_sources:string[]; allowed_ports:number[]; rules:FirewallRule[]; warning?: string }
export interface AuditEvent { id: number; username: string; server_id?: string; action: string; target: string; result: string; source_ip: string; created_at: string }
export interface MetricSample { sampled_at:string; cpu:number; memory:number; disk:number; rx:number; tx:number; connections:number; bans:number }
export interface AgentLogEntry { server_id:string; timestamp:string; unit:string; priority:number; message:string; boot_id?:string; pid?:number }
export interface ConnectionHistoryRow { protocol:string; local_address:string; local_port:number; remote_address:string; process:string; samples:number; peak:number; first_seen:string; last_seen:string }
export interface ConnectionHistory { rows:ConnectionHistoryRow[]; timeline:Array<{sampled_at:string;count:number}> }
export interface Fail2BanEvent { id:number; event_at:string; jail:string; ip:string; action:'ban'|'unban'; source:string }

View File

@@ -30,14 +30,18 @@ writes at 2 rps, burst 20, with 32 concurrent requests and five-second timeouts.
| GET | `/v1/network/routes` | kernel routes |
| GET | `/v1/network/listeners` | listening TCP/UDP sockets |
| GET | `/v1/network/connections` | current TCP/UDP sockets |
| GET | `/v1/firewall/rules` | backend and read-only ruleset |
| GET/POST | `/v1/firewall/rules` | structured iptables inventory / add managed rule |
| DELETE | `/v1/firewall/rules/:id` | delete a managed rule |
| GET/POST | `/v1/rate-limits` | list / add managed L4 policies |
| DELETE | `/v1/rate-limits/:id` | delete a managed L4 policy |
| GET | `/v1/fail2ban/status` | installation and jail summary |
| GET | `/v1/fail2ban/jails/:jail` | validated jail detail |
| POST | `/v1/fail2ban/ban` | validated IP and jail ban |
| POST | `/v1/fail2ban/unban` | validated IP and jail unban |
| POST | `/v1/fail2ban/configure` | write and validate an allow-listed jail drop-in |
| GET | `/v1/wireguard/status` | interface and peer dump |
| GET | `/v1/services` | allow-listed services only |
| POST | `/v1/services/:name/restart` | allow-listed restart only |
| GET | `/v1/services` | bounded inventory of all systemd services |
| POST | `/v1/services/:name/:operation` | allow-listed action or catalog installation |
| GET | `/v1/logs` | cursor-paginated journald rows from allow-listed units |
No generic command route exists. Child processes receive a fixed executable and
@@ -53,6 +57,8 @@ fixed subcommand plus individually validated argv values.
connections, bans)` with 30-day retention
- `agent_log_entries(server_id, journal_cursor, event_at, unit, priority,
message, boot_id, pid)` with configurable seven-day retention
- `connection_samples(...)` with current source/destination/process aggregates
- `fail2ban_events(...)` and `fail2ban_ban_state(...)` for ban history
- `audit_events(actor, server, action, target, before, after, result, source_ip,
created_at)`; secrets are excluded
@@ -78,10 +84,8 @@ Grafana ──Prometheus/Loki read APIs──> backend ──semantic polling─
## Privilege design
The agent has no ambient capabilities and runs as `vps-agent`. Linux usually
permits the read-only endpoints without elevation. Fail2Ban mutations and
service restarts need administrator-provided sudoers or polkit rules restricted
to each approved verb/name. The shipped service does not install such policy
automatically. Managed firewall mutation is out of v1 because giving the main
daemon `CAP_NET_ADMIN` violates least privilege; its future helper protocol must
provide prepare/apply/health/confirm/commit and persistent timed rollback.
The HTTP agent has no ambient capabilities and runs as `vps-agent`. Linux
usually permits the read-only endpoints without elevation. Mutations go over a
0600 Unix socket to a root, socket-activated helper. The helper accepts typed
JSON only, validates local allow-lists, uses fixed argv, snapshots iptables,
rolls back failures and never mutates rules outside its two reserved chains.

View File

@@ -7,6 +7,49 @@ WireGuard address only and allow TCP/9105 solely from the control-plane peer.
Alternatively bind to loopback and expose it through an authenticated tunnel.
TLS termination at the agent is supported when certificate paths are configured.
## Agent write features
On Debian/Ubuntu install the firewall userspace and persistence provider before
enabling managed writes:
```bash
sudo apt-get update
sudo apt-get install -y iptables iptables-persistent fail2ban
sudo systemctl enable --now netfilter-persistent vps-agent-helper.socket
```
Then edit `/etc/vps-agent/config.toml`. All write targets must be explicitly
allow-listed; use the real tunnel interface, management network and service
ports for the host:
```toml
[services]
allowed = ["nginx.service", "fail2ban.service"]
inventory_limit = 512
install_enabled = true
install_timeout_seconds = 300
packages = { "nginx.service" = "nginx", "fail2ban.service" = "fail2ban" }
[firewall]
management_enabled = true
persistence_enabled = true
allowed_interfaces = ["wg0"]
allowed_sources = ["192.168.50.0/24"]
allowed_ports = [22, 80, 443, 9105]
rollback_timeout_seconds = 60
max_snapshots = 5
[fail2ban]
management_enabled = true
allowed_jails = ["sshd", "nginx-http-auth"]
```
Restart the daemon after editing. The UI shows every iptables rule but only
rules in `VPS_CONTROL_INPUT` and `VPS_CONTROL_RATE` can be deleted. Successful
changes are saved through `netfilter-persistent`; failed changes restore the
last snapshot. Keep the control-panel port and source network in the allow-list
before adding restrictive rules.
## Control plane
```bash
@@ -36,7 +79,8 @@ needs only `/etc/vps-agent/`. For upgrades, pin image tags, back up, pull/build,
run `docker compose up -d`, then inspect health and audit events. Database
migrations are forward-only; restore the database backup for rollback.
Metric samples are retained for 30 days and collected logs for seven days by
Metric and connection samples are retained for 30 days and collected logs and
Fail2Ban history for seven days by
the backend cleanup loop. `METRICS_RETENTION` and `LOGS_RETENTION` control these
windows; log retention is constrained to one hour through 90 days. Configure
database-level backups independently of retention.

127
docs/gitea-deploy.md Normal file
View File

@@ -0,0 +1,127 @@
# Gitea production deployment
`.gitea/workflows/deploy-control-plane.yml` runs for a pushed `vX.X.X` tag. It
runs backend and frontend checks in isolated Docker build stages, builds
immutable backend, frontend, and Grafana images, pushes them to the configured
container registry, copies only the Compose definitions and the deployment
helper over SSH, and waits for all enabled service health checks.
The production host keeps its own `.env`, `secrets/`, PostgreSQL volume, and
reverse-proxy configuration. The workflow never copies those values from CI.
## Gitea configuration
Keep these existing instance-level values:
| Kind | Name | Purpose |
| --- | --- | --- |
| Variable | `REGISTRY_HOST` | Registry hostname with optional port, without `https://` |
| Variable | `REGISTRY_USERNAME` | Registry login/user name |
| Secret | `REGISTRY_PASSWORD` | Gitea PAT with `write:package` access (which includes read) |
| Secret | `RELEASE_TOKEN` | Used by the separate agent release workflow |
Add the following Actions variables:
| Name | Example | Purpose |
| --- | --- | --- |
| `DEPLOY_HOST` | `control.example.net` | SSH hostname or IPv4 address |
| `DEPLOY_PORT` | `22` | SSH port; an empty value defaults to 22 |
| `DEPLOY_USER` | `vps-deploy` | Dedicated deployment user |
| `DEPLOY_PATH` | `/opt/vps-control` | Absolute deployment directory; an existing clone's `control-plane` directory is also valid |
| `DEPLOY_PROFILES` | `observability` | Empty for core services, or `observability` to run Grafana |
Add these Actions secrets:
| Name | Purpose |
| --- | --- |
| `DEPLOY_SSH_KEY` | Complete unencrypted OpenSSH private key for the deployment user |
| `DEPLOY_SSH_KNOWN_HOSTS` | Pinned OpenSSH known-hosts line for the production server |
The workflow asks Gitea for `contents: read` and `packages: write`. Repository or
owner Actions settings must not clamp package access below write. The registry
account must be allowed to push and pull packages for the repository owner.
Protect `v*` tags so they cannot be moved to another commit after publication.
The explicit PAT is intentional: Gitea documents that automatic job-token
authorization for publishing OCI packages is not implemented yet.
## Prepare the production server
Install Docker Engine, the current Docker Compose v2 plugin, `flock` (normally
provided by `util-linux`), and an SSH server. The deployment user needs access
to Docker and must own the deployment directory. Membership in the Docker group
is effectively root-equivalent, so use a dedicated host and key.
Example for Debian or Ubuntu after Docker is installed:
```bash
sudo useradd --create-home --shell /bin/bash vps-deploy
sudo usermod --append --groups docker vps-deploy
sudo install -d -o vps-deploy -g vps-deploy -m 0700 /opt/vps-control
```
Create an SSH key on a trusted administrator machine and install only its public
half on the server:
```bash
ssh-keygen -t ed25519 -f ./gitea-vps-control-deploy -C gitea-vps-control-deploy
ssh-copy-id -i ./gitea-vps-control-deploy.pub vps-deploy@control.example.net
```
Put the private-key file content into `DEPLOY_SSH_KEY`. Obtain the server host
key, verify its fingerprint through a separate trusted channel, and then put
the resulting complete line into `DEPLOY_SSH_KNOWN_HOSTS`:
```bash
ssh-keyscan -p 22 control.example.net
```
On the production server, create `/opt/vps-control/.env` and the secret files
before the first deployment. Their format is described in `control-plane/README.md`:
```bash
cd /opt/vps-control
mkdir -m 0700 secrets
openssl rand -hex 32 > secrets/db_password
openssl rand -base64 24 > secrets/admin_password
openssl rand -hex 32 > secrets/integration_token
openssl rand -base64 24 > secrets/grafana_admin_password
openssl rand -hex 32 > secrets/grafana_secret_key
install -m 0600 /secure/source/control-plane.token secrets/agent_token
chmod 0600 secrets/*
```
Create `.env` from `control-plane/.env.example` and set production bindings,
cookie security, retention, and optional bootstrap values. The pipeline refuses
to deploy when `.env` or `secrets/` is absent.
If Gitea uses a private CA, install that CA in Docker's trust store on both the
runner and production host. Do not disable registry TLS verification.
## Release and rollback behavior
Commit the workflow and deployment files before creating the tag:
```bash
git tag -a v0.1.0 -m "VPS Control v0.1.0"
git push origin main
git push origin v0.1.0
```
Images use immutable version tags:
```text
REGISTRY_HOST/owner/repository-backend:v0.1.0
REGISTRY_HOST/owner/repository-frontend:v0.1.0
REGISTRY_HOST/owner/repository-grafana:v0.1.0
```
The remote helper serializes deployments with `flock`, validates the rendered
Compose configuration, pulls images, and runs `docker compose up --wait`. If a
health check fails and a previous `.release.env` exists, it restores the prior
image set and tries to start it again. Registry credentials are kept in a
temporary Docker config and removed after the SSH session.
Image rollback does not roll back a database schema. Keep tested PostgreSQL
backups before releases that change migrations; forward-only migration rollback
requires restoring the corresponding database backup.

71
docs/gitea-release.md Normal file
View File

@@ -0,0 +1,71 @@
# Gitea release pipeline
The workflow in `.gitea/workflows/release-agent.yml` runs only for pushed tags
matching `v*.*.*`. It then applies a stricter `vX.X.X` check, verifies that the
tag matches the version in `agent/Cargo.toml`, builds static Linux binaries for
amd64 and arm64, creates `SHA256SUMS`, and publishes all three files in a Gitea
release.
## Runner requirements
Register an amd64 Gitea Actions runner whose `ubuntu-latest` label resolves to a
Linux environment with:
- `bash`, `curl`, `jq`, `file`, `sha256sum`, Git, and CA certificates;
- Rustup and Cargo;
- Docker with permission for the runner user to access its daemon;
- outbound access to the Rust registries and the container registry used by
`cross`.
The job installs the pinned Rust 1.85.1 toolchain and `cross` 0.2.5. `cross`
uses Docker to build both musl targets; no amd64 or arm64 build host is required.
Do not expose the Docker daemon over an unauthenticated TCP socket.
The simplest setup is a dedicated runner VM with an `ubuntu-latest:host` label.
If jobs run inside a container instead, that container needs the Docker CLI and
controlled access to the host Docker socket. A runner that executes untrusted
repositories must not share this Docker access.
## Secrets, variables, and permissions
Configure this instance- or repository-level Actions secret:
- `RELEASE_TOKEN` (required): a Gitea access token for a dedicated automation
account with write access to releases in this repository. Store it as a
**secret**, not as a variable.
The workflow requests `contents: read` and `releases: write`. The token owner
must also be allowed to read the repository and create releases. Protect the
release tags so only trusted maintainers or automation can push them.
No custom Actions variables are required. Existing `REGISTRY_HOST`,
`REGISTRY_USERNAME`, and `REGISTRY_PASSWORD` values are deliberately unused:
this pipeline publishes release assets and does not push a container image.
Gitea supplies `GITHUB_API_URL`, `GITHUB_REPOSITORY`, and `GITHUB_REF_NAME` to
the job automatically.
## Publishing a release
First update `agent/Cargo.toml` and commit the change. Then create and push the
matching annotated tag:
```bash
git tag -a v0.1.0 -m "VPS Agent v0.1.0"
git push origin v0.1.0
```
After the job succeeds, the `v0.1.0` release contains:
- `vps-agent-linux-amd64`
- `vps-agent-linux-arm64`
- `SHA256SUMS`
The publisher refuses to overwrite an existing release. If a job fails while
uploading assets, it removes the incomplete release so that the same tag can be
rerun safely. It never deletes the Git tag.
Before installation, verify the downloaded binary:
```bash
sha256sum --check SHA256SUMS
```

View File

@@ -19,7 +19,7 @@ CSRF header on mutations. Passwords use Argon2id.
| Request flooding | request timeouts, concurrency semaphore, token buckets, reverse-proxy limits |
| Command injection | no command strings; executable and subcommands are constants; service names are allow-listed |
| Privilege escalation | unprivileged user, systemd sandbox, no capabilities, write privileges opt-in and narrow |
| Accidental firewall lockout | v1 is read-only; future mutations require local, crash-safe confirm-or-rollback |
| Accidental firewall damage | only dedicated chains are mutable; every change snapshots, restores on error, and persists only after success |
| Disk/log exhaustion | journald only, no metric spool, PostgreSQL retention, bounded body/audit fields |
| Observability token theft | independent file secret, constant-time verification, per-source limiting, no agent credentials in Grafana |
| Expensive dashboard queries | fixed metric set, restricted selectors, 31-day ranges, point/row/result caps |
@@ -37,13 +37,18 @@ the file, restart the agent, then update its control-plane Docker secret and
restart the backend. Keep the overlap window short; the agent intentionally
accepts one token. Never pass the token on a command line.
## Firewall safety design (future helper)
## Privileged helper and firewall safety
The future root helper owns only `table inet vps_control`. It writes a bounded
snapshot (maximum five), fsyncs a pending transaction with a monotonic deadline,
applies a complete validated table, and starts an independent rollback timer.
Only an authenticated confirmation commits. On restart it rolls back any pending
transaction before accepting a new one. Unknown tables/chains remain read-only.
The HTTP daemon remains unprivileged. A socket-activated, one-request root helper
accepts only typed operations from the `vps-agent` Unix account. Firewall writes
are restricted to `VPS_CONTROL_INPUT` and `VPS_CONTROL_RATE`; external rules are
always read-only. Before a mutation the helper stores a bounded `iptables-save`
snapshot and arms an independent systemd rollback timer. The backend confirms
the transaction only after reconnecting to the agent; without confirmation the
snapshot is restored and persisted. Immediate command failures also restore it.
Interfaces, source CIDRs, ports, services, packages and Fail2Ban jails must all
match local configuration allow-lists. Service installation uses a fixed
`apt-get` argv in a time-bounded transient systemd unit.
## Operational logging

View File

@@ -16,13 +16,25 @@ burst = 20.0
command_timeout_seconds = 4
[services]
allowed = ["nginx", "fail2ban", "wg-quick@wg0"]
allowed = ["nginx.service", "fail2ban.service", "wg-quick@wg0.service"]
inventory_limit = 512
install_enabled = false
install_timeout_seconds = 300
packages = { "nginx.service" = "nginx", "fail2ban.service" = "fail2ban" }
[firewall]
management_enabled = false
persistence_enabled = true
allowed_interfaces = ["wg0"]
allowed_sources = ["192.168.50.0/24"]
allowed_ports = [22, 80, 443, 9105]
rollback_timeout_seconds = 60
max_snapshots = 5
[fail2ban]
management_enabled = false
allowed_jails = ["sshd", "nginx-http-auth"]
[logging]
level = "info"

131
scripts/deploy-control-plane.sh Executable file
View File

@@ -0,0 +1,131 @@
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
umask 077
usage() {
printf 'Usage: %s TAG IMAGE_PREFIX\n' "$0" >&2
}
[[ $# -eq 2 ]] || { usage; exit 2; }
TAG="$1"
IMAGE_PREFIX="$2"
PROFILES="${CONTROL_PLANE_PROFILES:-}"
[[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || {
printf 'invalid deployment tag: %s\n' "$TAG" >&2
exit 2
}
[[ "$IMAGE_PREFIX" =~ ^[a-z0-9][a-z0-9./:_-]*[a-z0-9]$ ]] || {
printf 'invalid container image prefix\n' >&2
exit 2
}
[[ -z "$PROFILES" || "$PROFILES" == observability ]] || {
printf 'CONTROL_PLANE_PROFILES must be empty or observability\n' >&2
exit 2
}
for command_name in docker flock mktemp; do
command -v "$command_name" >/dev/null || {
printf '%s is required on the deployment server\n' "$command_name" >&2
exit 1
}
done
docker compose version >/dev/null
for required_path in .env docker-compose.yml docker-compose.prod.yml secrets; do
[[ -e "$required_path" ]] || {
printf 'required deployment path is missing: %s/%s\n' "$PWD" "$required_path" >&2
exit 1
}
done
exec 9>.deploy.lock
if ! flock -n 9; then
printf 'another control-plane deployment is already running\n' >&2
exit 1
fi
NEXT_ENV="$(mktemp .release.env.next.XXXXXX)"
cleanup() {
rm -f "$NEXT_ENV"
}
trap cleanup EXIT
printf '%s\n' \
"CONTROL_PLANE_BACKEND_IMAGE=${IMAGE_PREFIX}-backend:${TAG}" \
"CONTROL_PLANE_FRONTEND_IMAGE=${IMAGE_PREFIX}-frontend:${TAG}" \
"CONTROL_PLANE_GRAFANA_IMAGE=${IMAGE_PREFIX}-grafana:${TAG}" \
> "$NEXT_ENV"
PROFILE_ARGS=()
SERVICES=(postgres backend frontend)
if [[ "$PROFILES" == observability ]]; then
PROFILE_ARGS=(--profile observability)
SERVICES+=(grafana)
fi
compose() {
local release_env="$1"
shift
docker compose \
--env-file .env \
--env-file "$release_env" \
-f docker-compose.yml \
-f docker-compose.prod.yml \
"${PROFILE_ARGS[@]}" \
"$@"
}
# Validate all interpolation and secret paths before changing the active tag.
compose "$NEXT_ENV" config --quiet
HAD_PREVIOUS=false
if [[ -f .release.env ]]; then
cp -f .release.env .release.env.previous
HAD_PREVIOUS=true
fi
mv -f "$NEXT_ENV" .release.env
NEXT_ENV=""
printf 'pulling control-plane images for %s\n' "$TAG"
compose .release.env pull backend frontend
if [[ "$PROFILES" == observability ]]; then
compose .release.env pull grafana
fi
printf 'deploying control plane %s\n' "$TAG"
if compose .release.env up \
--detach \
--no-build \
--remove-orphans \
--wait \
--wait-timeout 180 \
"${SERVICES[@]}"; then
compose .release.env ps
printf 'control plane %s is healthy\n' "$TAG"
exit 0
fi
printf 'deployment %s failed health checks\n' "$TAG" >&2
if [[ "$HAD_PREVIOUS" == true ]]; then
printf 'restoring the previous container image set\n' >&2
cp -f .release.env.previous .release.env
compose .release.env pull backend frontend || true
if [[ "$PROFILES" == observability ]]; then
compose .release.env pull grafana || true
fi
if ! compose .release.env up \
--detach \
--no-build \
--remove-orphans \
--wait \
--wait-timeout 180 \
"${SERVICES[@]}"; then
printf 'automatic image rollback also failed; operator action is required\n' >&2
fi
else
printf 'no previous release metadata exists; automatic rollback is unavailable\n' >&2
fi
exit 1

145
scripts/publish-gitea-release.sh Executable file
View File

@@ -0,0 +1,145 @@
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
usage() {
printf 'Usage: %s TAG ARTIFACT_DIRECTORY\n' "$0" >&2
}
[[ $# -eq 2 ]] || { usage; exit 2; }
TAG="$1"
ARTIFACT_DIRECTORY="$2"
API_URL="${GITEA_API_URL:-${GITHUB_API_URL:-}}"
REPOSITORY="${GITEA_REPOSITORY:-${GITHUB_REPOSITORY:-}}"
TOKEN="${GITEA_TOKEN:-}"
[[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || {
printf 'refusing to publish invalid release tag: %s\n' "$TAG" >&2
exit 2
}
[[ "$API_URL" =~ ^https?://[^/]+(/.*)?$ ]] || {
printf 'GITEA_API_URL or GITHUB_API_URL must be an HTTP(S) URL\n' >&2
exit 2
}
[[ "$REPOSITORY" =~ ^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$ ]] || {
printf 'GITEA_REPOSITORY or GITHUB_REPOSITORY must be owner/repository\n' >&2
exit 2
}
[[ -n "$TOKEN" ]] || { printf 'GITEA_TOKEN is required\n' >&2; exit 2; }
[[ -d "$ARTIFACT_DIRECTORY" ]] || {
printf 'artifact directory does not exist: %s\n' "$ARTIFACT_DIRECTORY" >&2
exit 2
}
for command_name in curl jq sha256sum; do
command -v "$command_name" >/dev/null || {
printf '%s is required\n' "$command_name" >&2
exit 1
}
done
ARTIFACT_DIRECTORY="$(cd "$ARTIFACT_DIRECTORY" && pwd -P)"
REQUIRED_ASSETS=(
vps-agent-linux-amd64
vps-agent-linux-arm64
SHA256SUMS
)
for asset_name in "${REQUIRED_ASSETS[@]}"; do
[[ -f "$ARTIFACT_DIRECTORY/$asset_name" ]] || {
printf 'required release asset is missing: %s\n' "$asset_name" >&2
exit 1
}
done
(
cd "$ARTIFACT_DIRECTORY"
sha256sum --check SHA256SUMS
)
API_URL="${API_URL%/}"
RELEASES_URL="$API_URL/repos/$REPOSITORY/releases"
RESPONSE_FILE="$(mktemp)"
RELEASE_ID=""
RELEASE_CREATED=false
cleanup() {
local exit_status=$?
rm -f "$RESPONSE_FILE"
if [[ $exit_status -ne 0 && "$RELEASE_CREATED" == true && -n "$RELEASE_ID" ]]; then
printf 'publication failed; removing incomplete release %s\n' "$TAG" >&2
curl --silent --show-error --fail \
--request DELETE \
--header "Authorization: token $TOKEN" \
"$RELEASES_URL/$RELEASE_ID" >/dev/null || true
fi
exit "$exit_status"
}
trap cleanup EXIT
status_code="$(curl --silent --show-error \
--output "$RESPONSE_FILE" \
--write-out '%{http_code}' \
--header "Authorization: token $TOKEN" \
"$RELEASES_URL/tags/$TAG")"
case "$status_code" in
404) ;;
200)
printf 'release %s already exists; refusing to overwrite it\n' "$TAG" >&2
exit 1
;;
*)
printf 'failed to check existing release (HTTP %s): %s\n' \
"$status_code" "$(jq -r '.message // .error // "unknown API error"' "$RESPONSE_FILE" 2>/dev/null || true)" >&2
exit 1
;;
esac
RELEASE_BODY="${GITEA_RELEASE_BODY:-Automated vps-agent release for $TAG. Verify downloaded binaries with SHA256SUMS before installation.}"
release_payload="$(jq -n \
--arg tag "$TAG" \
--arg name "VPS Agent $TAG" \
--arg body "$RELEASE_BODY" \
'{tag_name: $tag, name: $name, body: $body, draft: false, prerelease: false}')"
status_code="$(curl --silent --show-error \
--output "$RESPONSE_FILE" \
--write-out '%{http_code}' \
--request POST \
--header "Authorization: token $TOKEN" \
--header 'Content-Type: application/json' \
--data "$release_payload" \
"$RELEASES_URL")"
if [[ "$status_code" != 201 ]]; then
printf 'failed to create release (HTTP %s): %s\n' \
"$status_code" "$(jq -r '.message // .error // "unknown API error"' "$RESPONSE_FILE" 2>/dev/null || true)" >&2
exit 1
fi
RELEASE_ID="$(jq -er '.id' "$RESPONSE_FILE")"
RELEASE_CREATED=true
ASSETS=("${REQUIRED_ASSETS[@]}")
if [[ -f "$ARTIFACT_DIRECTORY/SHA256SUMS.minisig" ]]; then
ASSETS+=(SHA256SUMS.minisig)
fi
for asset_name in "${ASSETS[@]}"; do
status_code="$(curl --silent --show-error \
--output "$RESPONSE_FILE" \
--write-out '%{http_code}' \
--request POST \
--header "Authorization: token $TOKEN" \
--form "attachment=@$ARTIFACT_DIRECTORY/$asset_name" \
"$RELEASES_URL/$RELEASE_ID/assets?name=$asset_name")"
if [[ "$status_code" != 201 ]]; then
printf 'failed to upload %s (HTTP %s): %s\n' \
"$asset_name" "$status_code" \
"$(jq -r '.message // .error // "unknown API error"' "$RESPONSE_FILE" 2>/dev/null || true)" >&2
exit 1
fi
printf 'uploaded %s\n' "$asset_name"
done
RELEASE_CREATED=false
printf 'published release %s with %d assets\n' "$TAG" "${#ASSETS[@]}"

View File

@@ -9,6 +9,8 @@ readonly CONFIG_DIR="/etc/vps-agent"
readonly CREDENTIAL_DIR="${CONFIG_DIR}/credentials"
readonly STATE_DIR="/var/lib/vps-agent"
readonly UNIT="/etc/systemd/system/vps-agent.service"
readonly HELPER_SOCKET_UNIT="/etc/systemd/system/vps-agent-helper.socket"
readonly HELPER_SERVICE_UNIT="/etc/systemd/system/vps-agent-helper@.service"
readonly DEFAULT_RELEASES="https://gitea.hyperdog.dev/dizyaka/vps-control/releases"
VERSION="latest"
@@ -137,6 +139,60 @@ RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
[Install]
WantedBy=multi-user.target
EOF
install -o root -g root -m 0644 /dev/null "$HELPER_SOCKET_UNIT"
tee "$HELPER_SOCKET_UNIT" >/dev/null <<'EOF'
[Unit]
Description=VPS Control privileged helper socket
[Socket]
ListenStream=/run/vps-agent-helper/control.sock
Accept=yes
MaxConnections=1
SocketUser=vps-agent
SocketGroup=vps-agent
SocketMode=0600
DirectoryMode=0750
RemoveOnStop=yes
[Install]
WantedBy=sockets.target
EOF
install -o root -g root -m 0644 /dev/null "$HELPER_SERVICE_UNIT"
tee "$HELPER_SERVICE_UNIT" >/dev/null <<'EOF'
[Unit]
Description=VPS Control privileged helper request
[Service]
Type=oneshot
ExecStart=/usr/local/bin/vps-agent --privileged-helper --config /etc/vps-agent/config.toml
StandardInput=socket
StandardOutput=socket
StandardError=journal
User=root
Group=root
TimeoutStartSec=330
UMask=0077
PrivateTmp=true
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
ProtectClock=true
ProtectHostname=true
RestrictSUIDSGID=true
LockPersonality=true
RestrictRealtime=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
EOF
}
install_helper_units() {
local source_dir="$(cd "$(dirname "$0")" && pwd)/../agent/packaging"
if [[ -f "$source_dir/vps-agent-helper.socket" && -f "$source_dir/vps-agent-helper@.service" ]]; then
install -o root -g root -m 0644 "$source_dir/vps-agent-helper.socket" "$HELPER_SOCKET_UNIT"
install -o root -g root -m 0644 "$source_dir/vps-agent-helper@.service" "$HELPER_SERVICE_UNIT"
elif [[ ! -f "$HELPER_SOCKET_UNIT" || ! -f "$HELPER_SERVICE_UNIT" ]]; then
die "helper unit templates are missing; use the packaged installer or install the units manually"
fi
}
create_config() {
@@ -158,10 +214,21 @@ burst = 20.0
command_timeout_seconds = 4
[services]
allowed = []
inventory_limit = 512
install_enabled = false
install_timeout_seconds = 300
packages = {}
[firewall]
management_enabled = false
persistence_enabled = true
allowed_interfaces = []
allowed_sources = []
allowed_ports = []
rollback_timeout_seconds = 60
max_snapshots = 5
[fail2ban]
management_enabled = false
allowed_jails = ["sshd"]
[logging]
level = "info"
[telemetry]
@@ -223,8 +290,9 @@ do_install() {
create_config
create_token
install_unit
install_helper_units
systemctl daemon-reload
systemctl enable --now vps-agent.service
systemctl enable --now vps-agent-helper.socket vps-agent.service
wait_healthy || die "agent failed to become healthy"
systemctl status --no-pager vps-agent.service
}
@@ -239,6 +307,10 @@ do_update() {
install -o root -g root -m 0755 "$downloaded" "$staged"
install -o root -g root -m 0755 "$BINARY" "$PREVIOUS"
mv -f -- "$staged" "$BINARY"
install_unit
install_helper_units
systemctl daemon-reload
systemctl enable --now vps-agent-helper.socket
systemctl restart vps-agent.service
if ! wait_healthy; then
info "health check failed; restoring previous binary"
@@ -268,8 +340,18 @@ do_remove() {
read -r -p "Permanently delete $CONFIG_DIR and credentials? [y/N] " answer
[[ "$answer" == "y" || "$answer" == "Y" ]] || die "purge cancelled"
fi
systemctl disable --now vps-agent.service 2>/dev/null || true
rm -f -- "$UNIT" "$BINARY" "$PREVIOUS"
local pending transaction
for pending in "$STATE_DIR"/firewall/pending-*.rules; do
[[ -f "$pending" ]] || continue
transaction="${pending##*/pending-}"
transaction="${transaction%.rules}"
[[ "$transaction" =~ ^[a-fA-F0-9]{16}$ ]] || die "invalid pending firewall transaction filename"
"$BINARY" --firewall-rollback "$transaction" --config "$CONFIG_DIR/config.toml" \
|| die "could not restore pending firewall transaction $transaction"
systemctl stop "vps-agent-firewall-rollback-${transaction}.timer" 2>/dev/null || true
done
systemctl disable --now vps-agent.service vps-agent-helper.socket 2>/dev/null || true
rm -f -- "$UNIT" "$HELPER_SOCKET_UNIT" "$HELPER_SERVICE_UNIT" "$BINARY" "$PREVIOUS"
rm -rf -- "$STATE_DIR"
systemctl daemon-reload
if [[ "$PURGE" == true ]]; then