Procyon Labs

**** COMMODORE 64 BASIC V2 ****

64K RAM SYSTEM 38911 BASIC BYTES FREE

Deploying Forgejo on FreeBSD 15 with Caddy, the Coraza WAF, and PostgreSQL

FreeBSD
Forgejo
Caddy
Coraza WAF
PostgreSQL Database

Abstract

This guide takes a fresh FreeBSD 15.1 VPS to a hardened, internet-facing Forgejo server. Forgejo is a self-hosted Git forge (think “your own GitHub”), written in Go. It handles Git hosting, pull requests, issues, Forgejo Actions CI, and package registries without the heavier stack (Rails, Redis, Sidekiq) that GitLab needs. Here it runs from the FreeBSD package as an rc.d service, with PostgreSQL behind it over a Unix socket and Caddy in front of it, filtered by the Coraza web application firewall (WAF).

The target is a small VPS (4 vCPU, 6 GB RAM, 100 GB NVMe) that holds the authoritative copy of both private and public repositories. Because it is the primary copy rather than a mirror, the guide spends as much time on hardening, backups and ongoing maintenance as it does on installation.

What You Will Build

  • A hardened FreeBSD 15.1 base: a non-root admin account, key-only SSH, and daily update checks.
  • A PostgreSQL 18 database for Forgejo, reachable only through a Unix socket (no TCP listener at all) and tuned for a 6 GB machine.
  • Forgejo (the LTS line) installed from the FreeBSD package, running as the unprivileged git user, with its own SSH server for Git on port 2222.
  • Caddy compiled with the Coraza WAF module and the OWASP Core Rule Set (CRS), with automatic Let’s Encrypt certificates, running as the unprivileged www user.
  • A default-deny pf firewall, with sshguard banning repeat SSH offenders through pf, and IPv6 disabled on the whole system.
  • Nightly off-box backups with restic (or pulled by Kopia from another machine). This part is strongly recommended for a server holding the only copy of your repositories, but no other section of the guide depends on it, so it can be skipped or done later.
  • Weekly update notifications for packages and Caddy, a one-command Caddy rebuild script, and a monthly CRS refresh, all driven by FreeBSD’s periodic system.

Out of Scope: jails (this guide deliberately runs everything directly on the host), ZFS and boot environments (the guide uses UFS), Forgejo Actions runners (these belong on a separate VM, see the end of the guide), email delivery for Forgejo itself (user notifications), SSO or LDAP, high availability, and monitoring beyond the periodic reports.

A Note on Ordering: the steps below are ordered so that nothing can lock you out. SSH hardening happens first and is tested from a second session before the first one is closed. The firewall comes after every service has been started and checked, and before the backup and maintenance sections, so a firewall mistake is never mixed up with a service problem, and it is loaded with a timed escape hatch. Keep the provider’s web console handy throughout; it is your way back in if SSH or the firewall is misconfigured.

Reader Note on Example Values: The hostname (montreal), domain (montreal.procyonlabs.com), admin account (beaker), SSH port (2222) and key file names shown throughout are the values from the reference system. Substitute your own. Commands are shown with a shell prompt so it is clear which account is running them: root@montreal:~# is a root shell on the server, beaker@montreal:~$ is the admin account on the server (using sudo where needed), beaker@workstation:~$ is your own laptop or workstation, and beaker@homelab:~$ is the separate machine that runs Kopia in the optional pull-backup section. The prompt is not part of the command. Example output is shown in separate blocks.

Prerequisites

  • A VPS running FreeBSD 15.1-RELEASE, installed with the traditional distribution sets and Auto (UFS) partitioning. Choose distribution sets rather than the experimental packaged base (pkgbase) option, because this guide patches the base system with freebsd-update, which does not work on a pkgbase system. Enable sshd and NTP in the installer if it offers them.
  • A way to get FreeBSD onto the VPS. Many providers do not list FreeBSD in their reinstall menu, so check yours, and if it is missing, ask support whether they can attach a custom ISO or offer a rescue mode before you start. If they can, a bootable installer is all you need. If they cannot, one documented route is to build a FreeBSD disk image in a local virtual machine and write it to the VPS disk from a rescue environment (see Helpful Links).
  • The provider’s console or rescue access, in case an SSH or firewall change locks you out. This is cheap insurance, so locate it before you start.
  • A domain name you control, and a fully qualified domain name (FQDN) for this server under it. The examples in this guide use montreal.procyonlabs.com, so substitute your own FQDN wherever it appears. DNS must point that name at the VPS’s IPv4 address (an A record, with no AAAA record, since IPv6 is disabled) before you reach Caddy with the Coraza WAF. Because it is a public domain rather than an internal .lan name, Caddy’s automatic Let’s Encrypt certificates work directly, with no internal CA or tls internal needed.
  • An offsite backup target for restic (an S3-compatible bucket, Backblaze B2, or another host you control), or a separate machine running Kopia. Only needed if you do the backup section.
  • An SMTP account for notification mail, preferably with an app-specific password.

1. Base OS Hardening

Patch the Base System and Create an Admin User

Start by patching the base system with freebsd-update, then bringing the package set up to date. A fresh install can be behind on security patches, and some of them touch the kernel, so check whether a reboot is needed before going further. Operating as root day to day is avoided from the very first login, so the baseline packages include sudo and the next step creates an admin account. The package list also includes bash, because FreeBSD’s base system only ships sh, and the admin account below uses bash as its login shell:

root@montreal:~# freebsd-update fetch install
root@montreal:~# freebsd-version -kru
root@montreal:~# pkg update
root@montreal:~# pkg upgrade -y
root@montreal:~# pkg install -y sudo bash curl ca_root_nss

freebsd-version -kru prints the installed kernel, the running kernel, and the userland version. If the installed kernel is newer than the running one, reboot now with shutdown -r now, then log back in.

Create the admin account as a member of wheel, with bash as its shell. On FreeBSD, bash installs to /usr/local/bin/bash, not /bin/bash, so that is the path to use here (a path that does not exist would leave the account unable to log in). Then set its password (needed for sudo, even though SSH will be key-only), and allow the wheel group to use sudo by uncommenting one line:

root@montreal:~# pw useradd beaker -m -s /usr/local/bin/bash -G wheel
root@montreal:~# passwd beaker
root@montreal:~# visudo

visudo opens the sudoers file in vi, the default editor on FreeBSD, and checks the syntax when you save, so a typo cannot lock you out of sudo. If you have not used vi before, the one thing to know is that it has two modes. It starts in command mode, where keys are commands and typing does not insert text. Press i to switch to insert mode, where you can type normally, and press Esc to go back to command mode. Saving and quitting are commands too, so they are typed from command mode:

KeysWhat it does
iEnter insert mode (type text)
EscReturn to command mode
xDelete the character under the cursor (command mode)
/text, then EnterSearch forward for text (n jumps to the next match)
:wq, then EnterSave and quit
:q!, then EnterQuit without saving

In the editor, find the line # %wheel ALL=(ALL:ALL) ALL (search for it with /%wheel ALL=(ALL:ALL) ALL), put the cursor on the #, press x to delete it, then save and quit with :wq.

Keep the clock accurate, since certificates, logs and TOTP codes all depend on it:

root@montreal:~# sysrc ntpd_enable=YES ntpd_sync_on_start=YES
root@montreal:~# service ntpd start

SSH Keys: Generating, Transferring, and Using Them

Two accounts are in play here: root, which may already have a public key installed from when the VPS was provisioned, and beaker, the admin account just created. If beaker does not already have a key pair, it gets generated on beaker‘s own laptop or workstation, never on the server itself. The private key must never be copied to a server or sent over the network in plaintext. If beaker connects from more than one device, generate a separate key pair per device rather than copying one private key between them. That way, losing one device means revoking one key, not rotating access everywhere.

Generate the key pair locally (on the laptop or workstation beaker connects from, not on montreal.procyonlabs.com). The default filename ssh-keygen uses (id_ed25519) works for a single key, but gets confusing once more than one server or purpose is involved, because every future key generated without a name collides with it. The -f flag gives the key a descriptive name instead:

beaker@workstation:~$ ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_montreal -C "beaker@workstation"

ssh-keygen then asks for a passphrase, twice. Set one. The passphrase encrypts the private key on your disk, so a stolen laptop, a leaked backup, or malware that copies your home directory does not hand over a working key. That matters more than usual here: once password login and root login are disabled, this key is the only way into the server, and beaker has sudo. Choose something long that you can remember, such as several random words, because a forgotten passphrase makes the key unusable (the provider’s console is your way back in). The AddKeysToAgent setting in the config example below shows how to avoid retyping it for every connection.

This creates two files in ~/.ssh/: id_ed25519_montreal (the private key: keep it secret and never copy it anywhere) and id_ed25519_montreal.pub (the public key, safe to share and copy to any server being accessed).

Why ed25519? It is a modern elliptic-curve signature algorithm and the sensible default for new SSH keys. It gives roughly the security of a 3072-bit RSA key with a public key of about 68 characters, faster key generation and signing, and no key size or curve parameters to get wrong. OpenSSH has supported it since version 6.5 (2014).

Is It Post-Quantum Safe? No, but your sessions are not exposed today. An authentication key only proves who you are, so an attacker would need a quantum computer at the moment of the attack. The part open to “record now, decrypt later” is the key exchange, and OpenSSH 10.0 and later (shipped with FreeBSD 15) already defaults to a hybrid post-quantum exchange. OpenSSH plans post-quantum signature keys, and until they arrive ed25519 is still the right choice.

Rather than specifying this key by its full path on every command, add an entry to beaker‘s own ~/.ssh/config on the workstation. It maps the key to this specific host automatically. The file is optional and OpenSSH never creates it, so it may not exist yet. SSH also refuses a config file that other users can write to, so create it with restrictive permissions first, then add the entry below with your editor:

beaker@workstation:~$ touch ~/.ssh/config
beaker@workstation:~$ chmod 600 ~/.ssh/config
Host montreal.procyonlabs.com
    User beaker
    IdentityFile ~/.ssh/id_ed25519_montreal
    AddKeysToAgent yes

After that, a plain ssh montreal.procyonlabs.com or git clone against this host uses the correct key without it being specified each time.

AddKeysToAgent yes is what keeps the passphrase from becoming a chore. The first time you connect, SSH asks for the passphrase and hands the unlocked key to ssh-agent, a small background program that holds it in memory, and later connections in the same login session do not ask again. It needs a running agent, which most Linux desktops start at login. Desktop keyring tools (GNOME Keyring, KDE Wallet) can go further and unlock the key at login. To load the key by hand instead, run ssh-add ~/.ssh/id_ed25519_montreal. If a script ever needs to log in unattended, give it its own separate, restricted key without a passphrase instead of removing the passphrase from this one.

With the key pair generated, view the public key so it can be copied exactly, character for character:

beaker@workstation:~$ cat ~/.ssh/id_ed25519_montreal.pub

That prints one line that looks something like this:

ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGVy... beaker@workstation

Copy that entire line, then paste it in place of <PASTE_BEAKERS_PUBLIC_KEY_HERE> below, replacing the placeholder completely rather than editing around it:

root@montreal:~# mkdir -p /home/beaker/.ssh
root@montreal:~# echo "<PASTE_BEAKERS_PUBLIC_KEY_HERE>" > /home/beaker/.ssh/authorized_keys
root@montreal:~# chown -R beaker /home/beaker/.ssh
root@montreal:~# chmod 700 /home/beaker/.ssh && chmod 600 /home/beaker/.ssh/authorized_keys

If a direct SSH session to the server as beaker is not possible yet (the account has no key installed and password login is not set up), paste the key in through the provider’s web console instead.

The authorized_keys file can hold multiple lines, one key per line, if beaker needs to log in from more than one device, such as a laptop and a desktop. Each line is evaluated independently, so any one of them grants access on its own.

Before disabling password authentication or root login, confirm that key-based login actually works. Do this in a second terminal session, without closing the one already connected as root:

beaker@workstation:~$ ssh beaker@montreal.procyonlabs.com

If that connects without a password prompt, the key is in place correctly and it is safe to proceed with the hardening steps below. If it fails, the original root session is still open to fix the problem, instead of being locked out entirely.

As an optional check, you can confirm that the session was set up with a post-quantum key exchange. Connecting verbosely prints the negotiated algorithm, and the line should read kex: algorithm: mlkem768x25519-sha256. This needs OpenSSH 10.0 or later on both ends. OpenSSH 10.1 and later also print a warning at connect time when a connection is not using a post-quantum key exchange, so the absence of a warning is a good sign too:

beaker@workstation:~$ ssh -v beaker@montreal.procyonlabs.com 2>&1 | grep -i "kex: algorithm"

SSH Hardening

PermitRootLogin no and PasswordAuthentication no close the two most commonly attacked paths into a public server: brute forcing root, and brute forcing any password at all. AllowUsers beaker is a whitelist that rejects any account not explicitly listed, even one with valid credentials, as a safety net in case some other account ever ends up with SSH access it should not have. (If you later set up the optional Kopia pull backup, its dedicated backup account has to be added to this line, and that section says so.) LogLevel VERBOSE raises sshd’s logging from the default INFO, so the authentication log (/var/log/auth.log) also records details such as which key was used to log in, which is useful for auditing who accessed the server. (The commented-out LogLevel INFO and SyslogFacility AUTH lines in the stock file are only the defaults, so uncommenting them changes nothing. Avoid the DEBUG levels, which are noisy and log more about user activity than a server needs.) Edit /etc/ssh/sshd_config, setting each of these (change the existing line if one is already present):

root@montreal:~# vi /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
X11Forwarding no
AllowUsers beaker
LogLevel VERBOSE

Check the file for syntax errors first, because a typo here followed by a restart is how lockouts happen. Restart SSH only after confirming you can log in as beaker in a second session (do not close the root session until confirmed):

root@montreal:~# sshd -t
root@montreal:~# service sshd restart

Open one more fresh session as beaker to confirm login still works after the restart. From this point on, the guide works as beaker and uses sudo, and the root session can be closed.

Disable IPv6

If your own network does not support IPv6, there is little reason to run it on the server. Every listener, firewall rule and log line would have a second address family to maintain and check, with no client ever using it. FreeBSD has no single “IPv6 off” switch, because IPv6 is compiled into the stock kernel, so it is turned off by combining a few settings. Each one does a different job:

  • ipv6_activate_all_interfaces="NO" is already FreeBSD’s default, but setting it explicitly documents the intent. With it, every interface that has no ifconfig_<interface>_ipv6 line in /etc/rc.conf is created with the IFDISABLED flag, which turns off all IPv6 functionality on that interface, including link-local addresses.
  • ip6addrctl_policy="ipv4_prefer" sets the address selection policy so outgoing connections prefer IPv4 whenever a name resolves to both address types. The default (AUTO) already picks IPv4 here, but this removes the guesswork.
  • net.inet6.ip6.accept_rtadv=0 stops the kernel from accepting IPv6 router advertisements (the mechanism behind SLAAC autoconfiguration). It is off by default, so this is a safeguard.
  • net.inet6.ip6.auto_linklocal=0 is the default for the per-interface flag that assigns an automatic link-local address. It only affects interfaces created after the setting is applied, so the IFDISABLED flag above is what actually covers the interface that exists at boot. It is a second layer, not the main one.

If you selected IPv6 in the installer’s network screen, the installer wrote an ifconfig_<interface>_ipv6 line (typically inet6 accept_rtadv), and that line overrides all of the above for that interface. Look for it first:

beaker@montreal:~$ grep ipv6 /etc/rc.conf

If it shows a line such as ifconfig_vtnet0_ipv6="inet6 accept_rtadv", remove it (use your own interface name):

beaker@montreal:~$ sudo sysrc -x ifconfig_vtnet0_ipv6

Now apply the settings. sysrc writes the rc.conf values, and tee -a appends to sysctl.conf as root. (A plain cat >> /etc/sysctl.conf under sudo would fail, because the redirection is performed by your own unprivileged shell, not by sudo.)

beaker@montreal:~$ sudo sysrc ipv6_activate_all_interfaces="NO" ip6addrctl_policy="ipv4_prefer"
beaker@montreal:~$ sudo tee -a /etc/sysctl.conf <<'EOF'
net.inet6.ip6.accept_rtadv=0
net.inet6.ip6.auto_linklocal=0
EOF
beaker@montreal:~$ sudo service sysctl reload

The interface flag is applied when the interface is created, so the change fully takes effect at the next boot. Reboot instead of running service netif restart over SSH. Restarting the network from inside an SSH session drops the connection while the interface is reconfigured, and it can also drop the default route, which then needs service routing restart to come back. A reboot avoids all of that:

beaker@montreal:~$ sudo shutdown -r now

After logging back in, confirm that the interface carries no IPv6 address and shows the IFDISABLED flag, that no IPv6 routes exist, and that the address selection policy prefers IPv4 (substitute your interface name):

beaker@montreal:~$ ifconfig vtnet0 | grep -E 'inet6|nd6'
beaker@montreal:~$ netstat -rn -f inet6
beaker@montreal:~$ ip6addrctl

The first command should show no inet6 line and an nd6 options= line that includes IFDISABLED. The routing table should hold nothing but the loopback entries. When you create the DNS record for this server later, create an A record only, with no AAAA record.

Update Notifications

Without a check, patches for known vulnerabilities sit unapplied until someone remembers to look. FreeBSD’s tooling differs from Debian’s unattended-upgrades in one important way: freebsd-update cron downloads available patches and emails root, but it does not install them. That is deliberate, because kernel patches need a reboot and a human should choose when it happens. The daily pkg audit check in the standard periodic security report covers vulnerable packages. Add one line to /etc/crontab:

beaker@montreal:~$ sudo vi /etc/crontab
@daily root freebsd-update cron

When the notification arrives (mail delivery is set up later in Set Up Mail Delivery, and until then it lands in root’s local mailbox), apply it with sudo freebsd-update install, and reboot if it says the kernel was updated.

2. Storage Layout (Expansion-Ready)

This guide uses UFS, the filesystem the installer’s Auto (UFS) option creates. On a single virtual disk with no redundancy, ZFS’s self-healing has nothing to heal from, and ZFS’s memory cache competes with PostgreSQL on a 6 GB machine, so UFS is a reasonable fit. The trade-off is that there are no boot environments (bectl), so the “snapshot, upgrade, roll back” workflow is replaced by backups: take a fresh backup (see Off-Box Backups) before any significant upgrade, or at the very least a manual copy of the database and /var/db/forgejo if you skipped that section.

There is nothing to do in this section during the initial setup. The installer’s root filesystem already holds everything, and the rest of the guide works as written. This section explains the layout and, for later, how to grow storage without reconfiguring anything.

The Forgejo package keeps everything it creates under /var/db/forgejo (repositories, LFS objects, attachments), and every path in this guide points there. That single location is what makes growing storage later a clean swap: whichever method you use, the data ends up at the same path, so no configuration changes are needed anywhere else. PostgreSQL’s data is separate, in /var/db/postgres/data18 on the root filesystem, and stays where it is. Forgejo’s repositories and files are what grow over time.

If you outgrow the 100 GB disk later, the right method depends on what your provider offers:

  • Option A: Expand the existing disk. Use this when the provider can enlarge the VPS’s current virtual disk (a plan upgrade, or a resize in the control panel). The disk keeps its device name, and the partition and filesystem are grown in place.
  • Option B: Add a new disk. Use this when the provider sells separate block-storage volumes that attach to the VPS as a second disk. The new disk is formatted, the Forgejo data is copied onto it, and it is mounted at /var/db/forgejo.

The steps below are for those later situations only. Skip them for now.

Option A: Expand the Existing Disk

After the provider enlarges the disk, the operating system sees a bigger disk, but the partition table still describes the old size, and the new space sits unallocated at the end. Start by looking at the current layout. GPT keeps a backup copy of its table at the very end of the disk, so after the disk grows, gpart marks the table CORRUPT until it is recovered:

beaker@montreal:~$ gpart show

Recover the table so the backup copy moves to the new end of the disk (use your disk’s name, da0 here, from the gpart show output):

beaker@montreal:~$ sudo gpart recover da0

A partition can only grow into free space directly behind it. If the root (freebsd-ufs) partition is the last one on the disk, resize it into the free space. Use the index of the freebsd-ufs partition shown by gpart show. The 2 below is only an example:

beaker@montreal:~$ sudo gpart resize -i 2 da0

If another partition, such as swap, comes after the root partition, there is no free space directly behind it. In that case, turn swap off and delete the swap partition first (sudo swapoff -a, then sudo gpart delete -i <swap index> da0), resize the root partition as above, and then recreate swap in the remaining space with sudo gpart add -t freebsd-swap da0 and sudo swapon -a. Check that /etc/fstab still names the right swap device.

Finally, grow the filesystem to fill the enlarged partition, then confirm the new size. growfs works on a mounted filesystem, so no reboot is needed:

beaker@montreal:~$ sudo growfs /
beaker@montreal:~$ df -h /

Option B: Add a New Disk

Use this method when the provider attaches a second disk. First find the new disk’s device name (da1 below, but it depends on the provider):

beaker@montreal:~$ geom disk list

Partition and format the new disk with a GPT label, so that the mount does not depend on device numbering, which can change between boots. -U turns on soft updates:

beaker@montreal:~$ sudo gpart create -s gpt da1
beaker@montreal:~$ sudo gpart add -t freebsd-ufs -a 1m -l forgejo da1
beaker@montreal:~$ sudo newfs -U /dev/gpt/forgejo

Next, copy the existing data across. The new disk is mounted temporarily at /mnt, and Forgejo is stopped first so that nothing changes during the copy. rsync is not in the base system, so install it first:

beaker@montreal:~$ sudo pkg install -y rsync
beaker@montreal:~$ sudo mount /dev/gpt/forgejo /mnt
beaker@montreal:~$ sudo service forgejo stop
beaker@montreal:~$ sudo rsync -a /var/db/forgejo/ /mnt/
beaker@montreal:~$ sudo umount /mnt

Now put the new disk in place at the original path. Mounting a disk over a directory hides what was in it, so the old copy would keep using space on the root filesystem while being invisible. Move it aside first, so it can be deleted after the move is confirmed, and create an empty directory to serve as the mount point:

beaker@montreal:~$ sudo mv /var/db/forgejo /var/db/forgejo.old
beaker@montreal:~$ sudo mkdir /var/db/forgejo

Add a permanent entry to /etc/fstab, so that the disk mounts at every boot, then mount it and start Forgejo again:

beaker@montreal:~$ sudo vi /etc/fstab
/dev/gpt/forgejo    /var/db/forgejo    ufs    rw    2    2
beaker@montreal:~$ sudo mount /var/db/forgejo
beaker@montreal:~$ sudo service forgejo start
beaker@montreal:~$ df -h /var/db/forgejo

Check that Forgejo works (clone, push and pull a repository). If you have set up the nightly backup from Off-Box Backups, let one run to completion on the new disk as well. Then delete the old copy to reclaim its space:

beaker@montreal:~$ sudo rm -rf /var/db/forgejo.old

3. PostgreSQL, Tuned for a 6 GB Machine

Install PostgreSQL 18 from the FreeBSD package repository and enable the service. FreeBSD’s initdb defaults to trust authentication for local connections, which would let any local user connect as any database role, including the superuser. That is the opposite of what this guide wants, so the initialization flags below add --auth-local=peer. The other two flags are the package’s defaults, kept so the command does not change them:

beaker@montreal:~$ sudo pkg install -y postgresql18-server
beaker@montreal:~$ sudo sysrc postgresql_enable=YES
beaker@montreal:~$ sudo sysrc postgresql_initdb_flags="--encoding=utf-8 --lc-collate=C --auth-local=peer --auth-host=scram-sha-256"
beaker@montreal:~$ sudo service postgresql initdb
beaker@montreal:~$ sudo service postgresql start

The data directory is /var/db/postgres/data18.

Forgejo runs as the system user git, and PostgreSQL’s peer authentication maps the operating system user name to a database role of the same name. So the database role is named git too. That lets Forgejo authenticate over the Unix socket with no password at all: no TCP exposure, and nothing travelling over a connection to intercept.

beaker@montreal:~$ sudo -u postgres createuser git
beaker@montreal:~$ sudo -u postgres createdb -O git forgejo

The git operating system user does not exist yet (the Forgejo package creates it in Forgejo: FreeBSD Package, Managed by rc.d), so the connection test for this step comes after that.

Memory and Connection Tuning

The shipped defaults assume more RAM than this machine has, and each of the settings below controls something different:

  • shared_buffers is memory PostgreSQL directly allocates for caching. Raising it from the very conservative 128 MB default helps performance without costing much on a 6 GB machine.
  • effective_cache_size allocates nothing at all. It is only a hint for the query planner, so it is set to an honest estimate of what is actually free, since Forgejo, Caddy and the WAF share this RAM too.
  • max_connections is lowered because a single Forgejo instance never needs 100 concurrent connections, and capping it reserves memory for what is actually used.
  • maintenance_work_mem is raised slightly because it is used one operation at a time (VACUUM, index builds) rather than multiplied per connection, so more here is cheap.
  • listen_addresses is set to an empty string, which tells PostgreSQL not to open any TCP listener at all. The default, localhost, still listens on the loopback address.

PostgreSQL reads the last occurrence of a setting, so appending to the end of postgresql.conf overrides the defaults earlier in the file. Run the append as the postgres user so the file keeps its ownership:

beaker@montreal:~$ sudo -u postgres tee -a /var/db/postgres/data18/postgresql.conf <<'EOF'

# Forgejo tuning for a 6 GB machine
listen_addresses = ''
shared_buffers = 512MB
effective_cache_size = 2GB
work_mem = 8MB
maintenance_work_mem = 128MB
max_connections = 40
EOF
beaker@montreal:~$ sudo service postgresql restart

Why PostgreSQL Has No Network Listener

PostgreSQL can accept connections over the network (TCP) or through a local Unix socket, which is a file-based connection only reachable by processes on the same machine. Since Forgejo and PostgreSQL run on the same server, there is no reason to use the network at all: Forgejo connects through the Unix socket, so nothing is exposed to the network. There is nothing to leak if a firewall rule ever slips, and nothing for a port scan to find. On FreeBSD the socket lives in /tmp by default (as /tmp/.s.PGSQL.5432), and that is the path Forgejo’s HOST setting points at below.

4. Forgejo: FreeBSD Package, Managed by rc.d

Install the Package

FreeBSD packages Forgejo in two tracks. forgejo is the current stable line, and forgejo-lts follows the long-term-support line. For a server meant to be carefully managed and low-churn, the LTS line fits better: fewer changes to validate, fewer opportunities to introduce regressions on a box you want to be boring. (LTS 15 is supported into mid-2027 as of this writing.)

beaker@montreal:~$ sudo pkg install -y forgejo-lts

The package installs the binary at /usr/local/sbin/forgejo, creates an unprivileged git user and group, and provides the forgejo service script. It also places a sample configuration under /usr/local/etc/forgejo/conf/, which this guide ignores in favor of its own. Everything Forgejo writes lives under /var/db/forgejo, and logs go to /var/log/forgejo.

The service script uses the git account’s home directory as HOME, and Forgejo writes a small Git configuration file there. First show the account. The home directory is the second-to-last colon-separated field of the output (on the reference system it is /usr/local/git):

beaker@montreal:~$ pw usershow git

Then confirm that the home directory it shows exists and is writable by git (substitute the path from the output above if it differs from /usr/local/git):

beaker@montreal:~$ ls -ld /usr/local/git

If the home directory shown does not exist, create it:

beaker@montreal:~$ sudo mkdir -p /usr/local/git
beaker@montreal:~$ sudo chown git:git /usr/local/git

Now confirm that the database role from the previous section works for this user over the socket:

beaker@montreal:~$ sudo -u git psql -d forgejo -c '\conninfo'
     Connection Information
      Parameter       |  Value  
----------------------+---------
 Database             | forgejo
 Client User          | git
 Socket Directory     | /tmp
 Server Port          | 5432
 Options              | 
 Protocol Version     | 3.0
 Password Used        | false
 GSSAPI Authenticated | false
 Backend PID          | 2992
 SSL Connection       | false
 Superuser            | off
 Hot Standby          | off
(12 rows)

The Socket Directory of /tmp confirms the connection went through the Unix socket, Password Used | false confirms peer authentication did the work, and Superuser | off shows the git role has no more rights than it needs. The Backend PID will differ on your system.

Permissions

A dedicated, unprivileged account keeps Forgejo confined to what this one low-privilege user can touch. It never runs as root, and it should not be able to change its own configuration. The configuration directory is owned by root, with the git group allowed to read it, and 750 keeps everyone else out, since app.ini will contain secrets:

beaker@montreal:~$ sudo chown root:git /usr/local/etc/forgejo /usr/local/etc/forgejo/conf
beaker@montreal:~$ sudo chmod 750 /usr/local/etc/forgejo /usr/local/etc/forgejo/conf

Generate Secrets

This server is on the public internet, so it should never expose Forgejo’s browser-based install page, where the first visitor could claim the admin account. Instead, the configuration below sets INSTALL_LOCK = true and supplies the four secrets Forgejo would otherwise generate during that install. Generate them now and keep the output handy for the next step:

beaker@montreal:~$ sudo -H -u git /usr/local/sbin/forgejo generate secret SECRET_KEY
beaker@montreal:~$ sudo -H -u git /usr/local/sbin/forgejo generate secret INTERNAL_TOKEN
beaker@montreal:~$ sudo -H -u git /usr/local/sbin/forgejo generate secret JWT_SECRET
beaker@montreal:~$ sudo -H -u git /usr/local/sbin/forgejo generate secret LFS_JWT_SECRET

Configuration

A few settings are worth explaining before you write the file:

  • HTTP_ADDR = 127.0.0.1 means Forgejo only listens locally. It is never reachable directly from the internet, only through Caddy in front of it.
  • SSH_PORT = 2222 is separate from the machine’s admin SSH on port 22. Forgejo runs its own SSH server for git clone and git push over SSH, distinct from the one you log into the server with.
  • HOST = /tmp under [database] is the PostgreSQL socket directory from PostgreSQL, Tuned for a 6 GB Machine: no network connection and no password over the wire.
  • DB_RETRIES and DB_RETRY_BACKOFF make Forgejo keep trying to reach the database for a short while at startup. FreeBSD’s rc system does not strictly order Forgejo after PostgreSQL at boot, so without this a slow database start could make Forgejo give up.
  • SCRIPT_TYPE = bash makes Forgejo write its Git hooks for bash, which is Forgejo’s default. FreeBSD’s base system does not include bash, but Patch the Base System and Create an Admin User installed it, and the service script puts /usr/local/bin on Forgejo’s PATH.
  • DISABLE_REGISTRATION = true stops strangers from creating accounts on a public server. Create accounts yourself from the admin CLI or the admin panel.
  • LFS_START_SERVER = true turns on Git LFS support, which is off by default.

Create /usr/local/etc/forgejo/conf/app.ini, replacing each <...> placeholder with the matching generated secret:

beaker@montreal:~$ sudo vi /usr/local/etc/forgejo/conf/app.ini
APP_NAME = Forgejo
RUN_USER = git
RUN_MODE = prod

[server]
DOMAIN           = montreal.procyonlabs.com
ROOT_URL         = https://montreal.procyonlabs.com/
HTTP_ADDR        = 127.0.0.1
HTTP_PORT        = 3000
SSH_DOMAIN       = montreal.procyonlabs.com
SSH_PORT         = 2222
START_SSH_SERVER = true
SCRIPT_TYPE      = bash
LFS_START_SERVER = true
LFS_JWT_SECRET   = <LFS_JWT_SECRET>

[database]
DB_TYPE          = postgres
HOST             = /tmp
NAME             = forgejo
USER             = git
DB_RETRIES       = 20
DB_RETRY_BACKOFF = 3s

[security]
INSTALL_LOCK   = true
SECRET_KEY     = <SECRET_KEY>
INTERNAL_TOKEN = <INTERNAL_TOKEN>

[oauth2]
JWT_SECRET = <JWT_SECRET>

[service]
DISABLE_REGISTRATION = true

[repository]
ROOT = /var/db/forgejo/forgejo-repositories

[lfs]
PATH = /var/db/forgejo/data/lfs

[session]
PROVIDER = file

[log]
ROOT_PATH = /var/log/forgejo
MODE      = console, file

Lock the file down so only root can write it and only the git group can read it:

beaker@montreal:~$ sudo chown root:git /usr/local/etc/forgejo/conf/app.ini
beaker@montreal:~$ sudo chmod 640 /usr/local/etc/forgejo/conf/app.ini

Enable and Start the Service

With the configuration in place, Forgejo still is not set up to run as a persistent service. sysrc writes the enable line into /etc/rc.conf so it starts at boot, and the service script runs a forgejo doctor check before every start. If the configuration has a problem, the check refuses to start the service and prints why, which is the first place to look when something is wrong. The service script sends Forgejo’s console output to syslog, so startup messages land in /var/log/messages:

beaker@montreal:~$ sudo sysrc forgejo_enable=YES
beaker@montreal:~$ sudo service forgejo start
beaker@montreal:~$ sudo service forgejo status
beaker@montreal:~$ curl -I http://127.0.0.1:3000

Forgejo’s SSH daemon binds port 2222 directly. It is not proxied by Caddy, because Caddy cannot proxy raw SSH. That port is opened on the firewall separately, in the firewall section below.

What Replaces the systemd Sandbox. On Linux, this service would run inside a systemd sandbox with a read-only filesystem. FreeBSD’s rc.d has no such feature, and this guide does not use jails, so Forgejo’s isolation comes from three things: it runs as an unprivileged user that cannot write its own configuration, the pf firewall exposes only the ports the deployment needs, and /var/db/forgejo is the only tree it owns. Two consequences are worth knowing. rc.d does not restart a crashed service the way Restart=on-failure does, so check on both services with sudo service forgejo status and sudo service caddy status after any unexpected reboot or crash. Use sudo for the Caddy check in particular: Caddy’s runtime directory, /var/run/caddy, is private to the www user, so without sudo the status command cannot read the process ID file and reports “caddy is not running” even when Caddy is up. And if you later want stronger isolation, a jail is the natural next step.

Create the First Admin Account

Since the web install page is locked, create the admin account from the command line, running as the git user and pointing at the config file. --random-password generates a password and prints it, which keeps it out of your shell history. Replace <name> and <email> with the username and email address you want for the admin account (leave off the angle brackets); everything else is typed exactly as shown:

beaker@montreal:~$ sudo -H -u git /usr/local/sbin/forgejo admin user create --admin --username <name> --email <email> --random-password --config /usr/local/etc/forgejo/conf/app.ini

Enable two-factor authentication on that account as soon as you can sign in. Do this before the server is reachable from the internet.

5. Caddy with the Coraza WAF

Caddy’s stock binary does not support third-party modules like Coraza, because plugins have to be compiled in at build time. xcaddy is a small build tool from the Caddy project that automates exactly this: it downloads Caddy’s source, pulls in whichever plugins you specify, and compiles a custom binary with them built in, without you hand-managing Go dependencies. Building Caddy with the Coraza module adds WAF-grade request inspection while keeping Caddy’s automatic HTTPS, so there is no need to switch to a different reverse proxy.

FreeBSD does package Caddy, but the package is the stock build with no custom modules, so it cannot include Coraza. This guide still installs the caddy package, but only for what comes with it: the www user, the rc.d service script, and the directory layout. The custom binary is installed under a different name, caddy-coraza, and the service script is pointed at it, so a routine pkg upgrade can never replace the WAF-enabled binary with a stock one. If you do not need the WAF, the plain caddy package is simpler and gets updates through pkg.

Why Coraza and Not ModSecurity

ModSecurity is the original open-source WAF engine, and Coraza is a newer one written in Go that reads the same rule language (SecLang). Both run the OWASP Core Rule Set, so the rules and tuning in this guide apply to either. The difference is where they run: ModSecurity ships as an Apache module or as a library for Nginx, and there is no ModSecurity connector for Caddy. Coraza has one, coraza-caddy, which compiles the engine into the Caddy binary. Coraza is also an actively developed OWASP project that passes the full CRS v4 test suite.

The trade-off is that Coraza is the younger engine, and because it is compiled in, a newer Coraza means a rebuild, covered in Ongoing Maintenance: Caddy, Coraza, and CRS. Since both engines share SecLang, any exclusions you write carry over if you ever move to ModSecurity.

Build Caddy

beaker@montreal:~$ sudo pkg install -y go git caddy portacl-rc
beaker@montreal:~$ go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest
beaker@montreal:~$ sudo mv $(go env GOPATH)/bin/xcaddy /usr/local/bin/xcaddy
beaker@montreal:~$ cd /tmp
beaker@montreal:/tmp$ xcaddy build --with github.com/corazawaf/coraza-caddy/v2
beaker@montreal:/tmp$ sudo mv caddy /usr/local/sbin/caddy-coraza
beaker@montreal:/tmp$ cd ~

Moving xcaddy itself into /usr/local/bin makes it available in any future shell session without a PATH change. That is useful later if you rebuild Caddy to add another module or pick up a new Coraza version.

Get the OWASP Core Rule Set

The OWASP Core Rule Set (CRS) is the industry-standard ruleset that ModSecurity uses, and Coraza is built to be compatible with it. The Coraza module also embeds its own copy of CRS inside the binary. This guide clones CRS onto disk instead, so the rules can be refreshed with git pull and tuned with your own exclusions without rebuilding Caddy:

beaker@montreal:~$ sudo mkdir -p /usr/local/etc/caddy/coraza
beaker@montreal:~$ sudo git clone https://github.com/coreruleset/coreruleset /usr/local/etc/caddy/coraza/coreruleset
beaker@montreal:~$ sudo cp /usr/local/etc/caddy/coraza/coreruleset/crs-setup.conf.example /usr/local/etc/caddy/coraza/coreruleset/crs-setup.conf

The base Coraza settings (coraza.conf-recommended) come from the copy embedded in the binary. That is what the @ prefix and the load_owasp_crs line in the Caddyfile below are for. The CRS clone stays owned by root, so root’s monthly refresh job can run git pull on it, and Caddy only needs read access.

The Caddyfile

Start in SecRuleEngine DetectionOnly. This logs what CRS would have blocked without actually blocking anything. Run it this way for one to two weeks of real Git, LFS and API traffic, review the Coraza audit log and the Caddy access log for false positives, add targeted exclusions, and only then switch to SecRuleEngine On. Git’s binary payloads and LFS uploads are exactly the kind of traffic generic CRS rules sometimes misfire on. Also check the request body limit directives in the embedded recommended config before switching to blocking, since large pushes and LFS uploads are the requests most likely to run into them.

The log block keeps Caddy’s access log on disk. Caddy rotates its own log files, so no extra rotation entry is needed for it. The Coraza audit log is written by Coraza rather than Caddy, so it is handled separately in the log monitoring section, which sets up weekly rotation for it. The SecAuditLogParts ABFHZ line keeps each audit entry to the timestamp, request headers, response headers and matched rules. The recommended config also records the full response body, which for a busy public server means every scanner’s 404 page is stored in full and the log grows far faster than it needs to. It comes after the Include line on purpose, so that it overrides the recommended setting. The audit log uses Coraza’s default Native layout, which spans several lines per entry. Coraza also offers JSON-based formats, but they did not work on the version this guide was tested with (Coraza v3.8.1, as built by xcaddy): in testing, JSON wrote no entries at all, JsonLegacy wrote entries with the rule messages left empty, and OCSF made Caddy fail the requests it tried to audit-log. If you ship these logs to a collector, plan for the native layout. In the global block, grace_period 10s tells Caddy to force-close any connections still open ten seconds after a stop or restart. Without it, Caddy waits indefinitely for every client to disconnect, and on a public server a scanner holding a connection open can make service caddy restart hang.

The package ships a sample Caddyfile that serves a placeholder site on localhost. Replace its entire contents with the block below rather than adding to it. The global options block must come first in the file, and the sample’s localhost site would otherwise keep serving (and logging to the same access.log) alongside yours. In FreeBSD’s vi, type :%d and press Enter to delete every line, then press i to enter insert mode and paste.

beaker@montreal:~$ sudo vi /usr/local/etc/caddy/Caddyfile
{
    order coraza_waf first
    grace_period 10s
}

montreal.procyonlabs.com {
    coraza_waf {
        load_owasp_crs
        directives `
            Include @coraza.conf-recommended
            SecRuleEngine DetectionOnly
            SecAuditLogParts ABFHZ
            SecAuditLog /var/log/coraza/coraza-audit.log
            Include /usr/local/etc/caddy/coraza/coreruleset/crs-setup.conf
            Include /usr/local/etc/caddy/coraza/coreruleset/rules/*.conf
        `
    }

    reverse_proxy 127.0.0.1:3000 {
        # LFS and large pushes need generous timeouts
        transport http {
            read_timeout 300s
            write_timeout 300s
        }
    }

    log {
        output file /var/log/caddy/access.log {
            roll_size 50MiB
            roll_keep 8
        }
    }
}

Binding Ports 80 and 443 as an Unprivileged User

Unix systems reserve ports below 1024 for root. Rather than run an internet-facing web server as root, FreeBSD’s mac_portacl policy lets named users bind specific ports. The portacl-rc package (installed above) turns a few rc.conf lines into the right rules. Caddy needs TCP 80 and 443 for HTTP and HTTPS, and UDP 443 for HTTP/3 (QUIC), which Caddy enables by default:

beaker@montreal:~$ sudo sysrc portacl_users+=www
beaker@montreal:~$ sudo sysrc portacl_user_www_tcp="http https"
beaker@montreal:~$ sudo sysrc portacl_user_www_udp="https"
beaker@montreal:~$ sudo service portacl enable
beaker@montreal:~$ sudo service portacl start

Configure the Service

The package’s service script runs Caddy as root by default, and its own comments recommend an unprivileged user instead. These settings run it as www, point it at the custom binary and the Caddyfile above, and enable it. The script creates the state directory (/var/db/caddy, where certificates are stored) and the log directory (/var/log/caddy) with the right owner on every start:

beaker@montreal:~$ sudo sysrc caddy_enable=YES
beaker@montreal:~$ sudo sysrc caddy_user=www caddy_group=www
beaker@montreal:~$ sudo sysrc caddy_command=/usr/local/sbin/caddy-coraza
beaker@montreal:~$ sudo sysrc caddy_config=/usr/local/etc/caddy/Caddyfile

Format the Caddyfile with Caddy’s own formatter. It only changes whitespace, but without it every validate and reload prints a warning that the file is not formatted, and the monthly CRS job below would repeat that warning in its email each time:

beaker@montreal:~$ sudo /usr/local/sbin/caddy-coraza fmt --overwrite /usr/local/etc/caddy/Caddyfile

Validate the configuration as www before starting, so that any log file Caddy opens during validation is created with the right owner. The log directories have to exist first. The WAF audit log gets its own directory, /var/log/coraza, separate from Caddy’s own logs. That keeps it at a fixed, predictable path for log collectors and lets you set its permissions independently. It records the headers of flagged requests, which can include cookies and tokens, so 750 keeps other local users out. Unlike /var/log/caddy, nothing in the service script creates this directory, so it must exist before Caddy starts:

beaker@montreal:~$ sudo mkdir -p /var/log/caddy /var/log/coraza
beaker@montreal:~$ sudo chown www:www /var/log/caddy /var/log/coraza
beaker@montreal:~$ sudo chmod 750 /var/log/coraza
beaker@montreal:~$ sudo -u www /usr/local/sbin/caddy-coraza validate --config /usr/local/etc/caddy/Caddyfile --adapter caddyfile
beaker@montreal:~$ sudo service caddy start
beaker@montreal:~$ sudo service caddy status

On first start, Caddy requests a Let’s Encrypt certificate for the domain. This needs DNS to already point at the VPS, and ports 80 and 443 to be reachable. The firewall has not been enabled yet, so they are.

Review the Detection-Only Logs Before Enabling Blocking

While SecRuleEngine is DetectionOnly, Coraza records every request that CRS would have blocked in /var/log/coraza/coraza-audit.log without interfering with it. Use Forgejo normally for a week or two (clones, pushes, pull requests, LFS uploads, the API) and read the log now and then. Entries from your own legitimate activity are false positives, and each one needs a targeted exclusion (see Tuning Coraza and CRS) before blocking is turned on, because with blocking enabled those same requests would fail:

Each audit entry is split into lettered parts (--abc123-A--, -B-- and so on): A is the timestamp and client address, B the request, F the response headers, and H the rules that matched (Z only marks the end of the entry). The full response body, part E, is deliberately left out by the ABFHZ setting. The log records every request that got a 4xx or 5xx response, whether or not a rule matched, so expect it to fill with internet scanners probing for WordPress, .env files and admin consoles that get a plain 404 from Forgejo. Those entries have an empty H part and can be ignored. The ones that matter are the entries with rule matches, which you can pull out because their lines start with [client:

beaker@montreal:~$ sudo grep '^\[client' /var/log/coraza/coraza-audit.log

A match looks like this: Coraza: Warning. Restricted File Access Attempt ... [id "930130"] ... [data "Matched Data: .env found within REQUEST_FILENAME: /.env"] ... [uri "/.env"]. The id is the CRS rule number you would exclude, data shows what triggered it, and uri shows which request. Expect rule 949110 (Inbound Anomaly Score Exceeded) to appear alongside the specific rule on the same request. It is CRS’s running total for that request, not a separate attack. A scanner asking for /.env is a correct detection. A match on a URL you actually use (a push, an API call, a wiki edit) is a false positive. To see which rules fire most often:

beaker@montreal:~$ sudo grep -o '\[id "[0-9]*"\]' /var/log/coraza/coraza-audit.log | sort | uniq -c | sort -rn

When the log only shows traffic you do not recognize, such as scanners and exploit probes, switch to blocking by changing SecRuleEngine DetectionOnly to SecRuleEngine On in the Caddyfile, then restart Caddy:

beaker@montreal:~$ sudo vi /usr/local/etc/caddy/Caddyfile
beaker@montreal:~$ sudo service caddy restart

Use Forgejo again right after the switch, including a push and an LFS upload if you use LFS, and keep an eye on the audit log for the first few days.

6. Firewall: pf, Default-Deny

pf is FreeBSD’s built-in packet filter, and it fits this server for the same reason PostgreSQL is Unix-socket-only rather than network-exposed: this is a static, single-purpose machine whose ruleset is not expected to change at runtime. A default-deny policy means only the ports this deployment explicitly needs are reachable. Everything else is dropped by default, rather than relying on remembering to close things later. ICMP is accepted so that ping and path MTU discovery keep working. IPv6 is disabled on this server (see Disable IPv6), so the ruleset deliberately has no IPv6 rules, and the default-deny policy drops any IPv6 packet that did arrive.

Two details to set before writing the file. First, find the network interface name with ifconfig -l, because it depends on how the VPS is virtualized (vtnet0 for virtio, vmx0 or em0 for others), and set ext_if to match. Second, the <sshguard> table in the ruleset is the list of addresses the SSH ban tool (set up below) adds repeat offenders to, and the block in quick from <sshguard> rule is what actually shuts them out. FreeBSD does not ship an /etc/pf.conf, so vi creates it as a new file:

beaker@montreal:~$ ifconfig -l
beaker@montreal:~$ sudo vi /etc/pf.conf
ext_if = "vtnet0"
tcp_ports = "{ 22, 2222, 80, 443 }"

set skip on lo0
set block-policy drop

table <sshguard> persist

block in all
block in quick from <sshguard>

pass in inet proto icmp

pass in on $ext_if proto tcp to port $tcp_ports   # 22 admin SSH, 2222 Forgejo git SSH, 80 ACME/redirect, 443 HTTPS
pass in on $ext_if proto udp to port 443          # HTTP/3 (QUIC)

pass out all keep state

PostgreSQL needs no firewall rule. It is Unix-socket-only, so it is invisible to the network entirely. Consider a non-standard port or rate limiting for admin SSH (22) as a later improvement.

Load It Safely

Loading a restrictive ruleset over SSH can cut off your own session, because connections that existed before pf started have no state in its tables. So the sequence below loads the pf kernel module and checks the syntax first (pfctl needs the module loaded to run, even for a syntax-only check, and fails with “Failed to open netlink” otherwise), then schedules pfctl -d (disable pf) to run in five minutes as a timed escape hatch, then loads the rules. Open a new SSH session; if it connects, cancel the escape hatch. If anything is wrong, the firewall turns itself off and you can reconnect. The at command needs its job spool, which exists by default on a standard install; if at is unavailable, keep the provider console open instead.

The Escape Hatch Is Not Exact. FreeBSD runs queued at jobs from cron through atrun, which fires every five minutes, so a job scheduled for “now + 5 minutes” can actually run anywhere from about five to ten minutes later. Do your login test promptly, and do not read a firewall that is still enabled after five minutes as proof that the escape hatch failed:

beaker@montreal:~$ sudo kldload pf
beaker@montreal:~$ sudo pfctl -nf /etc/pf.conf
beaker@montreal:~$ echo "pfctl -d" | sudo at now + 5 minutes
beaker@montreal:~$ sudo sysrc pf_enable=YES pflog_enable=YES
beaker@montreal:~$ sudo service pf start
beaker@montreal:~$ sudo service pflog start

From a second terminal on your workstation, confirm a fresh login works:

beaker@workstation:~$ ssh beaker@montreal.procyonlabs.com

Then, in the first session, list the pending escape-hatch job and remove it:

beaker@montreal:~$ sudo atq
beaker@montreal:~$ sudo atrm <job-number>

Finally, confirm that pf is enabled and that the ruleset you wrote is the one loaded. The first line of pfctl -si should read Status: Enabled, and pfctl -sr should list your rules:

beaker@montreal:~$ sudo pfctl -si | head -n 1
beaker@montreal:~$ sudo pfctl -sr

SSH Ban Tool: sshguard

Key-only authentication already means brute-force login attempts cannot succeed, but a public SSH port still gets scanned constantly. sshguard watches the authentication log and adds the address of repeat offenders to the <sshguard> table in pf, which keeps that noise out of your logs and off your resources. It also acts as a second layer in case a future configuration change ever weakens SSH. It watches the log of the admin sshd on port 22. It does not watch Forgejo’s own SSH server on port 2222, which logs to Forgejo’s log instead (see What Comes Next).

beaker@montreal:~$ sudo pkg install -y sshguard
beaker@montreal:~$ sudo vi /usr/local/etc/sshguard.conf

The shipped file has three BACKEND lines, all commented out, and sshguard will not start without one. Uncomment the pf line by removing the leading #, and leave the other two commented:

BACKEND="/usr/local/libexec/sshg-fw-pf"

The shipped FILES line already watches /var/log/auth.log (where sshd logs) and /var/log/maillog, so it needs no change. The defaults ban an address for 120 seconds once its attack score exceeds 30 (most attacks score 10 points each), and each repeat ban lasts 1.5 times longer. THRESHOLD, BLOCK_TIME and DETECTION_TIME change how aggressive that is. To make sure you never ban yourself, list your own address in a whitelist file and enable the WHITELIST_FILE line in the configuration. Then enable and start it, and confirm it is running. The ban table is empty until something earns a ban, so an empty result from the second command is normal:

beaker@montreal:~$ sudo sysrc sshguard_enable=YES
beaker@montreal:~$ sudo service sshguard start
beaker@montreal:~$ sudo service sshguard status
beaker@montreal:~$ sudo pfctl -t sshguard -T show

7. Off-Box Backups

Since this VPS holds the authoritative private repositories rather than a mirror, losing it without an offsite backup means losing the data, not just suffering downtime. Nothing else in this guide depends on this section, so it can be done later or skipped. Wherever another section mentions backups, it says what to do if you skipped them.

beaker@montreal:~$ sudo pkg install -y restic

Prepare the Repository

restic encrypts everything with a password. Generate one into a root-only file. Also store a copy somewhere that is not this VPS, because without the password the backups cannot be restored:

beaker@montreal:~$ sudo sh -c 'umask 077; openssl rand -base64 32 > /usr/local/etc/restic-pass'
beaker@montreal:~$ sudo cat /usr/local/etc/restic-pass

Then initialize the repository on your offsite target. Replace <your-offsite-repo> with a restic repository URL for your provider (S3-compatible bucket, Backblaze B2, or another host), and export any credentials that provider needs first:

beaker@montreal:~$ sudo restic init --repo <your-offsite-repo> --password-file /usr/local/etc/restic-pass

The Nightly Backup Job

FreeBSD’s periodic system runs every executable script in /usr/local/etc/periodic/daily/ each night and emails the combined output to root, so a backup failure shows up in the report you will already be reading. Scripts here start with #!/usr/local/bin/bash (the path FreeBSD’s bash package installs to, installed in Patch the Base System and Create an Admin User), and periodic runs them directly. The script dumps the database and pushes both the dump and Forgejo’s data to the offsite target. The important part is that the destination is not on this VPS, so losing the VPS does not mean losing the backup too.

The dump is written by root, from the output of pg_dump running as the git user, which can read the database directly over the socket. Doing it this way keeps the su command down to a single program, so it does not matter which login shell the git account uses (on FreeBSD that is csh by default, which does not understand bash syntax such as set -o pipefail). The pipefail setting in the script’s own bash makes the whole script fail if pg_dump fails, instead of quietly storing an empty dump. The dump lands in a directory only root and the git group can read, because it contains everything in the database.

The periodic directories do not exist on a fresh install, and vi cannot save into a missing folder, so create the daily one now (the maintenance section creates the weekly and monthly ones later):

beaker@montreal:~$ sudo mkdir -p /var/db/forgejo/backup /usr/local/etc/periodic/daily
beaker@montreal:~$ sudo chown root:git /var/db/forgejo/backup
beaker@montreal:~$ sudo chmod 750 /var/db/forgejo/backup
beaker@montreal:~$ sudo vi /usr/local/etc/periodic/daily/500.forgejo-backup
#!/usr/local/bin/bash
set -euo pipefail
export PATH=/usr/local/sbin:/usr/local/bin:$PATH
umask 027

DUMP=/var/db/forgejo/backup/forgejo-db.sql.gz

su -m git -c 'pg_dump forgejo' | gzip > "$DUMP"
chgrp git "$DUMP"

restic backup \
  /var/db/forgejo/data \
  /var/db/forgejo/forgejo-repositories \
  /var/db/forgejo/backup \
  /usr/local/etc/forgejo \
  --repo <your-offsite-repo> \
  --password-file /usr/local/etc/restic-pass
beaker@montreal:~$ sudo chmod 755 /usr/local/etc/periodic/daily/500.forgejo-backup

If your offsite provider needs credentials in environment variables, export them near the top of the script. Test a restore before trusting this, not after you need it, and run the script by hand once to confirm it works. Then check that the dump is not empty:

beaker@montreal:~$ sudo /usr/local/etc/periodic/daily/500.forgejo-backup
beaker@montreal:~$ sudo ls -l /var/db/forgejo/backup/

Using Kopia Instead

If you already run Kopia on another machine, you can have that machine pull the backup instead of having the VPS push it. The VPS then holds no credentials for the backup, so a compromised VPS cannot delete it. Kopia cannot pull from a remote host by itself, so rsync copies the data over SSH first and Kopia snapshots the local copy.

On the VPS, keep the script’s dump lines (everything down to the chgrp) and delete the restic backup command, and skip the restic install and repository steps. rsync has to be installed on the VPS as well, because the pulling machine runs the other half of the transfer there:

beaker@montreal:~$ sudo pkg install -y rsync

Then create a dedicated read-only account for the pull, put it in the git group so it can read Forgejo’s files, and give it the public key from your Kopia machine. The restrict option in authorized_keys disables port forwarding, agent forwarding and a terminal for that key:

beaker@montreal:~$ sudo pw useradd backup -m -s /usr/local/bin/bash -G git
beaker@montreal:~$ sudo mkdir -p /home/backup/.ssh
beaker@montreal:~$ echo 'restrict ssh-ed25519 AAAA... backup@homelab' | sudo tee /home/backup/.ssh/authorized_keys
beaker@montreal:~$ sudo chown -R backup:backup /home/backup/.ssh
beaker@montreal:~$ sudo chmod 700 /home/backup/.ssh
beaker@montreal:~$ sudo chmod 600 /home/backup/.ssh/authorized_keys

Replace the AAAA... placeholder with the full public key from the Kopia machine. The new account also has to be allowed through the AllowUsers whitelist from SSH Hardening, or sshd rejects it even with a valid key. Edit the line to list both accounts, check the file, and restart sshd. Keep your current session open and confirm a fresh login as beaker still works afterwards:

beaker@montreal:~$ sudo vi /etc/ssh/sshd_config
AllowUsers beaker backup
beaker@montreal:~$ sudo sshd -t
beaker@montreal:~$ sudo service sshd restart

Check that the backup account can read /var/db/forgejo/data, /var/db/forgejo/forgejo-repositories, /var/db/forgejo/backup and /usr/local/etc/forgejo before relying on it, and add group read permission where it cannot. Then, on the Kopia machine, create a repository once and run the pull and snapshot as a nightly job after the VPS’s dump has finished. The --rsync-path option tells the remote side where to find rsync, because a restricted, non-interactive SSH session on FreeBSD may not have /usr/local/bin on its PATH:

beaker@homelab:~$ kopia repository create filesystem --path /srv/kopia-repo
beaker@homelab:~$ rsync -a --delete -e ssh --rsync-path=/usr/local/bin/rsync --relative backup@montreal.procyonlabs.com:/var/db/forgejo/data :/var/db/forgejo/forgejo-repositories :/var/db/forgejo/backup :/usr/local/etc/forgejo /srv/backups/montreal/
beaker@homelab:~$ kopia snapshot create /srv/backups/montreal

As with the restic job, the database dump is the consistent piece and the repositories are copied while Forgejo is running. Test a restore from a Kopia snapshot before you rely on this, and keep a copy of the Kopia repository password somewhere other than the Kopia machine. This pull setup has not been tested on FreeBSD 15.1 yet.

8. Ongoing Maintenance: Mail and Package Updates

Set Up Mail Delivery

Everything automated on this machine reports by email: freebsd-update cron, the periodic reports, and the notification scripts below. FreeBSD 15 already includes dma, the DragonFly Mail Agent, as its default mail handler. It has no daemon and does not listen on port 25 (the base system’s sendmail is not running either), so it only needs to be told to relay through an external mail account. Without that, dma tries to deliver straight to the recipient’s mail server from the VPS address, which many providers block on port 25 and which recipients often reject or send to spam. Relaying through a real account on port 587 avoids both problems.

dma reads its settings from /etc/dma/dma.conf. Uncomment or add the lines below. SMARTHOST is the relay, AUTHPATH points at the credentials file created next, SECURETRANSFER with STARTTLS turns on encryption (port 587 starts in plain text and upgrades), and MASQUERADE sets the sender address on outgoing mail, which many providers require to match the account. If your provider uses port 465 instead, drop STARTTLS and keep SECURETRANSFER:

beaker@montreal:~$ sudo vi /etc/dma/dma.conf
SMARTHOST smtp.yourprovider.com
PORT 587
AUTHPATH /etc/dma/auth.conf
SECURETRANSFER
STARTTLS
MASQUERADE alerts@example.com

The credentials go in /etc/dma/auth.conf, one line in the form user|smarthost:password. Use an app-specific password from your mail provider, not your main account password. The file holds a credential, so it must not be readable by other users. The shipped files are owned by root and group mail with mode 640, which is what dma needs and what you want. A new auth.conf should end up the same, and ls -l /etc/dma/ shows whether it did. If the owner or mode is different, set it with sudo chown root:mail /etc/dma/auth.conf and sudo chmod 640 /etc/dma/auth.conf:

beaker@montreal:~$ sudo vi /etc/dma/auth.conf
your-smtp-username|smtp.yourprovider.com:your-app-password

Mail addressed to root, which is where the system’s own reports go, needs to reach a real mailbox. Add an alias for it:

beaker@montreal:~$ sudo vi /etc/aliases
root: you@example.com

Test the Email Path Before Relying on It. Send a message by hand and confirm it lands in your inbox. SMTP relay misconfiguration fails silently more often than loudly, and a notification system you have not verified is worse than none, because it creates false confidence. dma queues mail and then tries to deliver it, so check both the queue and the mail log. An empty queue means delivery succeeded, and a message that is stuck stays listed with the reason in the log:

beaker@montreal:~$ echo "mail test from montreal" | mail -s "mail test" you@example.com
beaker@montreal:~$ mailq
beaker@montreal:~$ sudo tail -n 20 /var/log/maillog

A successful send ends with delivery successful and a line saying it used the smarthost and SMTP authentication. If you disabled IPv6 earlier, you will also see the relay’s IPv6 address fail with No route to host just before the IPv4 address succeeds. That is expected: dma tries every address the relay publishes, and the first attempt costs a moment.

With this working, the daily and weekly periodic reports also arrive in your inbox. Those reports (disk space, failed logins, pkg audit vulnerability results, and the output of any scripts you added to the periodic directories, including the backup script from The Nightly Backup Job if you set it up) are FreeBSD’s built-in log digest, and they are what replace a separate tool like logwatch.

Package Update Checks

Forgejo, PostgreSQL and everything else installed from pkg are updated with pkg upgrade, so there is no separate download-and-verify routine. What is missing is a nudge to run it. The weekly script below refreshes the package catalog, then emails you if any installed package is out of date or has a known vulnerability, and says nothing otherwise. Scripts in /usr/local/etc/periodic/weekly/ run as part of the system’s weekly periodic run, and a script needs to be executable to run. In both notification scripts in this guide, change NOTIFY_EMAIL from the you@example.com placeholder to the address you want the alerts sent to. A stock caddy package showing as outdated is filtered out, because the stock binary is not the one running here.

The periodic script directories under /usr/local/etc/periodic/ do not exist on a fresh install, and vi cannot save into a folder that is missing. Create all three now, so that this and the later scripts in this guide can be saved. The command is harmless if the daily directory already exists because you set up backups:

beaker@montreal:~$ sudo mkdir -p /usr/local/etc/periodic/daily /usr/local/etc/periodic/weekly /usr/local/etc/periodic/monthly
beaker@montreal:~$ sudo vi /usr/local/etc/periodic/weekly/500.pkg-update-check
#!/usr/local/bin/bash
set -u

NOTIFY_EMAIL="you@example.com"

pkg update -q > /dev/null 2>&1 || true
pkg audit -F > /dev/null 2>&1 || true

OUTDATED=$(pkg version -vRl '<' | grep -v '^caddy-' || true)
VULNS=$(pkg audit -q || true)

if [ -n "$OUTDATED" ] || [ -n "$VULNS" ]; then
    printf "Package updates available on %s\n\nOut of date:\n%s\n\nKnown vulnerabilities:\n%s\n\nRun: sudo pkg upgrade\n" \
      "$(hostname)" "$OUTDATED" "$VULNS" \
      | mail -s "Package updates available on $(hostname)" "$NOTIFY_EMAIL"
fi
beaker@montreal:~$ sudo chmod 755 /usr/local/etc/periodic/weekly/500.pkg-update-check
beaker@montreal:~$ sudo /usr/local/etc/periodic/weekly/500.pkg-update-check

A Note on Ambition. The script only tells you an update exists. It deliberately does not upgrade anything. For a Git server holding both private and public repositories, an unattended version bump carries more risk than an unattended security patch does (schema migrations, config changes between versions, breaking changes even within a release line). Staying in the loop manually is the safer default. Before upgrading Forgejo, take a backup, since UFS has no snapshot to roll back to. If you set up the backup script in The Nightly Backup Job, run it first. It is an ordinary periodic script, so it can be run by hand at any time as well as nightly:

beaker@montreal:~$ sudo /usr/local/etc/periodic/daily/500.forgejo-backup

If you skipped backups, at least dump the database and copy /var/db/forgejo somewhere off this machine before you upgrade. The dump below goes into your home directory, and the redirection is done by your own shell, which is fine because you own that directory:

beaker@montreal:~$ sudo -u git pg_dump forgejo | gzip > ~/forgejo-db-$(date +%Y%m%d).sql.gz

Then upgrade and restart Forgejo:

beaker@montreal:~$ sudo pkg upgrade
beaker@montreal:~$ sudo service forgejo restart

FreeBSD’s default package repository is the quarterly branch, which receives only security and bug fixes between quarterly branch dates. That fits a server that should stay boring. The latest branch has newer versions but more churn, and is not used in this guide.

9. Ongoing Maintenance: Caddy, Coraza, and CRS

Unlike Forgejo, there is no single “check for updates” question here. Three separate pieces make up this stack, and each has its own natural update cadence. Because the Caddy binary is a source build (required for Coraza), pkg upgrade does not touch it. A plain packaged Caddy would get security patches automatically, but that trade-off was made deliberately to get the WAF module. The manual routine in this section stands in for that lost automation.

PieceWhat it isUpdate cadence
xcaddyThe build tool, not something that runsRe-fetch right before each rebuild. It is cheap, so there is no need to track it separately
Caddy + Coraza binaryThe actual internet-facing processRebuild when Caddy or the Coraza module ships a security fix, or when you want a newer feature
OWASP CRS rulesetThe attack-pattern rules Coraza checks requests againstRefresh periodically on its own. CRS ships rule updates a few times a year, independent of whether Caddy changed

The Caddy rebuild is handled by the caddy-update script below, which also refreshes CRS as its last step. CRS is additionally refreshed on its own by a small monthly job, because its release pace is independent of Caddy’s.

A Caution That Applies Regardless of the Script. Any time the CRS rules update, treat it like the initial rollout. A rule change can introduce new false positives against Git and LFS traffic that were not there before. If you have already switched to SecRuleEngine On, review Coraza’s logs briefly after a CRS update rather than assuming a clean pull means a clean result. The monthly job below pulls new rules without asking, which is harmless while Coraza is in DetectionOnly mode. Once blocking is on, decide whether you are happy with that. If you would rather review rule changes before they go live, skip the monthly job and let caddy-update be the only thing that refreshes CRS, run by hand when you choose.

Automating the Checks

The scripts below live in FreeBSD’s periodic directories. If you skipped Section 8, create all three now. The command is safe to repeat if they already exist:

beaker@montreal:~$ sudo mkdir -p /usr/local/etc/periodic/daily /usr/local/etc/periodic/weekly /usr/local/etc/periodic/monthly

Caddy is the piece worth tracking with a notification script, since endoflife.date notes that only the latest Caddy release is considered supported at all. There is no LTS-style grace window like Forgejo has, so falling behind here is a real exposure rather than a missed feature. This script compares the running custom binary against Caddy’s latest GitHub release and emails you only when they differ. FreeBSD’s base grep does not support the -P option, so the version lookup uses sed instead:

beaker@montreal:~$ sudo vi /usr/local/etc/periodic/weekly/510.caddy-update-check
#!/usr/local/bin/bash
set -u
export PATH=/usr/local/sbin:/usr/local/bin:$PATH

NOTIFY_EMAIL="you@example.com"
CURRENT=$(/usr/local/sbin/caddy-coraza version | awk '{print $1}' | sed 's/^v//')
LATEST_TAG=$(curl -s https://api.github.com/repos/caddyserver/caddy/releases/latest \
  | sed -n 's/.*"tag_name": *"v\([^"]*\)".*/\1/p')

if [ -n "$LATEST_TAG" ] && [ "$CURRENT" != "$LATEST_TAG" ]; then
    printf "You are running Caddy %s.\nVersion %s was just released.\n\nSince this is a custom build with the Coraza module, rebuild via xcaddy\n(run /usr/local/sbin/caddy-update) rather than installing the stock package binary.\n\nChangelog: https://github.com/caddyserver/caddy/releases/tag/v%s\n" \
      "$CURRENT" "$LATEST_TAG" "$LATEST_TAG" \
      | mail -s "Caddy update available: ${CURRENT} -> ${LATEST_TAG}" "$NOTIFY_EMAIL"
fi
beaker@montreal:~$ sudo chmod 755 /usr/local/etc/periodic/weekly/510.caddy-update-check

The Coraza module does not have a clean standalone version to check independent of an actual rebuild. Rather than tracking it separately, fold it into the same trigger: whenever the Caddy email fires, rebuild with xcaddy, which pulls the current Coraza module release at the same time. No separate check is needed.

CRS does not need a notification script at all. git pull is already the entire “check for updates” action, and it is harmless to run when nothing has changed. A monthly cadence matches CRS’s release pace closely enough. After the pull, the script restarts Caddy, but only if the pull actually changed something. A restart is required because a reload does not load new rules. In testing, even a forced reload (service caddy reloadssl, which runs caddy reload --force) exited successfully while Coraza kept the rules it had already loaded, and a new rule file took effect only after a full restart. The restart can take up to ten seconds, because open connections are given that long to finish (the grace_period in the Caddyfile), which is acceptable once a month:

beaker@montreal:~$ sudo vi /usr/local/etc/periodic/monthly/500.coraza-crs-update
#!/usr/local/bin/bash
set -eu
cd /usr/local/etc/caddy/coraza/coreruleset
OLD=$(git rev-parse HEAD)
git pull -q
if [ "$(git rev-parse HEAD)" != "$OLD" ]; then
    service caddy restart
fi
beaker@montreal:~$ sudo chmod 755 /usr/local/etc/periodic/monthly/500.coraza-crs-update

As with the mail setup, test the scripts by hand once before trusting the schedule. The reasoning is the same: an unverified notification system creates false confidence rather than removing risk:

beaker@montreal:~$ sudo /usr/local/etc/periodic/weekly/510.caddy-update-check
beaker@montreal:~$ sudo /usr/local/etc/periodic/monthly/500.coraza-crs-update

The One-Shot Update Script

When the notification arrives, this script combines the rebuild-and-swap steps from earlier into a single command, so you are not re-typing the manual sequence each time. It is ordered to minimize risk to the live service:

  • The new binary is built and validated against the real Caddyfile while the old one is still running, so a bad build never touches production.
  • The validation runs as the www user, so any file it opens (such as the audit log) keeps the correct owner.
  • The old binary is backed up before being replaced, for an instant rollback.
  • The CRS refresh only runs after the rebuilt Caddy is confirmed healthy.
beaker@montreal:~$ sudo vi /usr/local/sbin/caddy-update
#!/usr/local/bin/bash
set -eu

echo "== Refreshing xcaddy =="
go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest
mv "$(go env GOPATH)/bin/xcaddy" /usr/local/bin/xcaddy

echo "== Building Caddy with Coraza =="
cd /tmp
xcaddy build --with github.com/corazawaf/coraza-caddy/v2

echo "== Validating new binary against the live Caddyfile =="
chmod 755 /tmp/caddy
su -m www -c "/tmp/caddy validate --config /usr/local/etc/caddy/Caddyfile --adapter caddyfile"

echo "== Backing up current binary =="
cp /usr/local/sbin/caddy-coraza "/usr/local/sbin/caddy-coraza.bak-$(date +%Y%m%d)"

echo "== Swapping in new binary =="
service caddy stop
mv /tmp/caddy /usr/local/sbin/caddy-coraza
service caddy start
sleep 2
service caddy status

echo "== Refreshing OWASP CRS ruleset =="
cd /usr/local/etc/caddy/coraza/coreruleset
OLD=$(git rev-parse HEAD)
git pull
if [ "$(git rev-parse HEAD)" != "$OLD" ]; then
    echo "New CRS rules pulled, restarting Caddy to load them"
    service caddy restart
fi

echo "== Done. Confirm with: curl -I https://montreal.procyonlabs.com =="
beaker@montreal:~$ sudo chmod 750 /usr/local/sbin/caddy-update

If the validation step fails, the script stops immediately (via set -e) before anything about the running service is touched. The old binary and old CRS rules stay exactly as they were, with the broken build left in /tmp to inspect.

Running and Verifying an Update

The script prints a labeled == line before each stage, so its output doubles as a progress log. Watch it in real time rather than only checking the exit code afterward. A slow step, usually the xcaddy build that compiles from source, is normal and not a failure. The script has to run as root, because it stops and starts the service and replaces a file in /usr/local/sbin:

beaker@montreal:~$ sudo /usr/local/sbin/caddy-update

After it finishes, confirm the site is actually reachable, not just that the script exited cleanly. A 200 or 301 response confirms Caddy is serving traffic on the new binary:

beaker@montreal:~$ curl -I https://montreal.procyonlabs.com

If something is wrong after an update, the dated backup created mid-script is the rollback path. Stop the bad binary, restore the previous one, and restart:

beaker@montreal:~$ ls /usr/local/sbin/caddy-coraza.bak-*
beaker@montreal:~$ sudo service caddy stop
beaker@montreal:~$ sudo cp /usr/local/sbin/caddy-coraza.bak-YYYYMMDD /usr/local/sbin/caddy-coraza
beaker@montreal:~$ sudo service caddy start

Replace YYYYMMDD with the actual date the backup was created. Old backups are not pruned automatically, so clear out ones you are confident you will not need rather than letting them accumulate on a 100 GB disk.

One thing the script does not tell you is whether the CRS git pull actually pulled anything. To confirm a refresh happened rather than a no-op, compare the last commit date of the ruleset before and after a run:

beaker@montreal:~$ sudo git -C /usr/local/etc/caddy/coraza/coreruleset log -1 --format=%cd

Field Guide: Day-to-Day Operations

Starting and Stopping Forgejo

Always go through the service manager rather than killing the process directly. It stops Forgejo cleanly (letting in-flight Git operations finish) and keeps the PID file consistent, whereas a raw kill does not:

beaker@montreal:~$ sudo service forgejo stop
beaker@montreal:~$ sudo service forgejo start
beaker@montreal:~$ sudo service forgejo restart
beaker@montreal:~$ sudo service forgejo status

forgejo_enable in /etc/rc.conf controls whether Forgejo starts automatically on boot. It was set during the install, but it is worth knowing if you ever need to take Forgejo out of the boot sequence temporarily, such as during a longer maintenance window. Setting it to NO and then back to YES does that (the value only changes boot behavior, not the running service):

beaker@montreal:~$ sudo sysrc forgejo_enable=NO
beaker@montreal:~$ sudo sysrc forgejo_enable=YES

The same service and sysrc commands work for caddy, postgresql, pf and sshguard.

Remote Access to Forgejo

Once running, there are four separate ways in, each serving a different purpose.

Web UI. https://montreal.procyonlabs.com is for browsing repositories, managing settings, reviewing pull requests and issues, and administering users.

Git Over HTTPS. This works exactly like GitHub or GitLab, routed through Caddy and the WAF:

beaker@workstation:~$ git clone https://montreal.procyonlabs.com/<username>/<repo>.git

Git Over SSH. This uses Forgejo’s own SSH daemon on port 2222 (set up during the Forgejo install), not the machine’s admin SSH on port 22. Note the explicit port in the URL, which standard git clone syntax requires for non-default SSH ports:

beaker@workstation:~$ git clone ssh://git@montreal.procyonlabs.com:2222/<username>/<repo>.git

Admin CLI. This covers tasks the web UI does not (bulk user creation, scripted setup, password resets without email). Since Forgejo runs as the unprivileged git user, admin commands run as that user too, pointed at the config file. As before, <name> and <email> are placeholders for the new user’s details:

beaker@montreal:~$ sudo -H -u git /usr/local/sbin/forgejo admin user create --username <name> --email <email> --random-password --config /usr/local/etc/forgejo/conf/app.ini

Tuning Coraza and CRS

Two separate controls govern how strict the WAF actually is, and they matter more than which individual rules are on or off.

  • Paranoia level (PL1 to PL4). This controls how aggressively CRS scans requests. PL1 (the default) catches clear-cut attacks with minimal false positives, and each level up adds more sensitive, more false-positive-prone rules. For a Git server serving binary LFS payloads and API traffic, starting at PL1 and only raising it for a specific reason is the sane default. Higher levels are tuned more for typical web-app forms than for Git’s traffic patterns.
  • Anomaly score threshold. CRS scores each request by how many rules it triggers, then blocks if the total exceeds a threshold (default 5 for inbound). Raising the threshold is a blunt way to reduce false positives across the board, at the cost of also letting more borderline traffic through.

Both are set with SecAction directives in the same directives block of the Caddyfile, placed before the Include line for the CRS rules, because CRS reads these values as it loads:

beaker@montreal:~$ sudo vi /usr/local/etc/caddy/Caddyfile
SecAction "id:900000,phase:1,pass,t:none,nolog,setvar:tx.blocking_paranoia_level=1"
SecAction "id:900110,phase:1,pass,t:none,nolog,setvar:tx.inbound_anomaly_score_threshold=5"

For Specific False Positives (a particular rule ID misfiring on a specific endpoint, found in the audit log during detection-only mode), do not edit the CRS files themselves, since the git pull refresh would overwrite any changes. Instead, keep a separate exclusions file, included after the CRS rules so it can override them. Add this line to the directives block, below the CRS rules Include:

Include /usr/local/etc/caddy/coraza/custom-exclusions.conf

Then create the exclusions file:

beaker@montreal:~$ sudo vi /usr/local/etc/caddy/coraza/custom-exclusions.conf
SecRuleUpdateTargetById 942100 "!ARGS:some_field"

Restart Caddy to apply the change. A reload is not enough for rule files: in testing, a new rule file in an included location was ignored by both reload --force and reloadssl, and took effect only after a restart. The restart can take up to ten seconds, because open connections are given that long to finish. Your tuning stays isolated in one file you control and survives ruleset updates:

beaker@montreal:~$ sudo service caddy restart

Log Monitoring: Where to Look

SourceWhereWhat it is for
Forgejo/var/log/forgejo/ and /var/log/messagesApplication errors, auth failures, repository operations
Caddy access log/var/log/caddy/access.logEvery request Caddy handled: traffic patterns, error codes
Caddy process log/var/log/caddy/caddy.logCaddy’s own startup messages and errors
Coraza audit log/var/log/coraza/coraza-audit.logWhat the WAF flagged or blocked, and why
SSH and sshguard/var/log/auth.log and sudo pfctl -t sshguard -T showLogin failures, and the addresses currently banned
PostgreSQLserver.log in /var/db/postgres/data18/Query errors, connection issues

Two practical habits matter more than any specific tool.

Log Rotation. Forgejo and Caddy rotate their own file logs, and FreeBSD’s newsyslog handles the system logs automatically. The Coraza audit log is the exception: it is written by Coraza rather than Caddy, so it will grow indefinitely on a 100 GB disk you are already watching closely unless it is rotated. newsyslog cannot rotate it by renaming the file, and neither can a Caddy reload: Coraza keeps its file open across reloads, so after a rename it keeps writing into the renamed copy while the live log stays empty. (Once that copy is compressed and deleted, the entries are lost without any error.) This weekly script therefore copies the file aside and then empties the original in place. Coraza opens the log in append mode, so it keeps its file handle and its next entry lands at the start of the emptied file. An entry written in the instant between the copy and the truncate would be lost, which is an acceptable trade for a job that runs once a week. The script then compresses the copy and deletes anything older than eight weeks. It is the part of this guide most worth testing by hand after the first run, to confirm that new entries land in the live file:

beaker@montreal:~$ sudo vi /usr/local/etc/periodic/weekly/520.coraza-audit-rotate
#!/usr/local/bin/bash
set -eu

LOG=/var/log/coraza/coraza-audit.log
[ -s "$LOG" ] || exit 0

ROTATED="$LOG.$(date +%Y%m%d)"
cp -p "$LOG" "$ROTATED"
: > "$LOG"
gzip "$ROTATED"
find /var/log/coraza -name 'coraza-audit.log.*.gz' -mtime +56 -delete
beaker@montreal:~$ sudo chmod 755 /usr/local/etc/periodic/weekly/520.coraza-audit-rotate

To test it, make a request that Coraza will log (a 404 is enough), run the script, make a second request, and confirm that each request landed where it should. /var/log/coraza is private to www, so the file globs below are expanded by a root shell rather than your own, which could not list the directory:

beaker@montreal:~$ curl -s -o /dev/null https://montreal.procyonlabs.com/probe-one
beaker@montreal:~$ sudo /usr/local/etc/periodic/weekly/520.coraza-audit-rotate; echo "exit: $?"
beaker@montreal:~$ curl -s -o /dev/null https://montreal.procyonlabs.com/probe-two
beaker@montreal:~$ sudo grep -o 'probe-[a-z]*' /var/log/coraza/coraza-audit.log
beaker@montreal:~$ sudo sh -c 'for f in /var/log/coraza/coraza-audit.log.*.gz; do echo "$f: $(zcat "$f" | grep -c probe-one)"; done'
beaker@montreal:~$ sudo procstat -f $(pgrep -x caddy-coraza) | grep audit

The live file should contain only probe-two, probe-one should appear once in today’s compressed copy, and procstat should show Caddy holding /var/log/coraza/coraza-audit.log by its real path. If procstat shows a dash instead of a path, Caddy is writing to a deleted file and the rotation is not working.

caddy.log grows slowly, because Caddy only logs warnings and errors to it by default. If it ever gets large, stop Caddy, truncate it, and start Caddy again.

A Daily Digest Instead of Live-Tailing Everything. The periodic reports already do this. Every day and week, FreeBSD emails root a summary of disk space, failed logins, vulnerable packages, and the output of the scripts in this guide, and mail setup in Set Up Mail Delivery sends it to your inbox. That is much more sustainable than manually checking five different log sources. If a report does not arrive on schedule, that is itself the signal to look at the machine.

What Comes Next

  • Exact CRS exclusion tuning. This comes from reviewing real detection-only logs and cannot be decided in advance.
  • Admin SSH on a non-standard port. Moving port 22 to another port, with rate limiting in pf, is worth deciding on.
  • Banning Repeat Offenders on Forgejo’s SSH Port. sshguard as configured in this guide only reads the admin sshd log, so repeated failed connections to Forgejo’s SSH server on port 2222 are not banned. They are logged by Forgejo, and Forgejo only accepts keys registered to an account, so guessing passwords is not possible there. If you want those addresses banned too, rate limiting in pf is the simplest next step.
  • Actions runner placement. Forgejo Actions runners (CI) should live on a separate VM, not on this server, once you are ready for CI.
  • Service supervision. rc.d does not restart a crashed service. A supervisor such as monit (available from pkg) can watch Forgejo and Caddy and restart them.
  • Stronger isolation. If you later want a filesystem sandbox comparable to the systemd one on Linux, running Forgejo in a jail is the FreeBSD answer.
  • Packaged base and ZFS. FreeBSD 15 is moving toward managing the base system with pkg (pkgbase), and ZFS boot environments give one-command rollback. Both are reasonable later migrations if you want them.
  • Block storage. Confirm the attachment process with your provider before you actually need it.

FreeBSD

Forgejo

Caddy, Coraza, and the WAF

  • Caddy: the reverse proxy, with automatic HTTPS.
  • Caddy Documentation: Caddyfile syntax reference.
  • Caddy Releases (GitHub): what the Caddy update-check script polls.
  • Caddy on endoflife.date: confirms only the latest Caddy release is supported.
  • xcaddy: the build tool used to compile Caddy with Coraza built in.
  • coraza-caddy: the Caddy module that plugs the Coraza engine in, including the load_owasp_crs and @ path behavior.
  • Coraza: the ModSecurity-compatible WAF engine that coraza-caddy wraps.
  • OWASP Core Rule Set: the ruleset Coraza runs, and home of the paranoia level and anomaly scoring documentation.
  • OWASP CRS on GitHub: what gets cloned during setup and pulled by the update script.
  • CRS: Engine and Integration Options: the project’s comparison of ModSecurity v2, ModSecurity v3, and Coraza, which backs the engine choice in the Caddy section.
  • portacl-rc: how unprivileged users are allowed to bind ports 80 and 443 on FreeBSD.
  • FreeBSD caddy rc script (ports tree): the service script, including the reload and reloadssl commands (note that neither loads changed rule files; use a restart for that).

PostgreSQL

Security and Backups

  • sshguard: the SSH ban tool, including its pf backend.
  • restic: the offsite backup tool used for the optional nightly dump and data backup.
  • dma(8): the mail agent behind every notification in this guide, including the smarthost and TLS options.

,

Leave a Reply

Your email address will not be published. Required fields are marked *