> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pgw.sipmicro.services/llms.txt
> Use this file to discover all available pages before exploring further.

# Security in pgw

> What pgw stores and how it protects it, which ports to open, and how pgw stops password guessing.

pgw is reachable from the internet, it holds the keys that can push to every one of your users, and it sits in front of your PBX's registrar. Most of its protection is built in and needs no setup. The rest is yours to do:

1. [Protect the master key](#protect-the-master-key), because it decrypts everything else.
2. [Open only the ports that pgw needs](#open-only-the-ports-that-pgw-needs), and keep the admin API local.
3. [Tell pgw which addresses your PBX sends from](#allow-the-pbx-to-send-calls-to-pgw), so that nobody else can send calls through it.
4. [Review the REGISTER ban](#register-ban), which stops password guessing against your PBX.

## What pgw stores

pgw keeps its records in one database file, `pgw.db`, in `data_dir`.

| Data | Protection |
| - | - |
| Push credentials: APNs keys, Firebase service accounts, VAPID private keys | Encrypted with AES-256-GCM. Each tenant has its own data key, which the master key encrypts. |
| SIP passwords, in managed mode only | Encrypted like the push credentials. In passthrough mode, pgw never sees a password. |
| Kamailio database passwords, with a Kamailio user source only | Encrypted like the push credentials. |
| Push tokens | Never sent to the PBX, never returned by the API, and never logged. |
| API keys | Stored as SHA-256 hashes. pgw shows a key once, when it creates it. |
| Push log | One record for each push, without the token, kept for 7 days by default (`push_event_retention_days`). |

Someone who copies `pgw.db` without the master key gets no push credentials and no passwords.

## What pgw does for you

* **It isn't an open relay.** pgw refuses, with `403`, any request on the PBX listener that doesn't come from an upstream's allowed addresses. A request from an app goes only to that app's PBX.
* **Push tokens stay inside pgw.** pgw removes the push parameters from everything that it sends to the PBX.
* **Logs and API answers carry no secrets.** pgw drops tokens, push parameters, and credentials from every log line. The API returns none of them, except a web app's VAPID key when you export it for a backup. Logs do show each device's SIP address and its User-Agent, which can contain a name such as `Alice's iPhone`, so treat them as personal data.
* **Registrations are rate-limited.** One source address can send 5 REGISTERs a second, with a burst of 10. Above that, pgw answers `503` with `Retry-After: 5`. Change it with `register_rate_per_ip`.

## Protect the master key

The master key is a base64-encoded 32-byte key. pgw reads it from the file that `PGW_MASTER_KEY_FILE` names, or from the variable `PGW_MASTER_KEY`. It has no setting in `config.yaml`, so that it never ends up in a configuration repository.

* **Use the file.** A variable is inherited by child processes and can appear in crash reports.
* **Set the file's mode to `600` or `400`.** pgw refuses to start with a key file that its group or other users can access.
* **Back up the key separately from `pgw.db`.** Someone who holds both can decrypt every stored credential, and someone who holds only one can't.

> [!WARNING]
>
> If you lose the master key, pgw can't decrypt the push credentials or the stored passwords. You then start with an empty `data_dir` and create the tenant, apps, upstreams, and users again.

A test setup keeps the key in a `.env` file instead, which `pgw init` creates with mode `600`. Keep the file out of version control. Except on Windows, pgw refuses to start with a master key from a `.env` file that other users can read. See [The .env file](https://docs.pgw.sipmicro.services/reference/env-file.md).

## Open only the ports that pgw needs

| Listener | Default | Who must reach it |
| - | - | - |
| Apps | `0.0.0.0:5061`, TLS 1.2 or later | The internet. |
| Browser apps | Off. Set `app_wss_listen` to turn it on. | The internet. |
| PBX | `0.0.0.0:5060`, UDP and TCP | Your PBX only. Close it to everyone else with a firewall. |
| Admin API, metrics, and health checks | `127.0.0.1:8080`, plain HTTP | Only the pgw host itself. |

> [!WARNING]
>
> The admin API has no TLS. Keep `admin_listen` on `127.0.0.1`. To manage pgw from another host, use an SSH tunnel or put a TLS reverse proxy in front of it.

## Allow a browser page to call the admin API

A browser blocks a web page from reading the admin API's answers, because pgw sends no CORS headers by default. To let one page call it, list the page's origin:

```yaml theme={null}
admin_cors_origins:
  - https://docs.example.com
```

Each request still needs an API key, and pgw never accepts cookies on a cross-origin request. An entry of `*` allows a page on any site. The setting doesn't move the API, which stays on `admin_listen`, without TLS. For the playground in these docs, see [Use the playground](https://docs.pgw.sipmicro.services/api/introduction.md#use-the-playground).

## Allow the PBX to send calls to pgw

pgw accepts calls and other requests on the PBX listener only from the addresses in the upstream's `invite_source_cidrs`. You can leave the list empty only when the upstream's host is an IP address. pgw then accepts requests from that address. Any other address gets 403 Forbidden.

**1. Set the PBX's addresses**

When you create the upstream, list the addresses that the PBX sends from. A PBX cluster needs the address of every node.

```bash theme={null}
pgw upstream create --name office --host pbx.example.com --invite-source-cidrs 192.0.2.10/32
```

**2. Find a missing address**

If calls get 403 Forbidden, watch the SIP traffic on the pgw host while you call the app. The source address of the INVITE is the one to add.

```bash theme={null}
sudo tcpdump -n udp port 5060
```

**3. Update the list**

Give the whole new list. It replaces the old one, and the change applies at once.

```bash theme={null}
pgw upstream update --id <upstream-id> --invite-source-cidrs 192.0.2.10/32,192.0.2.11/32
```

## REGISTER ban

The PBX sees every REGISTER come from pgw, so it can't tell a password guesser from a legitimate device. pgw counts the REGISTERs from each source address that the PBX, or pgw in managed mode, refuses for bad credentials. After 10 within 10 minutes, pgw bans the address for 15 minutes. Its REGISTERs get 503 with `Retry-After` and don't reach the PBX. An IPv6 source counts by its /64 prefix.

* A refresh over a connection that registered the same account, with the same username, still reaches the PBX, so registered devices keep working.
* Devices behind the same NAT address share the ban. If many devices share an address, raise `register_auth_failures`.
* Behind a TCP proxy that hides the devices' addresses, every device shares the proxy's address, so set `register_auth_failures: 0`.
* pgw tracks at most 65,536 source addresses. While the table is full, pgw logs `register ban table full` and doesn't count new addresses.
* A restart of pgw clears every ban.

To change the ban, set `register_auth_failures`, `register_auth_failure_window`, and `register_ban`. To see the active bans, run `pgw ban list`. To lift a ban at once, run `pgw ban lift --source <address>`.

## Block banned addresses with fail2ban

pgw's ban covers only REGISTERs. To block a banned address at the firewall, point fail2ban at pgw's log line `register source banned`. Keep the block short. It also cuts off the devices already registered from that address, and a carrier-grade NAT address can hold many users.

**1. Create the filter**

Create `/etc/fail2ban/filter.d/pgw.conf`. The pattern depends on `log_format`.

> [tab] text (default)
>
> ```ini theme={null}
> [Definition]
> failregex = msg="register source banned".* banned_source=<HOST>
> ```

> [tab] json
>
> ```ini theme={null}
> [Definition]
> failregex = "msg":"register source banned".*"banned_source":"<HOST>"
> ```

The filter matches IPv4 addresses. For an IPv6 source, `banned_source` holds a /64 prefix, such as `2001:db8:1:2::/64`, which the filter doesn't match. Block an IPv6 prefix with a firewall rule of your own.

**2. Create the jail**

Create `/etc/fail2ban/jail.d/pgw.conf`. Set `bantime` to no longer than `register_ban`.

```ini theme={null}
[pgw]
enabled = true
backend = systemd
journalmatch = _SYSTEMD_UNIT=pgw.service
filter = pgw
maxretry = 1
bantime = 15m
```

**3. Reload fail2ban**

```bash theme={null}
sudo fail2ban-client reload
```

## Next steps

> [card] [Logs](https://docs.pgw.sipmicro.services/logs.md)
>
> Read the ban and refusal lines that this page names.

> [card] [Settings reference](https://docs.pgw.sipmicro.services/reference/settings.md)
>
> Look up the limits on this page, with their defaults and ranges.

> [card] [Back up, move, and restore pgw](https://docs.pgw.sipmicro.services/backup-move-restore.md)
>
> Back up the database and the master key, so that a lost host doesn't cost the credentials.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.