# Hardening

This guide lists the settings that make a CrushBalance 27 installation safer, and what each one protects. The [operator guide](Main.md) explains installation and daily operation; the [key reference](Key-Reference.md) lists every key.

Checklist:
1. Restrict the admin server: a management interface or loopback, a firewall that lets only management networks reach the admin port, and `admin_allowed_ips`.
2. Replace the generated admin certificate with your own.
3. Use a strong admin password; keep the `/metrics` token secret, or leave `/metrics` off.
4. Keep the prefs directory, its backups and `crushbalance.key` private.
5. Make PROXY-enabled CrushMFT ports reachable only from the balancer.
6. Use `backend_tls` where the network to CrushMFT is not trusted, with a pin or a CA-issued certificate.
7. Run as a non-root user (Linux).
8. Install the Windows service only in a folder that only administrators can write to (and, to keep `prefs.XML` private, read).

---

## The admin server

The admin server is HTTPS on `admin_bind_ip:admin_port`, by default **every address, port 8090**. It serves the UI, the REST API, `/healthz` and `/metrics`.

### Where it listens

- Bind it to a **management interface**: set `admin_bind_ip` to that interface's address (Settings › Admin). Or bind it to `127.0.0.1` and reach it through an SSH tunnel:
  ```
  ssh -L 8090:127.0.0.1:8090 admin@balancer
  ```
  then open `https://127.0.0.1:8090/`.
- `admin_bind_ip` and `admin_port` take effect after a restart (the UI says "Needs restart"). Make sure your monitors can still reach `/healthz` and `/metrics` at the new address.
- An enabled listener may not use the admin port on an overlapping address (ERROR ADMIN_PORT_CONFLICT).

### `admin_allowed_ips`

`admin_allowed_ips` (Settings › Admin › Allowed admin IPs) lists the sources that may open admin connections. Empty means every source.
- **What it accepts:** IPv4 and IPv6 addresses and CIDR blocks, comma-separated, for example `10.20.0.0/16, 192.0.2.15, 2001:db8:100::/48`. No host names and no patterns: a trust list never depends on DNS. The UI turns a trailing wildcard such as `192.168.*` into CIDR.
- **IPv4 and IPv6 are separate.** It is a plain address list, not an IP rule list: an IPv4 entry, `0.0.0.0/0` included, never matches an IPv6 source. List your IPv6 management networks explicitly.
- **Checked at the connection's first byte, before the TLS handshake.** A source outside the list gets no handshake at all, so it cannot try passwords, use the setup token, or load the server with handshakes. The check is repeated on every request, so a change also applies to admin connections that are already open. It does not protect the server's connection slots: see the limits below.
- **Loopback is always allowed**, so an SSH tunnel to `127.0.0.1` always works (it needs `admin_bind_ip` to be `0.0.0.0`, `::` or a loopback address; a connection to the host's own non-loopback address is not loopback).
- **No self-lockout from the UI.** A save or a backup restore that would exclude your own address is refused with "would lock out" (loopback clients are exempt). A safe-mode restore checks the backup's list the same way before it copies anything.
- **Hand edits fail closed.** An invalid entry in a hand-edited file is dropped with a warning and the rest is used; if the list had entries and none is valid, only loopback is allowed. It never falls back to "every source".
- **It also covers `/healthz` and `/metrics`.** Add your monitoring and Prometheus hosts.

**Limits of Java's HTTPS server (known limitations of CrushBalance 27).** The admin server is Java's built-in HTTPS server, and two things happen inside it before CrushBalance's own checks run. **Firewall the admin port** so that only your management networks reach it, and keep the open-file limit high (`LimitNOFILE=1048576`, [Capacity and tuning](Capacity-and-Tuning.md)).
- **Connections that never send a byte.** The server hands a connection to CrushBalance only when its first byte arrives, so neither `admin_allowed_ips` nor the limits of [Built-in protections (nothing to configure)](Hardening.md#built-in-protections-nothing-to-configure) see a connection that stays silent. Such a connection still takes one of the server's connection slots (`jdk.httpserver.maxConnections`, which CrushBalance sets to 256; when every slot is taken, new admin connections are refused) and an open file. Some Java 17 updates, 17.0.3.1 among them, ignore that limit: there silent connections take only open files, which the listeners need too.
- **A stalled next request.** The server reads the head of the next request on a kept-alive connection before CrushBalance's limits apply, so a client that stalls it holds an admin thread for up to 10 seconds (`sun.net.httpserver.maxReqTime`). The admin server therefore keeps 32 threads and adds up to 256 more while requests stall (an added thread ends after 60 seconds without work): with 64 stalled connections, from one source or from 16, a logged-in administrator is still answered within a second. Beyond the connection limit (256 on Java 21) or beyond 288 stalled requests, the admin server is unavailable while the stalls last, each at most 10 seconds, although an attacker can renew them: on Java 21 new connections are refused while an administrator's open connection keeps working; on a Java 17 update without the limit every further request is refused. Only sources that pass `admin_allowed_ips` and the TLS handshake can stall a request.

### The admin certificate

- **Default:** a certificate generated for this installation, `admin-selfsigned.p12` in the prefs directory: EC P-256, valid 825 days, renewed automatically 30 days before it expires. Its password is derived from `crushbalance.key` and stored nowhere. Browsers warn, because it is self-signed: compare its SHA-256 fingerprint with the console output or the log line `admin listening on https://… cert=generated sha256=…` before you trust it.
- **Your own certificate (recommended):** set `admin_keystore` to a keystore file (JKS, PKCS12 or JCEKS, recognised by content) and `admin_keystore_password` to its password. The private key must use the same password as the keystore. For example, from PEM files:
  ```
  openssl pkcs12 -export -in admin-fullchain.pem -inkey admin-key.pem -name crushbalance-admin \
    -passout file:/root/admin.p12.pass -out /var/opt/CrushBalance/admin.p12
  chmod 600 /var/opt/CrushBalance/admin.p12
  ```
  When CrushBalance runs as a non-root user ([Running as a non-root user (Linux)](Hardening.md#running-as-a-non-root-user-linux)), also `chown crushbalance: /var/opt/CrushBalance/admin.p12`, so the service user can read it. The file is checked every 60 seconds; a replaced file is used for new connections without a restart. A configured certificate with 30 days or less left raises the notice "Admin certificate expires soon".
- **Fallbacks.** If the configured keystore cannot be used, the generated certificate is used and the notice "Admin keystore unusable" is shown. If no certificate can be generated (no `keytool` in the Java installation, or an unusable `crushbalance.key`), a **built-in certificate** is used, whose private key every installation shares: the notice "Shared admin certificate" says so. Treat that notice as urgent: configure `admin_keystore`, or fix the key file or the Java installation.
- The admin server speaks TLS 1.3 and 1.2 only. It sends no HSTS header.

### Built-in protections (nothing to configure)

- **Password:** 8–1024 characters, stored only as a PBKDF2-HMAC-SHA256 verifier (600,000 iterations). Changing it ends every other session.
- **Login throttling** per source (IPv4 address or IPv6 /64): 5 failures within 15 minutes lock the source out for 5 minutes, doubling up to 60 minutes. Sessions that are already logged in are not affected.
- **Sessions:** the cookie `__Host-CrushBalance` (`Secure`, `HttpOnly`, `SameSite=Strict`), bound to the client address, ending after `admin_session_timeout` of inactivity (default 1800 s; background polling does not count) and after 12 hours in any case. Every change needs a CSRF header; `Origin` and `Sec-Fetch-Site` are checked; no CORS headers are sent.
- **Before login:** at most 24 connections may be in the TLS handshake or waiting for their first request (4 per source; over that the handshake is refused), and at most 16 requests without a session may run at once (8 per source; over that the request gets 503 at once); together they hold at most 24 admin threads (the server keeps 32 and adds more only while requests stall, [admin_allowed_ips](Hardening.md#admin_allowed_ips)). Every response write that is blocked for more than 20 seconds is cut.
- **Audit:** logins, failed logins, setup, password changes, configuration saves and restores, blocks and closes are written to the log in category `audit` (never a password, token or registration value). Repeated denials are summarised per source and minute.
- **No file access through the API:** there is no download of `prefs.XML`, backups or logs, and stored passwords are never returned, only their state (set, empty, plain text, cannot be decrypted).

### First-run setup and recovery

- The **setup token** (160 bits) is printed to the console and written to `setup-token.txt` (mode 0600). It is deleted when setup completes; a new one is created at each start while no password is set. The log records only where the token is. Anyone who can read the console output or the prefs directory can complete setup, so finish it promptly, or set the password before the first start with `java -jar CrushBalance.jar -set-admin-password`.
- `-set-admin-password` reads the password from the terminal without echo, or one line from stdin; never from the command line.
- **Recovery:** `-set-admin-password` on the server, or blank `admin_password` in `prefs.XML` (setup mode with a new token).

### The `/metrics` token

- `/metrics` is **off** by default (404).
- Settings › Server › Prometheus metrics › Generate token shows a random bearer token **once**. Only its SHA-256 is stored (`metrics_token`). Rotate it in the same place (the old token stops working) or turn it off.
- Only `Authorization: Bearer <token>` is accepted; admin cookies are not. A wrong token gets 401 and an aggregated `metrics_denied` audit line.
- `admin_allowed_ips` and the pre-login limits apply: allow only your Prometheus servers.
- Keep the token in a file readable only by Prometheus (`credentials_file`), and scrape over HTTPS with a certificate your Prometheus trusts ([The admin certificate](Hardening.md#the-admin-certificate)).
- The output names listeners and endpoints by id and contains no client addresses.

## Files, modes and the key file

### What is sensitive

| File | Contains | Mode set by CrushBalance |
|---|---|---|
| `prefs.XML` | the configuration; keystore, probe and GeoIP passwords as `enc:` values; the admin password verifier; the **registration code in plain text** (deliberately not encrypted, so a lost key never unlicenses the balancer) | 0600 for new files |
| `backup/prefs-*.XML` | the same, for the last 50 versions, plus raw `-invalid` copies | 0600, directory 0700 |
| `crushbalance.key` | the master key that decrypts every `enc:` value, derives the generated keystore passwords and keys the pin file | 0600; on Windows owner, SYSTEM and Administrators only |
| `admin-selfsigned.p12`, `listener-selfsigned.p12` | generated private keys | 0600 |
| `setup-token.txt` | the one-time setup token | 0600 |
| `prefs.XML.v1-*.bak` | a moved-aside CrushBalance 11 file, possibly with old passwords and the registration | 0600 (best effort) |
| `sticky-pins.dat` | hashed pins, never an address or cookie | 0600 |
| `geoip-cache.json` | client addresses with their locations | 0600 |
| `CrushBalanceServer*.log` | client addresses, admin activity (never secret values) | 0640 when created |

- The modes are POSIX modes (Linux, macOS). **On Windows** CrushBalance gives only `crushbalance.key` (its owner, SYSTEM and Administrators) and `setup-token.txt` (its owner) an access list of their own; every other file in the table, `prefs.XML`, the backups and the moved-aside CrushBalance 11 file included, and the log get the folder's access list. Under `C:\Program Files` that lets every local user read them, with the registration code and the admin password verifier. `-i` warns when Everyone, Authenticated Users or Users can read the install folder and prints the two `icacls` commands of [The Windows service](Hardening.md#the-windows-service); run them to keep these files private: they remove every right of those three groups, reading included, while Administrators and SYSTEM keep theirs.
- `prefs.XML` plus `crushbalance.key` together reveal every stored password. Keep both, and every backup of the prefs directory, as private as the passwords themselves.
- The prefs directory is created with mode 0700 when CrushBalance creates it. If you created it yourself (for example `/var/opt/CrushBalance`), set it: `chmod 700 /var/opt/CrushBalance`.
- On Linux, a key file readable by group or others is reported and changed to 0600 at startup. CrushBalance never overwrites an existing key file it cannot use; it reports it instead.
- Delete the moved-aside `prefs.XML.v1-*.bak` once you no longer need it.

### Backing up and moving the key

- Back up `crushbalance.key` with the prefs directory: without it the encrypted values in `prefs.XML` and in every backup cannot be decrypted (you would enter the passwords again).
- Store such backups encrypted or in a place only administrators can read.
- When moving to another host, copy `prefs.XML` and `crushbalance.key` over a protected channel and check the modes on the new host.

## CrushMFT ports with PROXY headers: reachable only from the balancer

CrushMFT accepts a PROXY header from **any** source on a port with `proxy_header` or `proxy_header_v2`, and from then on treats the address in it as the client's. A host that can reach such a port directly can therefore claim any client address: it can pass CrushMFT's IP restrictions, avoid its bans, and appear as someone else in its logs.

- **Firewall every PROXY-enabled CrushMFT port** (HTTP and HTTPS items, FTP ports and their passive ranges, SFTP ports) so that only the balancer's addresses reach it. For example, on a Linux CrushMFT host behind a balancer at 192.0.2.10, with the HTTP item on 8080, FTP on 21 and the passive range 40000–40099:
  ```
  iptables -A INPUT -p tcp -s 192.0.2.10 -m multiport --dports 21,8080,40000:40099 -j ACCEPT
  iptables -A INPUT -p tcp -m multiport --dports 21,8080,40000:40099 -j DROP
  ```
  On a Windows CrushMFT host, allow these ports only from the balancer in Windows Defender Firewall (for example `New-NetFirewallRule -DisplayName "CrushMFT via CrushBalance" -Direction Inbound -Protocol TCP -LocalPort 21,8080,40000-40099 -RemoteAddress 192.0.2.10 -Action Allow`), and make sure no broader rule also allows them.
- Use the address the backends actually see from the balancer (with several balancers or source addresses, list them all). Health probes come from the same addresses.
- **CrushBalance does not check this for you.** A warning when an endpoint with a PROXY header points at a public address was deliberately left out, because it would depend on DNS. The endpoint dialog shows the hint "CrushMFT trusts a PROXY header from any source on a PROXY-enabled port. Firewall that port so that only CrushBalance can reach it.", and warns when the host is a public IP address.
- Prefer PROXY headers over CrushMFT's `allow_x_forwarded_host`, a global CrushMFT setting that trusts `X-Forwarded-For` from anyone who reaches CrushMFT directly.
- **The balancer's own inbound PROXY** (`proxy_protocol_in=true`, behind an upstream load balancer) accepts headers only from the addresses in `trusted_proxies`; every other source is reset. Keep that list to the upstream balancers.

## Backend TLS and pinning

Without `backend_tls`, the traffic between the balancer and CrushMFT is plain text on `tls`, `http` and `https` listeners. Use `backend_tls=true` (endpoint dialog › Backend TLS) where that network is not trusted.

- **Trust, one rule per endpoint:**
  - no pin: the CrushMFT certificate must chain to the Java trust store and match the endpoint `host` by the HTTPS host-name rules. Use this with CA-issued certificates;
  - a pin (`backend_tls_pin`): the certificate's SHA-256 fingerprint must equal the pin exactly; the chain, the dates and the host name are not checked. Use this for CrushMFT's self-signed certificates.
- **Pin only what you verified.** "Check certificate" shows the certificate the endpoint presents now. Compare its SHA-256 fingerprint with the certificate on the CrushMFT server before "Trust this certificate", for example with `keytool -list -v -keystore <CrushMFT keystore>` on that server. A pin taken without that comparison trusts whatever answered at that moment.
- **Never plain.** A `backend_tls` endpoint is never connected without TLS. A failed handshake fails over to the next endpoint; an untrusted certificate also marks the endpoint DOWN in its health checks.
- **Renewals.** A pin names one certificate. When CrushMFT's certificate is replaced, the endpoint is DOWN until you check and trust the new one. With CA-issued certificates and no pin, renewals need nothing.
- TLS 1.3 and 1.2 only; SNI is the endpoint `host` when it is a name. The balancer presents no client certificate.
- Over `https`, a `crushftp` health probe sends its credentials (`probe_user`, `probe_password`) only after the certificate passed its check: the endpoint's own trust settings for its own host and port, the Java trust store for any other `https` URL. On an `http://` probe URL the login travels in plain text, so on an untrusted network use `backend_tls` and the `https://` URL, and give the probe user only the SERVER_VIEW role.
- `backend_tls` does not apply to `tcp` listeners: there the client's own TLS (FTPS, HTTPS passthrough) already reaches CrushMFT unchanged.

## Listener TLS

- Use a real certificate on `tls` and `https` listeners (`tls_keystore`); the generated one is self-signed.
- Keep `tls_protocols` at its default, TLS 1.3 and 1.2. Java 25 disables `TLSv1` and `TLSv1.1` in their `jdk.tls.disabledAlgorithms` security setting, so CrushBalance drops them from `tls_protocols` with a warning (CSV_ITEM_DROPPED). Only a Java installation whose setting allows them can use them, with the warning TLS_OLD_PROTOCOL.
- Client-initiated renegotiation is always refused.

## Running as a non-root user (Linux)

The init script runs CrushBalance as `root` by default (`CRUSH_USER="root"`). A dedicated user limits what a flaw in the process could reach. CrushBalance needs root only to bind ports below 1024.

- **systemd** (the service `crushbalance` that the init script's `install` writes; [Install on Linux](Install-Linux.md)):
  1. `useradd --system --home-dir /var/opt/CrushBalance --shell /usr/sbin/nologin crushbalance`
  2. set `CRUSH_USER="crushbalance"` in `crushbalance_init.sh`;
  3. `chown -R crushbalance: /var/opt/CrushBalance` and `chmod 700 /var/opt/CrushBalance`;
  4. run `./crushbalance_init.sh install` as root. The unit it writes has `User=crushbalance` and `AmbientCapabilities=CAP_NET_BIND_SERVICE`: CrushBalance runs as that user and may still open ports below 1024.
  - From then on manage the service only with `systemctl`. **Never run `crushbalance_init.sh` as root** while the folder belongs to `crushbalance`: that user can replace the script, so root would run whatever it holds. To uninstall, stop the service, `chown -R root: /var/opt/CrushBalance`, look at the script, then run `uninstall` as root.
  - Keystores you add (`admin_keystore`, `tls_keystore`) must be readable by `crushbalance`.
- **Without systemd** `start` run by root starts CrushBalance as `CRUSH_USER` (with `su`, so the user needs a login shell), but that user cannot open ports below 1024. Redirecting the low ports to high ones (the script's comment: `iptables -t nat -A PREROUTING -p tcp -m tcp --dport 21 -j REDIRECT --to-ports 2121`) lets the listeners use ports above 1024.
- **The Java the script downloads.** With no Java 21 or newer on the host, the script downloads Eclipse Temurin's JRE from Adoptium over HTTPS, as the service user, into the install folder, and checks it against the SHA-256 that Adoptium's API gives ([Install on Linux](Install-Linux.md#crushbalances-own-java)). On a host that must not fetch software, install Java yourself or set `JAVA=` in the script: then nothing is downloaded.
- Run the CLI commands (`-set-admin-password`, `-check-config`) as the same user, so the files keep their owner.
- Whatever the user, CrushBalance's log-file guard never appends to, rotates or deletes a file that is not a CrushBalance 27 log (a symbolic link, another program's file, a CrushBalance 11 log), and the admin API offers no file access.

## The Windows service

The service "CrushBalance Server" runs as LocalSystem on CrushMFT's own service launcher (`service\CrushBalanceService.exe`, which runs Java as a child process), so whoever can replace its files can run code as SYSTEM.

- **Install only in a folder that only administrators can write to**, for example under `C:\Program Files`, never in the root of a drive (`-i` refuses it: `Install CrushBalance into a folder, not the root of a drive (E:\).`).
- **The ACL check.** `-i` refuses (exit code 4) when Everyone (`S-1-1-0`), Authenticated Users (`S-1-5-11`) or Users (`S-1-5-32-545`) may write to, modify or fully control the install folder, `service\` or the jar. It compares security identifiers, so it works in every Windows language. It prints the fix:
  ```
  icacls "<dir>" /inheritance:d
  icacls "<dir>" /remove:g *S-1-1-0 *S-1-5-11 *S-1-5-32-545 /T
  ```
- **Reading is a warning.** When those groups can read the install folder, `-i` installs, warns that `prefs.XML` inherits that access, and prints the same two commands ([What is sensitive](Hardening.md#what-is-sensitive)).
- `-Dcrushbalance.service.allow_writable_dir=true` turns the refusals into warnings. Use it only on a host where no untrusted user can log on.
- **The Java the service runs** is chosen by the launcher, not by `-i`, so `-i` cannot check it. Install Java only where administrators alone can write: a Java that ordinary users can modify lets them run code as SYSTEM.
- `crushbalance.key` gets a protected access list (its owner, SYSTEM and Administrators, nothing inherited) when it is created, and `-i` applies it again to an existing key file. If that fails, a warning is shown with the `icacls` commands to run from an elevated prompt, and the folder's access list is what protects the key.
- The launcher asks for administrator rights itself (one UAC prompt) for `-i` and `-r`. The web UI never installs or removes the service.

## Other settings

- **GeoIP:** use a separate ipstack key for the balancer, or watch the quota you share with CrushMFT; `geoip_monthly_limit` caps the balancer's lookups. Only public client addresses that stay connected for 2 seconds are sent.
- **Per-client caps:** `max_connections_per_client` on internet-facing listeners without an upstream proxy or a large NAT in front limits how many sessions one address can hold.
- **IP rules** work as CrushMFT's: a list with rules denies every client no rule matches. Test changes with "Test an IP" before saving them for a listener that serves the public.
- **Log level:** keep `info` or above in production; `debug` on `geoip` writes client addresses and locations.

## What the CrushBalance 27 security tests check

CrushBalance 27 is tested against the following. For an operator they mean:
- **Parsers of untrusted input are fuzzed:** the inbound PROXY decoder, the HTTP request head parser, the chunked-body framer, the `prefs.XML` reader and the admin API's JSON parser. Each ends malformed input with its documented error.
- **No request smuggling between the balancer and CrushMFT.** A corpus of 68 framing cases (`Content-Length` and `Transfer-Encoding` together or repeated, folded lines, bare line feeds, odd chunk sizes and more) and a 40,000-case differential fuzz were compared with the request framing of CrushFTP 11's HTTP server: whatever CrushMFT rejects, the balancer rejects, and a request both accept ends at the same byte. (CrushMFT's chunk decoder itself was not available for the comparison; a case whose outcome depends on it is rejected by the balancer.)
- **Secrets stay secret:** canary passwords, tokens and keys in every secret position never appear in an API response, the event stream, `/metrics`, the log file or the log views, also in safe mode and at the most detailed log level.
- **File modes hold under any umask:** with a umask of 000 the files of [What is sensitive](Hardening.md#what-is-sensitive) still get 0600 (directories 0700, the lock file 0644, logs 0640; `geoip-cache.json`, which only a real ipstack answer creates, is checked on its own); the setup token is deleted after setup; `sticky-pins.dat` holds no client address and no cookie value.
- **Backend TLS fails closed:** a backend whose certificate fails the endpoint's trust settings (an untrusted chain, a host-name mismatch without a pin, another certificate than the pinned one) never receives a byte from the client, and Check certificate sends no application data.
- **The admin server before login:** 64 stalled connections from one source and from 16, slow handshakes and readers that never read leave a logged-in administrator answered within a second ([admin_allowed_ips](Hardening.md#admin_allowed_ips), [Built-in protections (nothing to configure)](Hardening.md#built-in-protections-nothing-to-configure)).
- **`prefs.XML` is read as XML 1.0 only.** A file that declares another version is refused with `PREFS_PARSE` ("the XML declaration must say version="1.0""). XML 1.1 allows control characters, as references such as `&#1;`, that an XML 1.0 file, and so every later save, cannot hold: such a file would load and then fail every save.
