Skip to content
1posixPublic

About

Lightweight Single Packet Authorization daemon for Linux written in Rust

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

18 Commits

Folders and files

Repository files navigation

knockd-rs

knockd-rs is a lightweight Single Packet Authorization (SPA) daemon and client written in Rust for Linux.

It provides temporary IPv4 access to SSH through an authenticated UDP packet and a dedicated nftables ruleset.

The project is currently focused on a small and auditable security model:

  • IPv4 only
  • UDP SPA transport
  • HMAC-SHA256 authentication
  • timestamp validation
  • nonce-based replay protection
  • authenticated source IPv4 binding
  • temporary nftables grants
  • SSH / TCP port 22 only
  • Debian/systemd deployment

knockd-rs is still pre-1.0 software. Review and test the firewall behavior in a VM or on a machine with console access before deploying it to a remote server.


How it works

Without an active grant:

Client
  |
  | TCP/22
  v
Server
  |
  +---- unauthorized source ----> DROP

The client first sends a SPA packet:

Client
  |
  | authenticated UDP SPA packet
  v
knockd-rs daemon
  |
  +-- HMAC verification
  +-- protocol validation
  +-- timestamp validation
  +-- source IPv4 validation
  +-- replay protection
  |
  v
nftables temporary set

A valid request creates a temporary nftables entry:

ssh_allowed_v4

192.0.2.42
  timeout 30s

While that entry exists:

192.0.2.42 -> TCP/22 -> ACCEPT

After the timeout expires:

192.0.2.42 -> TCP/22 -> DROP

Existing established SSH connections are preserved by conntrack. The SPA gate is applied to new IPv4 TCP/22 connections.


Security model

The current SPA protocol uses:

HMAC-SHA256

with a randomly generated 32-byte shared authentication key.

The key file must:

  • contain exactly 32 bytes;
  • be a regular file;
  • not be accessible by group or other users.

The server rejects malformed or unauthenticated packets silently.

The request processing pipeline is:

UDP datagram
    |
    v
exact packet length
    |
    v
HMAC-SHA256 verification
    |
    v
protocol parser
    |
    v
authorization policy
    |
    +-- authenticated access IPv4
    +-- observed UDP source IPv4
    +-- duration policy
    +-- service policy
    |
    v
timestamp validation
    |
    v
nonce replay protection
    |
    v
AuthorizedRequest
    |
    v
temporary nftables grant

Authentication and authorization are intentionally separate.

Possession of the shared HMAC key is currently the client identity.


SPA protocol v2

The authenticated request body is 37 bytes:

Offset Size Field
0 4 Magic KDRS
4 1 Protocol version
5 1 Message type
6 8 Unix timestamp
14 16 Random nonce
30 4 Requested IPv4 address
34 1 Service
35 2 Access duration

The body is followed by:

32-byte HMAC-SHA256 tag

Total authenticated datagram size:

37 + 32 = 69 bytes

Multi-byte integers use network byte order.

The HMAC authenticates the entire 37-byte request body.

The protocol authenticates data but does not encrypt it.


Replay protection

A valid SPA request must satisfy both conditions:

  1. its timestamp must be inside the configured clock-skew window;
  2. its 16-byte nonce must not already have been accepted.

Accepted nonces are stored in an in-memory replay cache.

If the replay cache reaches its configured capacity, new requests fail closed.

The replay cache is currently not persisted across daemon restarts. Timestamp validation limits the useful replay window after a restart.


Source address binding

The SPA request contains an authenticated IPv4 address:

access_ip

The daemon also observes the real IPv4 source address of the UDP packet.

Both addresses must match:

authenticated access_ip
        ==
observed UDP source IP

Otherwise the request is rejected.

This prevents an authenticated client from requesting temporary access for an unrelated IPv4 address.

When NAT is involved, the requested address must match the address observed by the server.


nftables design

knockd-rs owns a dedicated table:

table inet knockd_rs

It contains a timed IPv4 set:

ssh_allowed_v4

and a regular SSH gate chain:

ssh_gate_v4

The gate contains the equivalent of:

ip saddr @ssh_allowed_v4 tcp dport 22 accept
tcp dport 22 drop

When enforcement is enabled, a dedicated input base chain is created:

input_guard_v4

It:

  • preserves established/related TCP/22 connections;
  • sends new IPv4 TCP/22 connections to ssh_gate_v4.

Enforcement can be removed without deleting the temporary set or the inactive gate.


Firewall commands

Initialize the dedicated nftables objects:

sudo knockd-rs firewall init

Validate them:

sudo knockd-rs firewall check

Display state:

sudo knockd-rs firewall status

Example:

nftables scaffold: ready
SSH enforcement: disabled
active temporary grants: 0

Before enabling enforcement, the administrator must already have a valid temporary grant.

Example:

sudo knockd-rs firewall enable \
    --safety-ip 192.0.2.42

This intentionally fails if the safety address is not currently present in the temporary grant set.

Disable enforcement:

sudo knockd-rs firewall disable

enable and disable are idempotent.


Requirements

Runtime target:

Linux
Debian 13
nftables
systemd
IPv4

Build requirements:

Rust stable
Cargo

The current implementation invokes:

/usr/sbin/nft

directly and does not execute nftables commands through a shell.


Build from source

Clone the repository:

git clone git@github.com:1posix/knockd-rs.git
cd knockd-rs

Build and validate:

./scripts/build-release.sh

This performs:

cargo fmt --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-features --locked
cargo build --release --locked

The resulting binary is:

target/release/knockd-rs

Do not run Cargo as root.


Installation on Debian

Build first as your normal user:

./scripts/build-release.sh

Then install:

sudo ./scripts/install.sh

The installer creates:

/usr/local/bin/knockd-rs

/etc/knockd-rs/
├── knockd-rs.toml
└── server.key

/etc/systemd/system/
└── knockd-rs.service

It also creates the system account:

knockd-rs

with no interactive login shell.

The service is not started or enabled automatically.


Installing an existing key

To use an existing authentication key:

sudo ./scripts/install.sh \
    --key secrets/generated.key

The installer refuses keys that are not exactly 32 bytes.

An existing:

/etc/knockd-rs/server.key

is never overwritten.

If no key exists and --key is omitted, the installer generates a new one.

Never commit authentication keys to Git.

The client and server must possess the same 32-byte key.

Transfer it between systems using an appropriately secure channel.


Server configuration

Installed configuration:

/etc/knockd-rs/knockd-rs.toml

Default:

[daemon]
listen = "127.0.0.1:4242"
key_file = "/etc/knockd-rs/server.key"

[security]
max_access_duration_secs = 60
max_clock_skew_secs = 30
replay_cache_entries = 4096

The default listener is intentionally loopback-only.

For a server that must receive SPA packets from the network, explicitly configure an appropriate address, for example:

listen = "0.0.0.0:4242"

Only do this after reviewing the host firewall and deployment environment.

Unknown TOML fields are rejected.

Security-related values have hard upper bounds and invalid configurations cause the daemon to fail closed.


Starting the daemon

After reviewing the configuration:

sudo systemctl start knockd-rs

Check:

sudo systemctl status knockd-rs

Logs:

sudo journalctl \
    -u knockd-rs \
    -f

Enable at boot:

sudo systemctl enable knockd-rs

Or install, enable and start in one operation:

sudo ./scripts/install.sh \
    --enable \
    --start

Enabling the systemd service does not automatically enable SSH enforcement.


Sending a knock

Example:

knockd-rs knock \
    --target 192.0.2.10:4242 \
    --key-file ./client.key \
    --access-ip 192.0.2.42

The authenticated access IP must match the IPv4 source address observed by the daemon.

A successful client transmission only means that the authenticated datagram was sent.

The server intentionally does not return an authentication oracle to the network.


Generating a key manually

knockd-rs keygen \
    --output server.key

The command:

  • uses the operating system CSPRNG;
  • creates exactly 32 random bytes;
  • creates the file with restrictive permissions;
  • refuses to overwrite an existing file.

systemd hardening

The supplied service runs as:

User=knockd-rs
Group=knockd-rs

rather than root.

The unit is designed to grant only:

CAP_NET_ADMIN

for nftables administration and applies additional systemd sandboxing including:

NoNewPrivileges
ProtectSystem
ProtectHome
ProtectKernelTunables
ProtectKernelModules
ProtectKernelLogs
ProtectControlGroups
PrivateTmp
PrivateDevices
RestrictNamespaces
RestrictAddressFamilies

The exact deployment should still be validated on the target Debian system before production use.


Fail-safe behavior

The systemd unit executes:

knockd-rs firewall disable

during service shutdown.

The goal is to avoid leaving SSH enforcement active while no SPA daemon is available to create new grants.

Manual emergency rollback:

sudo /usr/local/bin/knockd-rs \
    firewall disable

If necessary, the dedicated nftables table can be removed from a local console:

sudo nft delete table inet knockd_rs

This removes only the table owned by knockd-rs.


Uninstall

Preserve configuration and authentication key:

sudo ./scripts/uninstall.sh

This removes the service, binary and dedicated nftables table.

The following are preserved:

/etc/knockd-rs
knockd-rs system account

Complete removal:

sudo ./scripts/uninstall.sh \
    --purge

--purge also deletes:

/etc/knockd-rs
/etc/knockd-rs/server.key
knockd-rs system account

Be careful: deleting the server key is irreversible unless another copy exists.


Development

Run the complete local validation suite:

cargo fmt
cargo fmt --check
cargo clippy \
    --all-targets \
    --all-features \
    -- \
    -D warnings

cargo test

cargo build --release

The project currently has extensive tests covering:

  • CLI parsing;
  • binary protocol parsing;
  • HMAC authentication;
  • wrong-key rejection;
  • packet mutation;
  • truncated and oversized packets;
  • timestamp boundaries;
  • replay attempts;
  • replay-cache exhaustion;
  • source-address mismatch;
  • authorization duration limits;
  • key generation and permissions;
  • configuration validation;
  • nftables script generation;
  • firewall lifecycle logic.

Real nftables integration tests are intentionally kept separate from unit tests because they require elevated Linux networking privileges.


GitHub Actions

Every push to main and every pull request runs:

rustfmt
clippy
unit tests
release build
Bash syntax validation

The workflow is defined in:

.github/workflows/ci.yml

Current limitations

The current architecture intentionally remains small.

Not yet supported:

  • IPv6;
  • services other than SSH/TCP 22;
  • multiple independent client identities;
  • per-client keys;
  • key IDs;
  • automatic key rotation;
  • asymmetric Ed25519 authentication;
  • persistent replay cache;
  • automatic firewall enforcement at boot;
  • packaged .deb releases;
  • automated privileged nftables integration testing.

These are potential future features, not requirements for the initial v0.1.


Project status

The current development target is:

v0.1.0

Core functionality already implemented includes:

UDP transport
binary SPA protocol v2
HMAC-SHA256
secure key handling
timestamp validation
nonce replay protection
source IPv4 binding
authorization policy
temporary nftables grants
reversible SSH enforcement
TOML configuration
systemd packaging

The remaining v0.1 work is primarily:

real Debian/systemd integration testing
two-machine network testing
final security review
documentation review
release preparation

Security

knockd-rs is security-sensitive software.

Do not rely on SPA as a replacement for:

  • SSH public-key authentication;
  • secure SSH configuration;
  • operating-system updates;
  • least privilege;
  • host firewall policy;
  • monitoring and logging.

SPA is an additional access-control layer.

If you discover a security issue, avoid publishing authentication keys, private infrastructure information or working secrets in a public issue.

About

Lightweight Single Packet Authorization daemon for Linux written in Rust

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages