# Network sets and country blocking

URL: https://scalws.com/docs/guide/network-sets/
Source: `docs/guide/network-sets.md` in the ScalWS repository

A network set is a named list of client networks. Routes refuse or admit clients by set
name: `deny_networks` and `allow_networks`. A set is either a file of CIDR networks (what
ScalPanel's edge writes) or a list of countries looked up in a country database (for
standalone servers). The design record is
[ADR-0054](https://scalws.com/docs/adr/0054-edge-features-for-scalpanel/).

```yaml
server:
  listeners:
    - {name: http, address: "0.0.0.0:80"}
  networks:
    BAD: {file: /etc/scalws/networks/bad.txt}
    KP: {countries: [KP]}
  geoip: {database: /var/lib/scalws/geoip/country.mmdb}
tenants:
  - name: shop
    applications:
      - name: web
        domains: [shop.example.com]
        root: /srv/shop
        runtime: {type: static}
        routes:
          - path: /
            deny_networks: [BAD, KP]
            runtime: {type: static}
```

## Sets

[`server.networks`](https://scalws.com/docs/reference/server/#server.networks) maps a name to one set.

* Names are 1 to 32 characters of `A-Z a-z 0-9 _ -`. At most 512 sets.
* A set has exactly one of `file` and `countries`.
* `file`: the absolute path of a CIDR list (below).
* `countries`: 1 to 249 ISO 3166-1 alpha-2 codes (`CN`, `kp`; stored upper case). `XK`
  (Kosovo) is accepted, as DB-IP and MaxMind use it. A set with `countries` needs
  [`server.geoip.database`](#country-database).
* A route that names a set that does not exist is an error.

## CIDR files

A file is UTF-8 text with one IPv4 or IPv6 address or CIDR network per line:

```text
# CN, generated 2026-11-17
198.51.100.0/24
203.0.113.0/25
2001:db8::/32
```

* Spaces around an entry are trimmed. Empty lines and lines starting with `#` are
  ignored. Any other line that is not an address or network fails the load, with an error
  that names the line (`server.networks.CN.file:3: not an IP address or CIDR network`),
  not its content.
* Host bits may be set (`192.0.2.77/24` means `192.0.2.0/24`).
* IPv4-mapped IPv6 clients (`::ffff:198.51.100.7`) match IPv4 entries.
* At most 32 MiB per file and 1 000 000 entries over all sets.
* Only a regular file is read. A final symbolic link is refused (`... is a symbolic
  link`): the file is opened with `O_NOFOLLOW`, so a link cannot point a set at another
  file. Links in the folders above the file are followed; keep those folders writable by
  root only.

Files are read when a configuration is built: at start, by `scalwsctl check` and on every
reload. A set whose path and file (device, inode, size and modification time) did not
change is not read again. A missing or invalid file fails the load as a whole and the
running configuration stays. With
[`server.reload.watch`](https://scalws.com/docs/reference/server/#server.reload) the files are watched like
certificates, so a changed file reloads the server.

Replace a file by writing a new file and renaming it over the old one. ScalPanel writes a
new `gen-N` directory for each generation, so its sets are read anew on each reload.

## Route keys

```yaml
routes:
  - path: /
    deny: [192.0.2.7/32]
    deny_networks: [CN]
    runtime: {type: proxy, upstream: "http://192.0.2.40:8080"}
  - path: /admin
    allow: [198.51.100.10]
    allow_networks: [OFFICE]
    runtime: {type: proxy, upstream: "http://192.0.2.40:8080"}
```

* [`deny_networks`](https://scalws.com/docs/reference/routes/#tenants-.applications-.routes-.deny_networks):
  clients in any listed set get `403`.
* [`allow_networks`](https://scalws.com/docs/reference/routes/#tenants-.applications-.routes-.allow_networks):
  when set, only clients in a listed set or in the route's `allow` are admitted; others
  get `403`.

With the route's `allow` and `deny`, the rule is:

```text
refused = in deny or in deny_networks
          or ((allow or allow_networks is set) and not in allow and not in allow_networks)
```

The client is the address the server resolved, never a header a client sent directly.
From a peer in [`server.trusted_proxies`](https://scalws.com/docs/guide/configuration/#trusted_proxies) it is read from
the header named by `server.client_address.header` (default `X-Forwarded-For`); from a
peer in the networks of a [`server.client_address.presets`](https://scalws.com/docs/guide/configuration/#client_address)
entry it is read from that vendor's header (`CF-Connecting-IP` for `cloudflare`). From any
other peer the peer itself is the client. Such a header is believed as sent: whoever is a
trusted peer, or can send from a preset's networks, decides the client address and so the
set and the country it falls in. A
refusal goes through the route's error path, so the route's `response_headers` apply, and
is counted in `scalws_security_blocked_total` with `reason="networks"` when a set decided.
A `deny` match, and a client outside `allow` on a route without `allow_networks`, count
as `route_access`. Routes with network lists never use the response
cache. When `.htaccess` rewrote the path, the lists of the client's own route are checked
too.

Each route's list is merged once into one table and shared by every route with the same
names, so a request does one binary search per list and allocates nothing.

## Country database

Country sets need [`server.geoip.database`](https://scalws.com/docs/reference/server/#server.geoip): the
absolute path of a MaxMind DB format country database. Supported layouts: MaxMind GeoIP2
and GeoLite2 Country, DB-IP IP to Country Lite (`country.iso_code`) and IPinfo Lite
(`country_code`).

* The file is opened only when a set uses `countries`. It is read into memory (no `mmap`,
  so a file written in place cannot crash the server).
* It must be a regular file (not a link) of 1 KiB to 256 MiB, owned by root or by the
  user scalwsd runs as, and not writable by group or others.
* The owner and mode are checked when the file is read: at start and when a reload finds
  a changed file (another inode, size or modification time). A `chmod` or `chown` alone
  changes none of these, so it is not noticed until the file is read again.
* A reload keeps the loaded database while the file is unchanged. A missing database
  fails the reload.
* A client is in a country set when the database gives its address one of the set's
  codes. Private, loopback, link-local, unspecified and documentation addresses, and
  addresses the database does not know, are in no country set. The lookup runs at most
  once per request, and only when the matched route names a country set.
* A country lookup is an estimate. The database maps address ranges to countries with
  limited accuracy (DB-IP Lite is a free, coarse database, and ranges move between monthly
  builds), so a legitimate client may be placed in the wrong country. A client behind a
  VPN, a proxy, Tor or a cloud host carries the country of that exit, not its own. Country
  sets are a coarse filter, not access control: use `allow`, `allow_networks` or
  authentication for anything that must hold.
* `scalwsctl status --json` and the admin API (`GET /v1/status`) show the field `geoip`
  with `type`, `build_epoch`, `build_date`, `lookups` and `reads`; the plain
  `scalwsctl status` view does not print it. The gauge `scalws_geoip_build_timestamp_seconds` is the build
  time (0 without a database): alert when it is old.
* Under scalws-controller, where the sandbox limits reads, the database gets a read rule
  only when a set uses `countries`, like every other path the configuration names. The
  CIDR files get one too ([sandbox](https://scalws.com/docs/guide/sandbox/)).

## `scalwsctl geoip update`

```sh
sudo scalwsctl geoip update
```

Installs DB-IP's free IP to Country Lite database at `server.geoip.database` (default
`/var/lib/scalws/geoip/country.mmdb`) and reloads the server.

* It fetches `https://download.db-ip.com/free/dbip-country-lite-YYYY-MM.mmdb.gz` for the
  current UTC month, and the previous month's file when this month's is not out yet
  (404). TLS uses the system's roots; redirects are not followed.
* The download is at most 64 MiB, the decompressed file 1 MiB to 256 MiB.
* Checks before anything is written: a country database, built at most 120 days ago
  (`--force` accepts an older one) and at most 2 days ahead of the clock, no country for a private
  address, and the right country for at least three of four well-known addresses.
* The file is written next to the target and renamed over it, owned by root. On any error
  nothing is written and the previous database stays.
* It needs root. `--no-reload` writes without reloading. The output names the file, the
  build date, `configuration: <path>` (the configuration it read) and a note when
  `server.geoip.database` is not set or no set uses `countries`.

The database is licensed CC BY 4.0. Its credit, printed by the command and shown here:

> IP geolocation by DB-IP (https://db-ip.com), licensed CC BY 4.0
> ([licence](https://creativecommons.org/licenses/by/4.0/)).

### Monthly timer (systemd)

The packages install `scalws-geoip-update.service` and `scalws-geoip-update.timer`. The
timer is disabled. Turn it on with:

```sh
sudo systemctl enable --now scalws-geoip-update.timer
```

It runs on the 3rd of each month at 04:00, with a random delay of up to one day, so hosts
do not all download at once (DB-IP builds the month's file on the 1st).

The service may write only below `/var/lib/scalws/geoip`. For a database elsewhere, add
its directory with a drop-in (`sudo systemctl edit scalws-geoip-update.service`):

```ini
[Service]
ReadWritePaths=/srv/geoip
```

### Alpine Linux (no systemd)

The apk does not schedule the update. To run it monthly with crond, create
`/etc/periodic/monthly/scalws-geoip-update` (no dot in the name, mode `0755`):

```sh
#!/bin/sh
/usr/bin/scalwsctl geoip update >/var/log/scalws/geoip-update.log 2>&1
```

Alpine's crond runs `/etc/periodic/monthly` on the 1st. When this month's file is not out
yet, the command installs the previous month's.

## See also

* [Hotlink protection](https://scalws.com/docs/guide/hotlink-protection/): the route's `referer`.
* [ScalPanel edge](https://scalws.com/docs/guide/scalpanel-edge/): the generator's network sets.
* [Security](https://scalws.com/docs/guide/security/): the order of checks and per-client limits.
* [request-processing.md](https://scalws.com/docs/guide/request-processing/#request): where route lists are checked.
