DEV Community

Kim Jarvis
Kim Jarvis

Posted on Originally published at reemote.hashnode.dev

Implement Wireguard and Crowdsec security for your servers in Python

WireGuard is an encrypted network tunnel with cryptographically authenticated peers. CrowdSec is a log-driven security engine: it detects abusive behavior, submits alerts to a Local API (LAPI), and produces decisions that remediation components, traditionally called bouncers, enforce. Reemote is a pure-Python configuration-management library that lets us assemble these systems using SSH, typed facts, operations, and ordinary Python control flow.

These tools solve different problems. WireGuard makes a service private and protects traffic in transit; it does not recognize an authenticated user's abusive HTTP requests or repeated SSH login failures. CrowdSec detects those patterns in service logs and shares decisions across a fleet; it does not encrypt the network. Here, WireGuard carries private LAPI traffic between Ubuntu servers while CrowdSec watches SSH. A bouncer is an additional enforcement layer, not a complete baseline firewall.

Try the canonical example first

Install Python 3.13 or newer and Docker or Podman. The connector requires you to name the CLI explicitly; there is no default.

uv venv .venv
source .venv/bin/activate
uv pip install reemote
Enter fullscreen mode Exit fullscreen mode

Save this as hello.py. It is the canonical example configured for Podman. The offline pytest suite simulates the connector, and the example was also verified live with Podman. Change both docker_cmd values to "docker" if that is your local CLI.

# hello.py
import asyncio

from reemote import files, format_log, format_plan, op, run

INVENTORY = [
    {
        "host": "demo0",
        "family": "Alpine",
        "connection": {
            "connector": "docker",
            "identifier": "alpine:3.20",
            "docker_cmd": "podman",
        },
    },
    {
        "host": "demo1",
        "family": "Alpine",
        "connection": {
            "connector": "docker",
            "identifier": "alpine:3.20",
            "docker_cmd": "podman",
        },
    },
]


def deploy(host):
    yield op(
        files.install,
        name="Write a greeting",
        content="Hello from reemote!\n",
        dest="/tmp/reemote-hello.txt",
        mode="0644",
    )
    yield op(
        files.install,
        name="Record the host name",
        content=f"written on {host.name}\n",
        dest="/tmp/reemote-host.txt",
        mode="0644",
    )


async def main():
    plans, report, _ = await run(INVENTORY, deploy, dry=True)
    print("== Dry run ==")
    print(format_plan(plans))
    assert report is None

    _, report, _ = await run(INVENTORY, deploy)
    print("\n== Applied ==")
    assert report is not None
    print(format_log(report))


asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

Run it with python hello.py. The dry run connects to both containers and reads real state, but sends no mutating deploy commands inside them. The connector may still create, commit, and remove its temporary containers. The apply then advances through the two operations in lockstep: both hosts finish writing the greeting before either starts recording its name.

Verified output from Podman is shown below. The dry-run plan is host-major, while the apply log is step-major: both Write a greeting entries appear before either Record the host name entry.

== Dry run ==
demo0: Write a greeting         [changed: content /tmp/reemote-hello.txt is absent, will install]
demo0: Record the host name     [changed: content /tmp/reemote-host.txt is absent, will install]
demo1: Write a greeting         [changed: content /tmp/reemote-hello.txt is absent, will install]
demo1: Record the host name     [changed: content /tmp/reemote-host.txt is absent, will install]

== Applied ==
demo0: Write a greeting         [changed: content /tmp/reemote-hello.txt is absent, will install]
    $ scp <files install> -> /tmp/reemote-install-2e52d4f8373a608a/content
    $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-2e52d4f8373a608a/content /tmp/reemote-hello.txt && chmod 644 /tmp/reemote-hello.txt && rm -rf /tmp/reemote-install-2e52d4f8373a608a'
demo1: Write a greeting         [changed: content /tmp/reemote-hello.txt is absent, will install]
    $ scp <files install> -> /tmp/reemote-install-2e52d4f8373a608a/content
    $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-2e52d4f8373a608a/content /tmp/reemote-hello.txt && chmod 644 /tmp/reemote-hello.txt && rm -rf /tmp/reemote-install-2e52d4f8373a608a'
demo0: Record the host name     [changed: content /tmp/reemote-host.txt is absent, will install]
    $ scp <files install> -> /tmp/reemote-install-8c7265455d37e471/content
    $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-8c7265455d37e471/content /tmp/reemote-host.txt && chmod 644 /tmp/reemote-host.txt && rm -rf /tmp/reemote-install-8c7265455d37e471'
demo1: Record the host name     [changed: content /tmp/reemote-host.txt is absent, will install]
    $ scp <files install> -> /tmp/reemote-install-8c7265455d37e471/content
    $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-8c7265455d37e471/content /tmp/reemote-host.txt && chmod 644 /tmp/reemote-host.txt && rm -rf /tmp/reemote-install-8c7265455d37e471'
Enter fullscreen mode Exit fullscreen mode

An image identifier creates a throwaway container for each host. On close, Reemote commits it to a new image and removes the container. That makes every run start fresh; idempotence is demonstrated later against an existing container instead.

Unlike the throwaway-container quickstart, the following examples target persistent Ubuntu hosts over SSH. They reuse host state, so reruns demonstrate convergence; applying them changes real networking and security services.

Inventory for persistent Ubuntu SSH hosts

Use fresh, dedicated Ubuntu 24.04 or newer machines with systemd, a WireGuard-capable kernel, working public-key SSH, verified host keys, and passwordless sudo for your deployment account. No target-side Python interpreter is required. Keep console access and an SSH route outside this tunnel throughout bootstrap.

Save this inventory as crowdsec-inventory.json in your checkout. Replace the documentation addresses, SSH user, key path, and hub endpoint. Choose unused RFC1918 tunnel addresses that do not overlap your existing networks. This is a two-host starting point; additional spokes need unique names and /32 addresses.

[
  {
    "host": "security-hub",
    "family": "Ubuntu",
    "group": "crowdsec",
    "connection": {
      "connector": "ssh",
      "address": "203.0.113.10",
      "username": "admin",
      "key_path": "~/.ssh/id_ed25519"
    },
    "crowdsec_role": "hub",
    "wg_address": "10.77.0.1/32",
    "wg_endpoint": "203.0.113.10:51820"
  },
  {
    "host": "security-spoke",
    "family": "Ubuntu",
    "group": "crowdsec",
    "connection": {
      "connector": "ssh",
      "address": "203.0.113.20",
      "username": "admin",
      "key_path": "~/.ssh/id_ed25519"
    },
    "crowdsec_role": "spoke",
    "wg_address": "10.77.0.2/32"
  }
]
Enter fullscreen mode Exit fullscreen mode

The scripts load inventory only in main(), select group=crowdsec, and reject non-Ubuntu or non-SSH entries in that group. They require exactly one hub and at least one spoke. Custom fields such as crowdsec_role belong at the top level of each inventory entry; Reemote exposes them through host.extra. The scripts do not alter the repository's inventory. Without --inventory, they read the repository's inventory.json; the explicit path below prevents accidental targeting. See hosts and the SSH connector for inventory and host-key verification.

Before applying, configure your existing host firewall and cloud security groups:

  • Permit the hub's UDP 51820 from the intended peers, and allow spoke egress to it.
  • Permit TCP 8080 to the hub's tunnel address only through wg-crowdsec from the spoke tunnel addresses. Do not publish LAPI on the public interface; also enforce the interface restriction in the host firewall, even though the process binds a private address.
  • Preserve your independent SSH management rules and required application traffic. These examples deliberately do not replace an existing firewall ruleset or change cloud security groups.

This tunnel routes only individual peer addresses. It is not a default route, exit VPN, or routed LAN gateway: no NAT, IP forwarding, 0.0.0.0/0, or spoke-to-spoke forwarding is configured.

Runnable example index

Clone the repository, use a revision containing the corrected WireGuard library, and install it on your controller with uv pip install -e .. The scripts are under examples/articles/crowdsec/. This index identifies this article's examples.

Script What it teaches
crowdsec_hello.py The canonical greeting on persistent SSH hosts
crowdsec_bootstrap.py Vendor repository, packages, target-local WireGuard identities
crowdsec_tunnel.py Public-key discovery, peer configuration, change-driven restart
crowdsec_hub.py Private LAPI binding and SSH detection on the hub
crowdsec_agents.py Target-side enrollment, identity validation, agent-only spokes
crowdsec_bouncers.py Explicitly opted-in nftables enforcement after secret provisioning
crowdsec_inspect.py Secret-free peer and registration summary
crowdsec_decisions.py Add/remove a short-lived test decision

The shared crowdsec_article_common.py contains inventory validation, the runner, and the detection configuration shared by hub and spokes.

Every mutating script previews by default and requires --apply. Unlike the canonical run() example, these scripts use wave-based deploys: a checkpoint can inspect actual changes, and an action can validate the resulting configuration before a restart. A dry wave run stops at the first barrier. It does not preview later waves or execute enrollment, validation, or secret preflight actions. Read the complete script before applying. Preview still connects over SSH to read state; it is not an offline command. The drivers, operations, and guide explain these contracts.

Start with a harmless persistent-host change

python examples/articles/crowdsec/crowdsec_hello.py --inventory crowdsec-inventory.json
python examples/articles/crowdsec/crowdsec_hello.py --inventory crowdsec-inventory.json --apply
Enter fullscreen mode Exit fullscreen mode

This counterpart writes the same greeting and host-name files as the canonical example, without sudo. A second apply should report no changes. It proves the SSH inventory before we modify networking.

What the modules provide

The WireGuard module groups its capabilities around installation and identity, persistent interface/peer configuration, runtime peer reconciliation, service lifecycle, and observation. We use the persistent configuration path because addresses and routes belong to wg-quick; a peer-only live sync is not a substitute for applying address or route changes.

The CrowdSec module covers detection content and acquisitions, machine and bouncer registrations, decision lifecycle, Hub maintenance, and inventory/health facts. Registration is not installation of a remote agent or bouncer. Its machine operation writes credentials on the host running cscli, and its bouncer operation needs a caller-supplied key. This article uses native target-side agent registration so no machine password needs to be uploaded or returned to the controller.

Supporting APT, files, systemd, actions, and handlers handle the surrounding operating-system work. There is no interpreter hidden behind the Python: an operation yields commands and transfers, while facts decide whether work is needed.

Bootstrap packages and identities

Follow CrowdSec's official Linux repository instructions to obtain and independently verify its current public repository-signing key. Save the reviewed ASCII-armored key as crowdsec-repo.asc on the controller. Inspect its full fingerprint with gpg --show-keys --with-fingerprint crowdsec-repo.asc and compare it with your approved vendor trust record. Do not treat downloading a key over HTTPS as independent fingerprint verification.

The bootstrap example installs repository prerequisites, a scoped .asc keyring, the official any repository with signed-by, crowdsec and wireguard-tools, then calls wireguard.ensure_keypair. Modern Ubuntu APT accepts armored .asc keyrings directly, so the installed public key can be compared byte-for-byte on reruns. Check apt-cache policy crowdsec on the targets: other repositories or Ubuntu Pro priorities can override the vendor candidate. Resolve that policy explicitly instead of assuming the newest vendor package wins. Use a current CrowdSec release supporting the documented .yaml.local overrides.

python examples/articles/crowdsec/crowdsec_bootstrap.py --inventory crowdsec-inventory.json --repo-key crowdsec-repo.asc
Enter fullscreen mode Exit fullscreen mode

Apply only after reviewing the plan. The bootstrap does not install a bouncer. Native package installation can start a local CrowdSec service; its initial LAPI listens on loopback. The later hub/agent scripts establish the intended fleet roles.

WireGuard identities live in /etc/wireguard/wg-crowdsec.key as root-owned mode 0600. Existing valid identities are preserved, insecure metadata is repaired, and an invalid key causes an error rather than silent rotation. Back up keys through your existing protected backup system, not by printing them in deployment logs.

Establish the private tunnel

The tunnel script gathers only public keys through authenticated SSH, checks their shape and uniqueness, and constructs immutable WireguardPeerConfig values. On the hub, each peer gets only its own /32 in AllowedIPs. Each spoke gets only the hub /32, its public UDP endpoint, and a 25-second keepalive for NAT mappings.

wireguard.configure_interface uploads a secret-free template. The corrected library reads and validates the private key on the target, inserts a real inline PrivateKey, and atomically installs the final root-owned 0600 configuration. A filename is not a valid PrivateKey value. Reconciliation masks the inline key on the target and detects drift against the key file. Do not use the raw WireguardConfig fact for public diagnostics: it contains the private key.

A checkpoint reports whether the configuration changed. Only changed hosts request a restart; stopped services are started and disabled units enabled even when the file is already correct. A restart briefly interrupts this tunnel, which is why its SSH control connection must not depend on it. The Requires= drop-ins can also stop dependent CrowdSec/bouncer services when the tunnel stops. After a tunnel change, finish the hub and agent steps below, and rerun the optional bouncer step if you enabled enforcement. Public-key discovery requires a completed bootstrap, even for a tunnel preview.

Configure the private LAPI hub

The hub script writes non-secret .yaml.local overrides instead of replacing package defaults. LAPI listens on 10.77.0.1:8080, not a wildcard address. A URL-only local_api_credentials.yaml.local points the hub's own log processor at that address while retaining its package-generated login and password. CrowdSec supports this credentials override as well as the main configuration override.

Detection deliberately owns a separate acquisition file and directory. The configured acquisition_path is /etc/crowdsec/reemote-acquis.yaml; acquisition_dir is /etc/crowdsec/reemote-acquis.d. This SSH-only lab does not also ingest the package's auto-detected /var/log/auth.log, avoiding duplicate processing. It consequently stops consuming other package-discovered inputs: on an existing production deployment, merge your required sources into this design before applying. These examples own config.yaml.local and the named article files, so do not point them at unrelated overrides you need to preserve.

The source reads the journal with _SYSTEMD_UNIT=ssh.service and labels it syslog. Confirm that filter actually returns SSH events on your Ubuntu image. Install only collections that match acquired logs; the example adds Linux and SSH collections without removing unrelated installed collections. The singular collection() operation is additive; collections() reconciles an exact complete set.

A systemd drop-in orders CrowdSec after wg-quick@wg-crowdsec. The script runs crowdsec -t before starting/restarting the service, then checks cscli lapi status. A failing action stops the workflow. Validation occurs after writing files, so failure leaves those files for inspection; it is not a transactional rollback of the entire deployment. After correcting a failed run, validate on the affected host with sudo crowdsec -t, then explicitly restart with sudo systemctl restart crowdsec and check sudo cscli lapi status. A file already written by a failed run may compare unchanged on retry, so that retry alone does not guarantee a restart.

Enroll agent-only spokes without moving passwords

After the hub is running, the agent script performs three ordered phases:

  1. On each spoke, cscli lapi register --machine reemote-<host> --url <private-LAPI> --file /etc/crowdsec/reemote-agent.yaml generates a random password locally. The surrounding elevated shell uses a restrictive umask, rejects a symlink, and refuses to reuse an empty, non-regular, or incorrectly owned/permitted credentials file. Existing credentials are reused; nothing is force-registered.
  2. On the hub, the script reads machine registrations, matches only inventory-derived names, verifies that each source IP matches that peer's pinned WireGuard /32, and validates only unvalidated matching registrations. It does not approve every pending machine. There is no NAT between peers to obscure that address.
  3. On the spokes, it disables their LAPI servers, selects the new credentials file, installs the SSH acquisition and collections, validates configuration, and starts the log processors against the hub.

Native registration and validation are explicit Shell actions, because the public operations do not expose this remote, target-generated enrollment flow. All compound shell syntax stays inside sh -c, including when sudo is used. Action output is not printed; failures report the step and exit status, leaving detailed diagnostics on the target.

This is enrollment, not automatic credential rotation or disaster recovery. If a hub database is lost, a registration succeeds but credential publication fails, or stored credentials no longer authenticate, investigate and reconcile that particular machine deliberately. The script fails rather than using --force and silently replacing an identity. A peer with control of a trusted host is still trusted by this model; the IP check does not protect against compromise of that host.

Run the ordered detection workflow

After reviewing individual previews and configuring the network rules, run these commands in order from the repository root. This sequence establishes detection and shared decisions, not firewall enforcement:

python examples/articles/crowdsec/crowdsec_hello.py --inventory crowdsec-inventory.json --apply
python examples/articles/crowdsec/crowdsec_bootstrap.py --inventory crowdsec-inventory.json --repo-key crowdsec-repo.asc --apply
python examples/articles/crowdsec/crowdsec_tunnel.py --inventory crowdsec-inventory.json --apply
python examples/articles/crowdsec/crowdsec_hub.py --inventory crowdsec-inventory.json --apply
python examples/articles/crowdsec/crowdsec_agents.py --inventory crowdsec-inventory.json --apply
python examples/articles/crowdsec/crowdsec_inspect.py --inventory crowdsec-inventory.json
Enter fullscreen mode Exit fullscreen mode

The inspection script reports peer handshake timestamps, collection names, hub registrations, and a decision count, never raw credential files. A missing handshake is not proof of health; check firewall rules, endpoint reachability, clock synchronization, journal ingestion, and LAPI authentication. Facts are gathered concurrently across hosts, one fact type at a time. Hosts are closed even when a read fails.

Add enforcement explicitly

Without a bouncer, CrowdSec detects but does not block. The optional example installs the nftables firewall bouncer in its packaged managed mode. Review compatibility with UFW, firewalld, existing nftables rules, container forwarding, IPv6, and your management allowlists first. Do not install competing iptables and nftables bouncer packages together. Keep an out-of-band console available.

Bouncer API keys are separate from machine passwords. Provision them before running the example:

  1. On the hub, register one uniquely named bouncer per enforcing host using your secret-management workflow and cscli bouncers add <unique-name>. Capture the one-time key directly into that protected workflow; do not commit it, paste it into inventory, or place it in command-line arguments. For controller-supplied keys, the module's registration operation exists, but this article does not use its secret-upload path.
  2. Through that same secret manager, create /etc/crowdsec/bouncers/crowdsec-firewall-bouncer.yaml.local on each enforcing host, with a root-owned non-writable parent and file ownership root:root, mode 0600. Supply two unquoted scalar lines: api_url: http://10.77.0.1:8080/ (adjust for your hub) and api_key: followed by that host's real key. Do not reuse a key across hosts.
  3. Review any pre-existing base bouncer configuration. The example retains the package's defaults and your override; it does not rewrite secrets. Its preflight checks file type, permissions, expected URL, and a syntactically plausible key, not server-side authentication.

The credential-delivery step is intentionally external, not an implemented secret-store integration. The existing general file uploader and CrowdSec registration uploader do not offer the corrected WireGuard installer's complete private-spool safeguards. Passing mode="0600" alone is not a claim that every intermediate copy is private. No article-specific secret uploader is hidden here.

python examples/articles/crowdsec/crowdsec_bouncers.py --inventory crowdsec-inventory.json
python examples/articles/crowdsec/crowdsec_bouncers.py --inventory crowdsec-inventory.json --apply --ack-firewall
Enter fullscreen mode Exit fullscreen mode

The preview stops before the secret preflight. During apply, all hosts must pass preflight before package installation proceeds. Installation may start the bouncer and immediately enforce decisions. The script also installs tunnel startup ordering and enables the service. After an externally provisioned key or configuration rotation, rerun with --apply --ack-firewall --reload-secrets; that explicit restart is intentionally not a zero-change operation.

Verify actual bouncer pulls on the hub with cscli bouncers list and cscli metrics show bouncers, inspect the target service journal, and inspect the nftables rules/sets. A registered name or an active service alone does not prove that enforcement is working.

Exercise a decision and remove it

Use a documentation-only address, never the operator's public IP, SSH source, or WireGuard peer address:

python examples/articles/crowdsec/crowdsec_decisions.py --inventory crowdsec-inventory.json --apply
python examples/articles/crowdsec/crowdsec_inspect.py --inventory crowdsec-inventory.json
python examples/articles/crowdsec/crowdsec_decisions.py --inventory crowdsec-inventory.json --remove --apply
Enter fullscreen mode Exit fullscreen mode

The operation adds a two-minute ban for 192.0.2.123 only on the hub. Inspect the bouncer's set to verify distribution, then remove the decision. Repeating add while the same decision is present is a no-op; after expiry it creates a new decision. It is a presence operation, not a lease renewal. Removal is scoped to the ban type. This test checks decision delivery, not the SSH parser; separately confirm real log acquisition and parser metrics without brute-forcing a production server.

Convergence and failure boundaries

Once the initial workflow succeeds, repeat this steady-state sequence:

python examples/articles/crowdsec/crowdsec_hello.py --inventory crowdsec-inventory.json --apply
python examples/articles/crowdsec/crowdsec_bootstrap.py --inventory crowdsec-inventory.json --repo-key crowdsec-repo.asc --apply
python examples/articles/crowdsec/crowdsec_tunnel.py --inventory crowdsec-inventory.json --apply
python examples/articles/crowdsec/crowdsec_hub.py --inventory crowdsec-inventory.json --apply
python examples/articles/crowdsec/crowdsec_agents.py --inventory crowdsec-inventory.json --apply
Enter fullscreen mode Exit fullscreen mode

With unchanged input and a fresh APT cache, operations converge to zero changes. Read-only validation actions still execute. APT refreshes after the one-hour cache interval are expected maintenance, not configuration drift. Agent credentials and WireGuard keys do not rotate, and collection management does not remove unrelated content. The opt-in bouncer deployment also converges when its provisioned configuration is unchanged and --reload-secrets is absent.

Hub updates/upgrades, expired test decisions, explicit restarts, credential rotation, and adding/removing peers have different change semantics and are not part of that no-change claim. Removing a spoke from inventory removes its peer from the hub's desired WireGuard configuration on the next tunnel apply, but does not decommission its remote service, machine registration, or bouncer key. Revoke those deliberately on the hub and stop the retired host.

The offline pytest suite executes the canonical code block and every real-host script with simulated hosts, then replays the documented multi-script workflow against persistent state. It also exercises shell rendering and registration/preflight failures with local stub tools. These are not live Ubuntu/WireGuard interoperability tests; they do not establish that a particular cloud firewall, kernel, journal source, package maintainer script, or bouncer is correctly deployed.

Further reading

For CrowdSec's engine/LAPI/remediation split, see the official introduction, technical documentation, LAPI configuration, configuration overrides, and firewall bouncer documentation. Lumadock's introduction and CrowdSec Fundamentals provide broader background.

For tunnel concepts, start with WireGuard, Jason Eckert's introduction, Netmaker's overview, and the server/client walkthrough. Their wider routing examples require additional firewall and forwarding decisions beyond this management tunnel.

Do not enable routine WireGuard kernel debug logging just to feed CrowdSec. The authors of the CrowdSec WireGuard collection discourage that use. WireGuard itself is deliberately quiet to unauthenticated peers; CrowdSec usually protects SSH, proxies, and applications alongside it, not the WireGuard UDP port. A server exposing only WireGuard may gain little from adding log-based detection.

Implementation summary

We built a persistent Ubuntu fleet with target-local WireGuard identities, private /32 peer routes, a tunnel-bound CrowdSec LAPI, authenticated agent enrollment, SSH log acquisition, additive collections, change-driven services, secret-free inspection, and a reversible test decision. Optional nftables enforcement is runnable after explicitly provisioning separate bouncer credentials through a secret manager. Baseline firewall rules, cloud security groups, backups, key rotation, and production log-source selection remain explicit operator responsibilities.

WireGuard supplies encrypted transport and authenticated network membership; CrowdSec supplies behavioral detection and shared decisions that bouncers enforce. Keeping those complementary roles clear makes the Python deployment understandable—and makes its limits as important as its successful run.

References

Top comments (0)