Compare commits
31
Commits
dev-v0.1.71
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0a742d5a0 | ||
|
|
354d711f3d | ||
|
|
0cc3aab07e | ||
|
|
a54a50623f | ||
|
|
7168914d12
|
||
|
|
b152f54f4c | ||
|
|
70a99789d8 | ||
|
|
d77e8deef9 | ||
|
|
d1a24d5e3a | ||
|
|
6d51a6b716 | ||
|
|
31e649f670 | ||
|
|
c0b7b0b4d4 | ||
|
|
01b2912765 | ||
|
|
13ea230e73 | ||
|
|
75638f7e1b | ||
|
|
bd268c3e82 | ||
|
|
75d7104670 | ||
|
|
933e373247 | ||
|
|
db1bd2e819 | ||
|
|
4bacfbfd99 | ||
|
|
f1ae8d598c | ||
|
|
fd775091b5 | ||
|
|
87fc8a3f3c | ||
|
|
1701f36638 | ||
|
|
3de78c2f6b | ||
|
|
abc8ae9a6b | ||
|
|
0a45ccc315 | ||
|
|
bd283fbf22 | ||
|
|
29eab9f955 | ||
|
|
1d95451402 | ||
|
|
230ea19b34 |
No files matched your search
@@ -16,7 +16,7 @@ permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
PACKAGE_VERSION: 1.1.60
|
||||
PACKAGE_VERSION: 2.1.0
|
||||
|
||||
jobs:
|
||||
build-android:
|
||||
|
||||
@@ -14,7 +14,7 @@ permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
PACKAGE_VERSION: 1.1.60
|
||||
PACKAGE_VERSION: 2.1.0
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
paths:
|
||||
- 'core/**'
|
||||
- 'CMakeLists.txt'
|
||||
- 'nipovpn/etc/nipovpn/config.yaml'
|
||||
- 'tests/**'
|
||||
- '.github/workflows/test.yml'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: tests-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
name: End-to-end (${{ matrix.build }})
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- build: release
|
||||
build_type: Release
|
||||
cxx_flags: ""
|
||||
- build: sanitizers
|
||||
build_type: RelWithDebInfo
|
||||
cxx_flags: "-fsanitize=address,undefined -fno-omit-frame-pointer"
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
build-essential \
|
||||
cmake \
|
||||
libssl-dev \
|
||||
libboost-all-dev \
|
||||
libyaml-cpp-dev \
|
||||
python3-yaml \
|
||||
curl \
|
||||
openssl
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
cmake -S . -B build \
|
||||
-DCMAKE_BUILD_TYPE=${{ matrix.build_type }} \
|
||||
-DCMAKE_CXX_FLAGS="${{ matrix.cxx_flags }}"
|
||||
cmake --build build -j"$(nproc)"
|
||||
|
||||
- name: Run end-to-end tests
|
||||
env:
|
||||
ASAN_OPTIONS: detect_leaks=0
|
||||
UBSAN_OPTIONS: print_stacktrace=1
|
||||
run: python3 tests/e2e.py --binary build/core/nipovpn --artifacts test-artifacts
|
||||
|
||||
- name: Upload logs of failed tests
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-logs-${{ matrix.build }}
|
||||
path: test-artifacts
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
@@ -15,7 +15,7 @@ permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
PACKAGE_VERSION: 1.1.60
|
||||
PACKAGE_VERSION: 2.1.0
|
||||
|
||||
jobs:
|
||||
build-windows:
|
||||
|
||||
+3
-2
@@ -40,7 +40,8 @@ test
|
||||
|
||||
|
||||
.git
|
||||
.github
|
||||
*.deb
|
||||
*.tar.gz
|
||||
*.log
|
||||
*.log
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -24,7 +24,7 @@ It is written in C++20 on top of Boost.Asio, OpenSSL and yaml-cpp.
|
||||
|
||||
### Client side (agent)
|
||||
|
||||
- **HTTP proxy and SOCKS5 proxy** for local applications (`general.protocol`).
|
||||
- **HTTP proxy and SOCKS5 proxy** for local applications (`agent.protocol`).
|
||||
- HTTP: plain HTTP requests and `CONNECT` tunnels (HTTPS).
|
||||
- SOCKS5: `CONNECT` command, no authentication, with IPv4, IPv6 and domain
|
||||
name targets.
|
||||
@@ -48,7 +48,7 @@ It is written in C++20 on top of Boost.Asio, OpenSSL and yaml-cpp.
|
||||
### Encryption
|
||||
|
||||
- **AES-256-GCM payload encryption** (on by default). The key is the SHA-256 of
|
||||
`general.token`; each message gets a random 12-byte nonce and a 16-byte
|
||||
the user's token; each message gets a random 12-byte nonce and a 16-byte
|
||||
authentication tag, so tampered or wrongly keyed payloads are rejected.
|
||||
- **TLS between agent and server** (`tlsEnable`): TLS 1.2 minimum, TLS 1.3
|
||||
preferred, with AEAD-only cipher suites (AES-GCM, ChaCha20-Poly1305).
|
||||
@@ -78,6 +78,15 @@ neither.
|
||||
### Operations
|
||||
|
||||
- **Config validation at startup** with clear error messages.
|
||||
- **Per-user monthly traffic limits** (e.g. 2 GB), with usage kept in an
|
||||
editable file. See [Usage limits](#usage-limits).
|
||||
- **Multiple users** on one server, each with their own token. Users can be
|
||||
added, disabled or removed without a restart. See [Multiple users](#multiple-users).
|
||||
- **Reload without restart** on `SIGHUP` (`systemctl reload`). See
|
||||
[Reloading the configuration](#reloading-the-configuration).
|
||||
- **Web dashboard** to manage users and server settings, watch usage and
|
||||
activity, and share agent configs and `nipovpn://` links with QR codes. See
|
||||
[Dashboard](#dashboard).
|
||||
- **Warning when the public sample token is still in use.**
|
||||
- **Log levels** `INFO`, `TRACE` (per-request source/destination) and `DEBUG`;
|
||||
logs go to a file and to stdout.
|
||||
@@ -110,7 +119,8 @@ Browser/app ──HTTP or SOCKS5──▶ Agent ──decoy HTTP(S)──▶ Ser
|
||||
1. A local application sends a request to the agent (HTTP proxy or SOCKS5).
|
||||
SOCKS5 requests are converted to an HTTP `CONNECT` internally.
|
||||
2. The agent builds an envelope `action + session ID + request bytes`, encrypts
|
||||
it with AES-256-GCM (if `aesEnable`) and Base64-encodes it.
|
||||
it with AES-256-GCM (if `aesEnable`; otherwise signs it with HMAC-SHA256)
|
||||
and Base64-encodes it.
|
||||
3. The envelope is sent as the body of a decoy request such as
|
||||
`PUT /login` with `Host: cloudflare.com`, over TLS if `tlsEnable`.
|
||||
4. The server decodes and decrypts the body and performs the action:
|
||||
@@ -128,10 +138,12 @@ Browser/app ──HTTP or SOCKS5──▶ Agent ──decoy HTTP(S)──▶ Ser
|
||||
| Platform | How |
|
||||
|---|---|
|
||||
| Debian / Ubuntu (amd64, arm64) | `.deb` from the [releases page](https://github.com/MortezaBashsiz/nipovpn/releases), tested on Ubuntu 24.04 |
|
||||
| Arch Linux | [AUR package](https://aur.archlinux.org/packages/nipovpn) |
|
||||
| Build from source on Linux | [Linux build guide](guides/BuildLinux.md) |
|
||||
| Docker | [Docker guide](guides/Docker.md) |
|
||||
| Nix / NixOS | [Nix guide](guides/Nix.md) |
|
||||
| Termux | [Termux guide](guides/InstallTermux.md) |
|
||||
| Dashboard (web page to manage the server) | [nipovpn-dashboard](https://github.com/MortezaBashsiz/nipovpn-dashboard) |
|
||||
| Windows (x86_64) | zip from the [releases page](https://github.com/MortezaBashsiz/nipovpn/releases) (`windows-v*` tags) |
|
||||
| Android | [nipovpn-android](https://github.com/MortezaBashsiz/nipovpn-android) |
|
||||
|
||||
@@ -152,6 +164,35 @@ sudo systemctl enable --now nipovpn-server.service # on the server
|
||||
sudo systemctl enable --now nipovpn-agent.service # on the agent machine
|
||||
```
|
||||
|
||||
### Arch Linux
|
||||
|
||||
Install NipoVPN from the AUR using your preferred AUR helper:
|
||||
|
||||
```bash
|
||||
paru -S nipovpn
|
||||
```
|
||||
|
||||
Or build and install it manually:
|
||||
|
||||
```bash
|
||||
git clone https://aur.archlinux.org/nipovpn.git
|
||||
cd nipovpn
|
||||
makepkg -si
|
||||
```
|
||||
|
||||
The package installs:
|
||||
|
||||
- `/usr/bin/nipovpn`
|
||||
- `/etc/nipovpn/config.yaml`
|
||||
- `nipovpn-server.service` and `nipovpn-agent.service`
|
||||
|
||||
```bash
|
||||
sudo systemctl enable --now nipovpn-server.service # on the server
|
||||
sudo systemctl enable --now nipovpn-agent.service # on the agent machine
|
||||
```
|
||||
|
||||
See the [AUR package page](https://aur.archlinux.org/packages/nipovpn) for package details.
|
||||
|
||||
### From source
|
||||
|
||||
Requirements: a C++20 compiler, CMake ≥ 3.22, Boost ≥ 1.88, yaml-cpp ≥ 0.8 and
|
||||
@@ -178,15 +219,26 @@ sudo mkdir -p /var/log/nipovpn/
|
||||
sudo touch /var/log/nipovpn/nipovpn.log
|
||||
```
|
||||
|
||||
### 2. Pick a shared token
|
||||
### 2. Create a user
|
||||
|
||||
`general.token` must be at least 32 bytes and identical on the agent and the
|
||||
server. Do not use the sample token from the shipped config.
|
||||
Generate a token of at least 32 bytes for each person. Do not use the sample
|
||||
tokens from the shipped config.
|
||||
|
||||
```bash
|
||||
openssl rand -hex 16 # prints 32 hex characters
|
||||
```
|
||||
|
||||
On the server, list it in `server.users`. On that person's machine, put the
|
||||
same token in `agent.token`:
|
||||
|
||||
```yaml
|
||||
# server config # agent config
|
||||
server: agent:
|
||||
users: token: "<alice's token>"
|
||||
- name: alice
|
||||
token: "<alice's token>"
|
||||
```
|
||||
|
||||
### 3. TLS certificate (if `tlsEnable: true`)
|
||||
|
||||
The server needs a certificate and key. A self-signed pair is enough when
|
||||
@@ -209,8 +261,8 @@ sudo nipovpn server /etc/nipovpn/config.yaml
|
||||
### 5. Run the agent
|
||||
|
||||
On your machine, set `agent.serverIp`/`agent.serverPort` to the server's
|
||||
address and make sure `token`, `aesEnable`, `tlsEnable` and `tunnelEnable` match
|
||||
the server. Then:
|
||||
address, set `agent.token` to one of the server's users, and make sure
|
||||
`aesEnable`, `tlsEnable` and `tunnelEnable` match the server. Then:
|
||||
|
||||
```bash
|
||||
sudo nipovpn agent /etc/nipovpn/config.yaml
|
||||
@@ -219,10 +271,10 @@ sudo nipovpn agent /etc/nipovpn/config.yaml
|
||||
### 6. Point your applications at the agent
|
||||
|
||||
```bash
|
||||
# protocol: socks5
|
||||
# agent.protocol: socks5
|
||||
curl --socks5-hostname 127.0.0.1:8080 https://example.com
|
||||
|
||||
# protocol: http
|
||||
# agent.protocol: http
|
||||
curl -x http://127.0.0.1:8080 https://example.com
|
||||
```
|
||||
|
||||
@@ -236,24 +288,15 @@ Settings marked **must match** have to be the same on agent and server.
|
||||
|
||||
### `general`
|
||||
|
||||
Settings both sides use. Old configs that still have one of the settings below
|
||||
in `general` keep working, with a warning naming the keys to move.
|
||||
|
||||
| Key | Type | Default | Description |
|
||||
|---|---|---|---|
|
||||
| `token` | string | — | Shared secret, ≥ 32 bytes when `aesEnable` is on. The AES key is derived from it. **Must match.** |
|
||||
| `aesEnable` | bool | `true` | AES-256-GCM payload encryption. **Must match.** |
|
||||
| `protocol` | `http` \| `socks5` | — | Protocol the agent accepts from local applications. |
|
||||
| `bufferSize` | 1–65536 | `65536` | Maximum bytes read per operation. |
|
||||
| `fakeUrls` | list | — | Hosts used at random for the decoy `Host` header and TLS SNI. |
|
||||
| `methods` | list | — | HTTP methods used at random for decoy requests. |
|
||||
| `endPoints` | list | — | URL paths used at random for decoy requests (`/api`, `/login`, ...). |
|
||||
| `timeout` | seconds | `10` | I/O timeout for stalled connections. `0` disables it. |
|
||||
| `pullTimeout` | milliseconds | `1` | Base polling interval in polling mode. |
|
||||
| `tunnelEnable` | bool | `false` | `true` = direct tunnel mode, `false` = polling mode. **Must match.** |
|
||||
| `connectionReuse` | bool | `false` | Reuse one keep-alive connection between agent and server. |
|
||||
| `tlsEnable` | bool | `false` | TLS between agent and server. **Must match.** |
|
||||
| `tlsVerifyPeer` | bool | `false` | Agent verifies the server certificate. |
|
||||
| `tlsCertFile` | path | — | Server certificate (PEM, chain allowed). |
|
||||
| `tlsKeyFile` | path | — | Server private key (PEM). |
|
||||
| `tlsCaFile` | path | — | CA file the agent uses when `tlsVerifyPeer` is on. |
|
||||
| `timeout` | seconds | `10` | I/O timeout for stalled connections. `0` disables it. Each side uses its own value. |
|
||||
|
||||
### `log`
|
||||
|
||||
@@ -269,6 +312,9 @@ Settings marked **must match** have to be the same on agent and server.
|
||||
| `threads` | `2` | Worker threads. |
|
||||
| `listenIp` | `127.0.0.1` | IPv4 address to listen on. |
|
||||
| `listenPort` | `8080` | Port to listen on (443 is a good choice to blend in). |
|
||||
| `bufferSize` | `65536` | Maximum bytes read from a destination at a time in polling mode, 1–65536. |
|
||||
| `tlsCertFile` | — | Server certificate (PEM, chain allowed), used when `tlsEnable` is on. |
|
||||
| `tlsKeyFile` | — | Server private key (PEM). |
|
||||
|
||||
### `agent`
|
||||
|
||||
@@ -277,10 +323,169 @@ Settings marked **must match** have to be the same on agent and server.
|
||||
| `threads` | `2` | Worker threads. |
|
||||
| `listenIp` | `127.0.0.1` | IPv4 address for local applications to connect to. |
|
||||
| `listenPort` | `8080` | Port for local applications. |
|
||||
| `protocol` | — | `http` or `socks5`: the protocol local applications use to connect to the agent. |
|
||||
| `serverIp` | `127.0.0.1` | IPv4 address of the NipoVPN server. |
|
||||
| `serverPort` | `8080` | Port of the NipoVPN server. |
|
||||
| `httpVersion` | `1.1` | HTTP version in decoy requests. |
|
||||
| `userAgent` | `NipoAgent` | `User-Agent` header in decoy requests. |
|
||||
| `fakeUrls` | — | Hosts used at random for the decoy `Host` header and TLS SNI. |
|
||||
| `methods` | `GET` | HTTP methods used at random for decoy requests. |
|
||||
| `endPoints` | `api` | URL paths used at random for decoy requests (`/api`, `/login`, ...). |
|
||||
| `pullTimeout` | `1` | Base polling interval in milliseconds in polling mode. |
|
||||
| `connectionReuse` | `false` | Reuse one keep-alive connection to the server. The server follows the agent's choice. |
|
||||
| `tlsVerifyPeer` | `false` | Verify the server certificate. |
|
||||
| `tlsCaFile` | — | CA file used when `tlsVerifyPeer` is on. |
|
||||
| `token` | — | This agent's token, ≥ 32 bytes. Must be the token of an enabled user on the server. The AES key (or, with `aesEnable: false`, the signing key) is derived from it; the token itself is never sent. |
|
||||
|
||||
### `server.users`
|
||||
|
||||
The users allowed to connect, each with their own token. Agents do not use
|
||||
this block.
|
||||
|
||||
| Key | Default | Description |
|
||||
|---|---|---|
|
||||
| `name` | — | 1–64 characters of `A-Z a-z 0-9 . _ - @`. Unique. Shown in the server log. |
|
||||
| `token` | — | The user's token, ≥ 32 bytes. Unique. The user's agent puts it in `agent.token`. |
|
||||
| `enabled` | `true` | `false` rejects the user without deleting the entry. |
|
||||
| `limit` | none | Traffic allowed per month, e.g. `2GB`, `500MB`, `1.5GiB`. See [Usage limits](#usage-limits). |
|
||||
|
||||
### `server.usage` (optional)
|
||||
|
||||
| Key | Default | Description |
|
||||
|---|---|---|
|
||||
| `file` | `/var/lib/nipovpn/usage.yaml` | Where per-user usage is kept. Changing it needs a restart. |
|
||||
| `resetDay` | `1` | Day of the month (1–28) on which everyone's usage goes back to zero. |
|
||||
|
||||
## Multiple users
|
||||
|
||||
Every person gets their own token. The **server** lists them all in
|
||||
`server.users`:
|
||||
|
||||
```yaml
|
||||
server:
|
||||
users:
|
||||
- name: alice
|
||||
token: "4f3c9a...32 or more characters"
|
||||
- name: bob
|
||||
token: "b81e07...32 or more characters"
|
||||
enabled: false # bob is rejected until this is set back to true
|
||||
```
|
||||
|
||||
Each user's agent puts their token in `agent.token`. All other settings that
|
||||
must match (such as `aesEnable`, `tlsEnable` and `tunnelEnable`) are shared by
|
||||
everyone.
|
||||
|
||||
- The server identifies a request's user by which token decrypts it, or with
|
||||
`aesEnable: false`, by which token's HMAC-SHA256 signature matches. Nothing on
|
||||
the wire names the user, so this adds nothing for a censor to fingerprint.
|
||||
- With `aesEnable: false`, requests are signed but not encrypted: tampered
|
||||
requests are rejected, but anyone on the path can read them unless
|
||||
`tlsEnable` is on.
|
||||
- The server log shows the user on each connection: `[SRC ...] [USER alice]`.
|
||||
- A tunnel opened by one user cannot be used by another user.
|
||||
- **Upgrading from `general.token`:** older configs still work. An agent reads
|
||||
`general.token` when `agent.token` is missing, and a server without a `server.users`
|
||||
list accepts `general.token` as a single user named `default`. Both log a
|
||||
deprecation warning at startup. To migrate, move the agent's token to
|
||||
`agent.token` and add it to the server's `server.users` list. Agents of any version
|
||||
keep working, since the token on the wire is the same.
|
||||
- Each new connection costs one decryption attempt per enabled user until a
|
||||
token matches. A reused connection tries its last user first. This is fine
|
||||
for dozens of users; with hundreds, prefer `connectionReuse: true`.
|
||||
|
||||
To add, disable or remove a user, edit the config and [reload](#reloading-the-configuration).
|
||||
When a user is removed or disabled, or their token changes, the server closes
|
||||
their open connections and tunnels on reload.
|
||||
|
||||
## Usage limits
|
||||
|
||||
A server with a `server.users` list counts each user's traffic: the bytes they send to
|
||||
websites plus the bytes they receive from them. NipoVPN's own overhead (decoy
|
||||
HTTP framing, base64, encryption) is not counted. Give a user a monthly
|
||||
allowance with `limit`:
|
||||
|
||||
```yaml
|
||||
server:
|
||||
usage:
|
||||
resetDay: 1 # everyone's usage resets on the 1st of each month
|
||||
users:
|
||||
- name: alice
|
||||
token: "..."
|
||||
limit: 2GB # KB/MB/GB/TB = powers of 1000; KiB/MiB/GiB/TiB = powers of 1024
|
||||
- name: bob
|
||||
token: "..." # no limit
|
||||
```
|
||||
|
||||
When a user reaches their limit, the server closes their open connections and
|
||||
refuses new ones until the next period, and logs:
|
||||
|
||||
```
|
||||
[Usage] user alice reached their limit of 2.00 GB; blocked until the next period
|
||||
```
|
||||
|
||||
They regain access as soon as their usage drops below the limit: at the next
|
||||
`resetDay`, when you raise their limit (edit the config and reload), or when you
|
||||
reset them.
|
||||
|
||||
**Seeing and changing usage.** The server writes usage to `server.usage.file`
|
||||
(default `/var/lib/nipovpn/usage.yaml`) every 30 seconds, on reload and on
|
||||
shutdown:
|
||||
|
||||
```yaml
|
||||
period: "2026-11-01"
|
||||
users:
|
||||
alice: {used: 2000123456} # 2.00 GB of 2.00 GB (100%), blocked
|
||||
bob: {used: 734003200} # 734.00 MB, no limit
|
||||
```
|
||||
|
||||
To reset or change a user's usage, edit their `used` number (for example set it
|
||||
to `0`) and save. The server applies the edit within 30 seconds, or right away
|
||||
on reload. Traffic counted in the meantime is kept on top of your value. Do not
|
||||
edit `period`.
|
||||
|
||||
Notes:
|
||||
|
||||
- The file is the only record of usage, so it survives restarts. With Docker,
|
||||
keep `/var/lib/nipovpn` on a volume (the compose file does).
|
||||
- If the file cannot be parsed, the server logs an error and stops saving until
|
||||
you fix it, rather than overwriting your edit.
|
||||
- A user who is removed and later added back keeps their usage for the period.
|
||||
- Usage is not tracked on a server without a `server.users` list.
|
||||
|
||||
## Reloading the configuration
|
||||
|
||||
Send `SIGHUP` to apply config changes without dropping other users' connections:
|
||||
|
||||
```bash
|
||||
sudo systemctl reload nipovpn-server.service # or nipovpn-agent.service
|
||||
docker kill -s HUP nipovpn # Docker
|
||||
kill -HUP "$(pidof nipovpn)" # anything else
|
||||
```
|
||||
|
||||
The file is validated first. If it is invalid, the running configuration is
|
||||
kept and the error is logged at `ERROR` level, so a typo never takes the server
|
||||
down. A successful reload logs a summary, for example:
|
||||
|
||||
```
|
||||
[Runner reload] config reloaded; 2 of 3 users enabled; access revoked for: bob
|
||||
[Runner reload] closed 1 connections and 0 tunnel sessions of revoked users
|
||||
```
|
||||
|
||||
New requests use the new settings at once. These settings only change on
|
||||
restart: `listenIp`, `listenPort`, `threads`, `tlsEnable` and `server.usage.file`. If you change
|
||||
them, the reload logs `... changed but needs a restart`. Certificate files are
|
||||
read for every new connection, so a renewed certificate needs no reload at
|
||||
all. Reload is not available on Windows.
|
||||
|
||||
## Dashboard
|
||||
|
||||
[NipoVPN Dashboard](https://github.com/MortezaBashsiz/nipovpn-dashboard) is a
|
||||
separate web dashboard that runs beside the server. It adds, edits, disables
|
||||
and deletes users, changes server settings, shows usage and activity, and shares
|
||||
agent configs and `nipovpn://` links with QR codes. It works by editing
|
||||
`config.yaml` and reloading the server, so it needs nothing from the server
|
||||
beyond what is described above. It has its own Debian package,
|
||||
`nipovpn-dashboard`; see its README for setup.
|
||||
|
||||
## Security notes
|
||||
|
||||
@@ -307,8 +512,12 @@ Log lines look like:
|
||||
|
||||
```
|
||||
2026-01-01_12:00:00 [AGENT] [INFO] [<session-uuid>] [CONNECT] [SRC 127.0.0.1:51234] [ORIGIN example.com:443]
|
||||
2026-01-01_12:00:00 [SERVER] [INFO] [<session-uuid>] [CONNECT] [SRC 203.0.113.7:40112] [USER alice] [ORIGIN example.com:443]
|
||||
```
|
||||
|
||||
On the server, `[USER ...]` is the user from the `server.users` list, or `default`
|
||||
when the server still uses the deprecated `general.token`.
|
||||
|
||||
- `INFO`: startup, effective configuration (token hidden), connections opened.
|
||||
- `TRACE`: adds the destination of every forwarded request.
|
||||
- `DEBUG`: adds handshake, encryption and byte-level details. Use only for
|
||||
@@ -324,12 +533,42 @@ journalctl -u nipovpn-server.service -f
|
||||
| Symptom | Likely cause |
|
||||
|---|---|
|
||||
| `Configuration validation failed: ...` | A required key is missing or invalid; the message names the block. |
|
||||
| `token must be at least 32 bytes when aesEnable is true` | Use a longer token (`openssl rand -hex 16`). |
|
||||
| `agent.token must be at least 32 bytes` | Use a longer token (`openssl rand -hex 16`). |
|
||||
| `Error opening log file` | Create the log directory and file (see Quick start). |
|
||||
| Server logs `Decryption Failed` / `Invalid Envelope` | `token`, `aesEnable` or NipoVPN versions differ between agent and server. |
|
||||
| Server logs `Decryption Failed` / `Invalid Envelope` | `token`, `aesEnable` or NipoVPN versions differ between agent and server. With `server.users`: the agent's token is not an enabled user's token. |
|
||||
| `agent.token is required` | Set the agent's token in the `agent` block (it used to be `general.token`). |
|
||||
| `the server needs a server.users list with at least one user` | Add a `users` list under `server` in the server config. |
|
||||
| `users belongs under the server block` | Configs from before this change had `users`/`usage` at the top level; indent them under `server:`. |
|
||||
| `[WARNING] general.token is deprecated` | Move the token to `agent.token` (agent) or a `server.users` entry (server). |
|
||||
| `[WARNING] these settings moved out of general: ...` | Move the listed keys from `general` to the block the warning names (`agent` or `server`). |
|
||||
| `limit must be a size with a unit` | Write the limit with a unit: `2GB`, `500MB`, `1.5GiB`, or `1024B` for bytes. |
|
||||
| `[Usage] cannot read .../usage.yaml` | The usage file has a syntax error, probably from a manual edit. Fix it; usage is not saved until then. |
|
||||
| `[Usage] cannot save usage` | The server cannot write `server.usage.file`; check the directory and permissions. |
|
||||
| `[Runner reload] config not reloaded: ...` | The edited file is invalid; the old configuration is still running. Fix the file and reload again. |
|
||||
| Agent logs `[Tunnel closed] recv refused or failed` | The server rejected the agent's token (e.g. the user was disabled) or became unreachable. |
|
||||
| Agent logs `[TLS] [ERROR]` | `tlsEnable` differs between the two sides, or the certificate/key path is wrong. |
|
||||
| `[CONNECT] [ERROR] [To Server]` | Agent cannot reach `serverIp:serverPort` (firewall, wrong address, server not running). |
|
||||
|
||||
## Tests
|
||||
|
||||
[tests/e2e.py](tests/e2e.py) runs end-to-end tests: for each test it starts a real
|
||||
server and agent on localhost, sends traffic through them with `curl`, and checks
|
||||
every byte with SHA-256. It covers every combination of `tlsEnable`,
|
||||
`tunnelEnable`, `connectionReuse`, `aesEnable` and `protocol`, plus multiple users,
|
||||
unknown and disabled users, reload, usage limits, the 1.1.x config layout and
|
||||
config validation. Every test config is built from the sample `config.yaml`.
|
||||
|
||||
```bash
|
||||
cmake -S . -B build && cmake --build build -j
|
||||
python3 tests/e2e.py --binary build/core/nipovpn # all tests
|
||||
python3 tests/e2e.py --binary build/core/nipovpn -k reload # names containing "reload"
|
||||
python3 tests/e2e.py --list
|
||||
```
|
||||
|
||||
It needs Python 3 with PyYAML, `curl` and `openssl`. GitHub Actions runs it on every
|
||||
push and pull request ([.github/workflows/test.yml](.github/workflows/test.yml)),
|
||||
once on a release build and once with AddressSanitizer and UndefinedBehaviorSanitizer.
|
||||
|
||||
## Contribution
|
||||
|
||||
See the [contribution guide](CONTRIBUTING.md). In short: branch from `dev`,
|
||||
@@ -339,3 +578,4 @@ format with `scripts/format.sh`, build and test, and open a pull request against
|
||||
## License
|
||||
|
||||
NipoVPN is released under the [GNU General Public License v3.0](LICENSE).
|
||||
|
||||
@@ -12,6 +12,7 @@ set(CORE_TARGET_HEADERS
|
||||
src/tcpclient.hpp
|
||||
src/tcpconnection.hpp
|
||||
src/tcpserver.hpp
|
||||
src/usage.hpp
|
||||
)
|
||||
|
||||
set(CORE_TARGET_SOURCES
|
||||
@@ -24,6 +25,7 @@ set(CORE_TARGET_SOURCES
|
||||
src/tcpclient.cpp
|
||||
src/tcpconnection.cpp
|
||||
src/tcpserver.cpp
|
||||
src/usage.cpp
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -83,8 +83,8 @@ void AgentHandler::handle() {
|
||||
const std::string payload =
|
||||
makeEnvelope(action, to_string(uuid_), hexStreambufToStr(readBuffer_));
|
||||
encryption = config_->general().aesEnable
|
||||
? aes256Encrypt(payload, config_->general().token)
|
||||
: BoolStr{true, payload};
|
||||
? aes256Encrypt(payload, config_->agent().token)
|
||||
: BoolStr{true, signWithKey(payload, deriveAesKey(config_->agent().token))};
|
||||
if (!encryption.ok) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Encryption Failed] : [ " +
|
||||
encryption.message + "] ",
|
||||
@@ -107,7 +107,7 @@ void AgentHandler::handle() {
|
||||
<< "Content-Type: text/plain; charset=utf-8\r\n"
|
||||
<< "Content-Length: " << innerRequest.size() << "\r\n"
|
||||
<< "Connection: "
|
||||
<< ((config_->general().connectionReuse || directTunnelOpen) ? "keep-alive" : "close")
|
||||
<< ((config_->agent().connectionReuse || directTunnelOpen) ? "keep-alive" : "close")
|
||||
<< "\r\n"
|
||||
<< "\r\n"
|
||||
<< innerRequest;
|
||||
@@ -117,7 +117,7 @@ void AgentHandler::handle() {
|
||||
client_->doWrite(readBuffer_);
|
||||
client_->doReadAgent();
|
||||
|
||||
if (client_->readBuffer().size() == 0 && !config_->general().connectionReuse) {
|
||||
if (client_->readBuffer().size() == 0 && !config_->agent().connectionReuse) {
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
@@ -140,7 +140,7 @@ void AgentHandler::handle() {
|
||||
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
decryption = config_->general().aesEnable
|
||||
? aes256Decrypt(responseBody, config_->general().token)
|
||||
? aes256Decrypt(responseBody, config_->agent().token)
|
||||
: BoolStr{true, responseBody};
|
||||
if (!decryption.ok) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Failed] : [ " +
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
#include "log.hpp"
|
||||
#include "tcpclient.hpp"
|
||||
|
||||
|
||||
class AgentHandler : private Uncopyable {
|
||||
public:
|
||||
using pointer = std::shared_ptr<AgentHandler>;
|
||||
|
||||
+242
-113
@@ -1,126 +1,219 @@
|
||||
#include "config.hpp"
|
||||
|
||||
namespace {
|
||||
std::string trimNewlines(std::string s) {
|
||||
while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) s.pop_back();
|
||||
return s;
|
||||
}
|
||||
}// namespace
|
||||
|
||||
std::unique_ptr<Config::Settings> Config::load(RunMode mode, const std::string &filePath) {
|
||||
const YAML::Node yaml = YAML::LoadFile(filePath);
|
||||
auto s = std::make_unique<Settings>();
|
||||
|
||||
const std::string legacyToken = yaml["general"]["token"].as<std::string>("");
|
||||
|
||||
std::vector<std::string> deprecated;
|
||||
auto setting = [&](const char *block, const char *key) {
|
||||
if ((mode == RunMode::agent) == (std::string(block) == "agent") &&
|
||||
isDeprecatedSetting(yaml, block, key)) {
|
||||
deprecated.push_back(key);
|
||||
}
|
||||
return movedSetting(yaml, block, key);
|
||||
};
|
||||
|
||||
s->general = {yaml["general"]["timeout"].as<unsigned short>(10),
|
||||
yaml["general"]["tunnelEnable"].as<bool>(false),
|
||||
yaml["general"]["aesEnable"].as<bool>(true),
|
||||
yaml["general"]["tlsEnable"].as<bool>(false)};
|
||||
s->log = {yaml["log"]["logLevel"].as<std::string>("INFO"),
|
||||
yaml["log"]["logFile"].as<std::string>()};
|
||||
s->server = {yaml["server"]["threads"].as<unsigned short>(2),
|
||||
yaml["server"]["listenIp"].as<std::string>("127.0.0.1"),
|
||||
yaml["server"]["listenPort"].as<unsigned short>(8080),
|
||||
setting("server", "bufferSize").as<unsigned int>(65536),
|
||||
setting("server", "tlsCertFile").as<std::string>(""),
|
||||
setting("server", "tlsKeyFile").as<std::string>("")};
|
||||
s->agent = {yaml["agent"]["threads"].as<unsigned short>(2),
|
||||
yaml["agent"]["listenIp"].as<std::string>("127.0.0.1"),
|
||||
yaml["agent"]["listenPort"].as<unsigned short>(8080),
|
||||
yaml["agent"]["serverIp"].as<std::string>("127.0.0.1"),
|
||||
yaml["agent"]["serverPort"].as<unsigned short>(8080),
|
||||
yaml["agent"]["httpVersion"].as<std::string>("1.1"),
|
||||
yaml["agent"]["userAgent"].as<std::string>("NipoAgent"),
|
||||
yaml["agent"]["token"].as<std::string>(""),
|
||||
setting("agent", "protocol").as<std::string>(""),
|
||||
setting("agent", "fakeUrls").as<std::vector<std::string>>(std::vector<std::string>{}),
|
||||
setting("agent", "methods").as<std::vector<std::string>>(std::vector<std::string>{}),
|
||||
setting("agent", "endPoints").as<std::vector<std::string>>(std::vector<std::string>{}),
|
||||
setting("agent", "pullTimeout").as<unsigned short>(1),
|
||||
setting("agent", "connectionReuse").as<bool>(false),
|
||||
setting("agent", "tlsVerifyPeer").as<bool>(false),
|
||||
setting("agent", "tlsCaFile").as<std::string>("")};
|
||||
|
||||
if (!deprecated.empty()) {
|
||||
std::string keys;
|
||||
for (const auto &key: deprecated) keys += (keys.empty() ? "" : ", ") + key;
|
||||
s->warnings.push_back("these settings moved out of general: " + keys + "; move them to the " +
|
||||
(mode == RunMode::agent ? "agent" : "server") + " block");
|
||||
}
|
||||
|
||||
if (mode == RunMode::agent && s->agent.token.empty() && !legacyToken.empty()) {
|
||||
s->agent.token = legacyToken;
|
||||
s->warnings.push_back("general.token is deprecated; move it to agent.token");
|
||||
}
|
||||
|
||||
if (mode == RunMode::server) {
|
||||
const YAML::Node usage = yaml["server"]["usage"];
|
||||
s->usageFile = usage ? usage["file"].as<std::string>("/var/lib/nipovpn/usage.yaml")
|
||||
: "/var/lib/nipovpn/usage.yaml";
|
||||
s->usageResetDay = usage ? usage["resetDay"].as<int>(1) : 1;
|
||||
|
||||
const YAML::Node users = yaml["server"]["users"];
|
||||
if (users && users.IsSequence()) {
|
||||
s->usersFromFile = true;
|
||||
for (const auto &u: users) {
|
||||
const std::string token = u["token"].as<std::string>();
|
||||
std::uint64_t limit = 0;
|
||||
if (u["limit"]) parseByteSize(u["limit"].as<std::string>(), limit);
|
||||
s->users.push_back({u["name"].as<std::string>(), token, deriveAesKey(token),
|
||||
u["enabled"].as<bool>(true), limit});
|
||||
}
|
||||
} else {
|
||||
s->users.push_back({"default", legacyToken, deriveAesKey(legacyToken), true});
|
||||
if (!legacyToken.empty()) {
|
||||
s->warnings.push_back(
|
||||
"general.token is deprecated on the server; "
|
||||
"put the token in a server.users list instead");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
Config::Config(RunMode mode, const std::string &filePath)
|
||||
: runMode_(mode),
|
||||
filePath_(filePath),
|
||||
configYaml_(YAML::LoadFile(filePath)),
|
||||
threads_(0),
|
||||
listenIp_("127.0.0.1"),
|
||||
listenPort_(0),
|
||||
general_({configYaml_["general"]["token"].as<std::string>(),
|
||||
configYaml_["general"]["protocol"].as<std::string>(""),
|
||||
configYaml_["general"]["bufferSize"].as<unsigned int>(65536),
|
||||
configYaml_["general"]["fakeUrls"].as<std::vector<std::string>>(),
|
||||
configYaml_["general"]["methods"].as<std::vector<std::string>>(),
|
||||
configYaml_["general"]["endPoints"].as<std::vector<std::string>>(),
|
||||
configYaml_["general"]["timeout"].as<unsigned short>(10),
|
||||
configYaml_["general"]["pullTimeout"].as<unsigned short>(1),
|
||||
configYaml_["general"]["tunnelEnable"].as<bool>(false),
|
||||
configYaml_["general"]["connectionReuse"].as<bool>(false),
|
||||
configYaml_["general"]["aesEnable"].as<bool>(true),
|
||||
configYaml_["general"]["tlsEnable"].as<bool>(false),
|
||||
configYaml_["general"]["tlsVerifyPeer"].as<bool>(false),
|
||||
configYaml_["general"]["tlsCertFile"].as<std::string>(""),
|
||||
configYaml_["general"]["tlsKeyFile"].as<std::string>(""),
|
||||
configYaml_["general"]["tlsCaFile"].as<std::string>("")}),
|
||||
log_({configYaml_["log"]["logLevel"].as<std::string>("INFO"),
|
||||
configYaml_["log"]["logFile"].as<std::string>()}),
|
||||
server_({configYaml_["server"]["threads"].as<unsigned short>(2),
|
||||
configYaml_["server"]["listenIp"].as<std::string>("127.0.0.1"),
|
||||
configYaml_["server"]["listenPort"].as<unsigned short>(8080)}),
|
||||
agent_({configYaml_["agent"]["threads"].as<unsigned short>(2),
|
||||
configYaml_["agent"]["listenIp"].as<std::string>("127.0.0.1"),
|
||||
configYaml_["agent"]["listenPort"].as<unsigned short>(8080),
|
||||
configYaml_["agent"]["serverIp"].as<std::string>("127.0.0.1"),
|
||||
configYaml_["agent"]["serverPort"].as<unsigned short>(8080),
|
||||
configYaml_["agent"]["httpVersion"].as<std::string>("1.1"),
|
||||
configYaml_["agent"]["userAgent"].as<std::string>("NipoAgent")}) {
|
||||
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
listenPort_(0) {
|
||||
publish(load(mode, filePath));
|
||||
|
||||
const Settings &s = current();
|
||||
switch (runMode_) {
|
||||
case RunMode::server:
|
||||
threads_ = server_.threads;
|
||||
listenIp_ = server_.listenIp;
|
||||
listenPort_ = server_.listenPort;
|
||||
threads_ = s.server.threads;
|
||||
listenIp_ = s.server.listenIp;
|
||||
listenPort_ = s.server.listenPort;
|
||||
break;
|
||||
|
||||
case RunMode::agent:
|
||||
threads_ = agent_.threads;
|
||||
listenIp_ = agent_.listenIp;
|
||||
listenPort_ = agent_.listenPort;
|
||||
threads_ = s.agent.threads;
|
||||
listenIp_ = s.agent.listenIp;
|
||||
listenPort_ = s.agent.listenPort;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Config::Config(const Config::pointer &config)
|
||||
: runMode_(config->runMode()),
|
||||
filePath_(config->filePath()),
|
||||
configYaml_(YAML::LoadFile(config->filePath())),
|
||||
threads_(config->threads()),
|
||||
listenIp_(config->listenIp()),
|
||||
listenPort_(config->listenPort()),
|
||||
general_(config->general()),
|
||||
log_(config->log()),
|
||||
server_(config->server()),
|
||||
agent_(config->agent()) {}
|
||||
|
||||
Config::~Config() = default;
|
||||
|
||||
const Config::Settings &Config::current() const {
|
||||
return *current_.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
void Config::publish(std::unique_ptr<Settings> settings) {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
snapshots_.push_back(std::move(settings));
|
||||
current_.store(snapshots_.back().get(), std::memory_order_release);
|
||||
}
|
||||
|
||||
Config::ReloadResult Config::reload() {
|
||||
std::lock_guard<std::mutex> lock(reloadMutex_);
|
||||
|
||||
const BoolStr valid = validateConfigFile(modeToString(), filePath_);
|
||||
if (!valid.ok) {
|
||||
return {false, "config not reloaded: " + trimNewlines(valid.message), {}};
|
||||
}
|
||||
|
||||
std::unique_ptr<Settings> next;
|
||||
try {
|
||||
next = load(runMode_, filePath_);
|
||||
} catch (const std::exception &e) {
|
||||
return {false, std::string("config not reloaded: ") + e.what(), {}};
|
||||
}
|
||||
|
||||
const Settings &prev = current();
|
||||
std::vector<std::string> notes;
|
||||
|
||||
auto keep = [¬es](auto &field, const auto &old, const char *name) {
|
||||
if (field != old) {
|
||||
notes.push_back(std::string(name) + " changed but needs a restart");
|
||||
field = old;
|
||||
}
|
||||
};
|
||||
if (runMode_ == RunMode::server) {
|
||||
keep(next->server.listenIp, prev.server.listenIp, "server.listenIp");
|
||||
keep(next->server.listenPort, prev.server.listenPort, "server.listenPort");
|
||||
keep(next->server.threads, prev.server.threads, "server.threads");
|
||||
} else {
|
||||
keep(next->agent.listenIp, prev.agent.listenIp, "agent.listenIp");
|
||||
keep(next->agent.listenPort, prev.agent.listenPort, "agent.listenPort");
|
||||
keep(next->agent.threads, prev.agent.threads, "agent.threads");
|
||||
}
|
||||
keep(next->usageFile, prev.usageFile, "server.usage.file");
|
||||
keep(next->general.tlsEnable, prev.general.tlsEnable, "general.tlsEnable");
|
||||
|
||||
std::vector<std::string> revoked;
|
||||
for (const auto &old: prev.users) {
|
||||
if (!old.enabled) continue;
|
||||
bool stillValid = false;
|
||||
for (const auto &u: next->users) {
|
||||
if (u.name == old.name) {
|
||||
stillValid = u.enabled && u.token == old.token;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!stillValid) revoked.push_back(old.name);
|
||||
}
|
||||
|
||||
std::size_t enabled = 0;
|
||||
for (const auto &u: next->users) {
|
||||
if (u.enabled) ++enabled;
|
||||
}
|
||||
|
||||
std::string message = "config reloaded";
|
||||
if (runMode_ == RunMode::server) {
|
||||
message += "; " + std::to_string(enabled) + " of " +
|
||||
std::to_string(next->users.size()) + " users enabled";
|
||||
if (!revoked.empty()) {
|
||||
message += "; access revoked for:";
|
||||
for (const auto &name: revoked) message += " " + name;
|
||||
}
|
||||
}
|
||||
for (const auto ¬e: notes) message += "; " + note;
|
||||
|
||||
publish(std::move(next));
|
||||
return {true, message, revoked};
|
||||
}
|
||||
|
||||
std::string Config::toString() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
|
||||
const Settings &cur = current();
|
||||
const General &general_ = cur.general;
|
||||
const Log &log_ = cur.log;
|
||||
const Server &server_ = cur.server;
|
||||
const Agent &agent_ = cur.agent;
|
||||
|
||||
std::stringstream ss;
|
||||
|
||||
ss << "\nConfig :\n"
|
||||
<< " General :\n"
|
||||
<< " token: " << (general_.token.empty() ? "" : "<hidden>") << "\n"
|
||||
<< " protocol: " << general_.protocol << "\n"
|
||||
<< " bufferSize: " << general_.bufferSize << "\n"
|
||||
<< " fakeUrls: ";
|
||||
|
||||
for (std::size_t i = 0; i < general_.fakeUrls.size(); ++i) {
|
||||
ss << general_.fakeUrls[i];
|
||||
|
||||
if (i != general_.fakeUrls.size() - 1) {
|
||||
ss << ", ";
|
||||
}
|
||||
}
|
||||
|
||||
ss << "\n"
|
||||
<< " methods: ";
|
||||
|
||||
for (std::size_t i = 0; i < general_.methods.size(); ++i) {
|
||||
ss << general_.methods[i];
|
||||
|
||||
if (i != general_.methods.size() - 1) {
|
||||
ss << ", ";
|
||||
}
|
||||
}
|
||||
|
||||
ss << "\n"
|
||||
<< " endPoints: ";
|
||||
|
||||
for (std::size_t i = 0; i < general_.endPoints.size(); ++i) {
|
||||
ss << general_.endPoints[i];
|
||||
|
||||
if (i != general_.endPoints.size() - 1) {
|
||||
ss << ", ";
|
||||
}
|
||||
}
|
||||
|
||||
ss << "\n"
|
||||
<< " timeout: " << general_.timeout << "\n"
|
||||
<< " pullTimeout: " << general_.pullTimeout << "\n"
|
||||
<< " tunnelEnable: " << std::boolalpha << general_.tunnelEnable << "\n"
|
||||
<< " connectionReuse: " << std::boolalpha << general_.connectionReuse << "\n"
|
||||
<< " aesEnable: " << std::boolalpha << general_.aesEnable << "\n"
|
||||
<< " tlsEnable: " << std::boolalpha << general_.tlsEnable << "\n"
|
||||
<< " tlsVerifyPeer: " << std::boolalpha << general_.tlsVerifyPeer << "\n"
|
||||
<< " tlsCertFile: " << general_.tlsCertFile << "\n"
|
||||
<< " tlsKeyFile: " << general_.tlsKeyFile << "\n"
|
||||
<< " tlsCaFile: " << general_.tlsCaFile << "\n"
|
||||
|
||||
<< " Log :\n"
|
||||
<< " logLevel: " << log_.level << "\n"
|
||||
@@ -130,6 +223,9 @@ std::string Config::toString() const {
|
||||
<< " threads: " << server_.threads << "\n"
|
||||
<< " listenIp: " << server_.listenIp << "\n"
|
||||
<< " listenPort: " << server_.listenPort << "\n"
|
||||
<< " bufferSize: " << server_.bufferSize << "\n"
|
||||
<< " tlsCertFile: " << server_.tlsCertFile << "\n"
|
||||
<< " tlsKeyFile: " << server_.tlsKeyFile << "\n"
|
||||
|
||||
<< " Agent :\n"
|
||||
<< " threads: " << agent_.threads << "\n"
|
||||
@@ -138,29 +234,62 @@ std::string Config::toString() const {
|
||||
<< " serverIp: " << agent_.serverIp << "\n"
|
||||
<< " serverPort: " << agent_.serverPort << "\n"
|
||||
<< " httpVersion: " << agent_.httpVersion << "\n"
|
||||
<< " userAgent: " << agent_.userAgent << "\n";
|
||||
<< " userAgent: " << agent_.userAgent << "\n"
|
||||
<< " protocol: " << agent_.protocol << "\n"
|
||||
<< " fakeUrls: " << boost::algorithm::join(agent_.fakeUrls, ", ") << "\n"
|
||||
<< " methods: " << boost::algorithm::join(agent_.methods, ", ") << "\n"
|
||||
<< " endPoints: " << boost::algorithm::join(agent_.endPoints, ", ") << "\n"
|
||||
<< " pullTimeout: " << agent_.pullTimeout << "\n"
|
||||
<< " connectionReuse: " << std::boolalpha << agent_.connectionReuse << "\n"
|
||||
<< " tlsVerifyPeer: " << std::boolalpha << agent_.tlsVerifyPeer << "\n"
|
||||
<< " tlsCaFile: " << agent_.tlsCaFile << "\n"
|
||||
<< " token: " << (agent_.token.empty() ? "" : "<hidden>") << "\n";
|
||||
|
||||
if (runMode_ == RunMode::server && cur.usersFromFile) {
|
||||
ss << " Users :\n";
|
||||
for (const auto &u: cur.users) {
|
||||
ss << " " << u.name << (u.enabled ? "" : " (disabled)")
|
||||
<< (u.limit ? " limit " + formatBytes(u.limit) : std::string()) << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
const Config::General &Config::general() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return general_;
|
||||
return current().general;
|
||||
}
|
||||
|
||||
const Config::Log &Config::log() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return log_;
|
||||
return current().log;
|
||||
}
|
||||
|
||||
const Config::Server &Config::server() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return server_;
|
||||
return current().server;
|
||||
}
|
||||
|
||||
const Config::Agent &Config::agent() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return agent_;
|
||||
return current().agent;
|
||||
}
|
||||
|
||||
const std::vector<User> &Config::users() const {
|
||||
return current().users;
|
||||
}
|
||||
|
||||
const std::vector<std::string> &Config::warnings() const {
|
||||
return current().warnings;
|
||||
}
|
||||
|
||||
bool Config::hasUserList() const {
|
||||
return current().usersFromFile;
|
||||
}
|
||||
|
||||
const std::string &Config::usageFile() const {
|
||||
return current().usageFile;
|
||||
}
|
||||
|
||||
int Config::usageResetDay() const {
|
||||
return current().usageResetDay;
|
||||
}
|
||||
|
||||
unsigned short Config::threads() const {
|
||||
@@ -217,9 +346,9 @@ std::string Config::modeToString() const {
|
||||
}
|
||||
|
||||
std::string Config::randomFakeUrl() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
const Agent &agent_ = current().agent;
|
||||
|
||||
if (general_.fakeUrls.empty()) {
|
||||
if (agent_.fakeUrls.empty()) {
|
||||
return "www.google.com";
|
||||
}
|
||||
|
||||
@@ -227,15 +356,15 @@ std::string Config::randomFakeUrl() const {
|
||||
|
||||
std::uniform_int_distribution<std::size_t> distribution(
|
||||
0,
|
||||
general_.fakeUrls.size() - 1);
|
||||
agent_.fakeUrls.size() - 1);
|
||||
|
||||
return general_.fakeUrls[distribution(generator)];
|
||||
return agent_.fakeUrls[distribution(generator)];
|
||||
}
|
||||
|
||||
std::string Config::randomMethod() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
const Agent &agent_ = current().agent;
|
||||
|
||||
if (general_.methods.empty()) {
|
||||
if (agent_.methods.empty()) {
|
||||
return "GET";
|
||||
}
|
||||
|
||||
@@ -243,15 +372,15 @@ std::string Config::randomMethod() const {
|
||||
|
||||
std::uniform_int_distribution<std::size_t> distribution(
|
||||
0,
|
||||
general_.methods.size() - 1);
|
||||
agent_.methods.size() - 1);
|
||||
|
||||
return general_.methods[distribution(generator)];
|
||||
return agent_.methods[distribution(generator)];
|
||||
}
|
||||
|
||||
std::string Config::randomEndPoint() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
const Agent &agent_ = current().agent;
|
||||
|
||||
if (general_.endPoints.empty()) {
|
||||
if (agent_.endPoints.empty()) {
|
||||
return "api";
|
||||
}
|
||||
|
||||
@@ -259,7 +388,7 @@ std::string Config::randomEndPoint() const {
|
||||
|
||||
std::uniform_int_distribution<std::size_t> distribution(
|
||||
0,
|
||||
general_.endPoints.size() - 1);
|
||||
agent_.endPoints.size() - 1);
|
||||
|
||||
return general_.endPoints[distribution(generator)];
|
||||
return agent_.endPoints[distribution(generator)];
|
||||
}
|
||||
+69
-32
@@ -2,6 +2,8 @@
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <random>
|
||||
@@ -16,25 +18,21 @@ enum class RunMode {
|
||||
agent
|
||||
};
|
||||
|
||||
struct User {
|
||||
std::string name;
|
||||
std::string token;
|
||||
std::string key;
|
||||
bool enabled;
|
||||
std::uint64_t limit = 0;
|
||||
};
|
||||
|
||||
class Config : private Uncopyable {
|
||||
private:
|
||||
public:
|
||||
struct General {
|
||||
std::string token;
|
||||
std::string protocol;
|
||||
unsigned int bufferSize;
|
||||
std::vector<std::string> fakeUrls;
|
||||
std::vector<std::string> methods;
|
||||
std::vector<std::string> endPoints;
|
||||
unsigned short timeout;
|
||||
unsigned short pullTimeout;
|
||||
bool tunnelEnable;
|
||||
bool connectionReuse;
|
||||
bool aesEnable;
|
||||
bool tlsEnable;
|
||||
bool tlsVerifyPeer;
|
||||
std::string tlsCertFile;
|
||||
std::string tlsKeyFile;
|
||||
std::string tlsCaFile;
|
||||
};
|
||||
|
||||
struct Log {
|
||||
@@ -46,6 +44,9 @@ private:
|
||||
unsigned short threads;
|
||||
std::string listenIp;
|
||||
unsigned short listenPort;
|
||||
unsigned int bufferSize;
|
||||
std::string tlsCertFile;
|
||||
std::string tlsKeyFile;
|
||||
};
|
||||
|
||||
struct Agent {
|
||||
@@ -56,40 +57,54 @@ private:
|
||||
unsigned short serverPort;
|
||||
std::string httpVersion;
|
||||
std::string userAgent;
|
||||
std::string token;
|
||||
std::string protocol;
|
||||
std::vector<std::string> fakeUrls;
|
||||
std::vector<std::string> methods;
|
||||
std::vector<std::string> endPoints;
|
||||
unsigned short pullTimeout;
|
||||
bool connectionReuse;
|
||||
bool tlsVerifyPeer;
|
||||
std::string tlsCaFile;
|
||||
};
|
||||
|
||||
RunMode runMode_;
|
||||
std::string filePath_;
|
||||
YAML::Node configYaml_;
|
||||
struct Settings {
|
||||
General general;
|
||||
Log log;
|
||||
Server server;
|
||||
Agent agent;
|
||||
std::vector<User> users;
|
||||
bool usersFromFile = false;
|
||||
std::string usageFile;
|
||||
int usageResetDay = 1;
|
||||
std::vector<std::string> warnings;
|
||||
};
|
||||
|
||||
unsigned short threads_;
|
||||
std::string listenIp_;
|
||||
unsigned short listenPort_;
|
||||
struct ReloadResult {
|
||||
bool ok;
|
||||
std::string message;
|
||||
std::vector<std::string> revokedUsers;
|
||||
};
|
||||
|
||||
mutable std::mutex configMutex_;
|
||||
|
||||
explicit Config(RunMode mode, const std::string &filePath);
|
||||
|
||||
public:
|
||||
using pointer = std::shared_ptr<Config>;
|
||||
|
||||
static pointer create(RunMode mode, const std::string &filePath) {
|
||||
return pointer(new Config(mode, filePath));
|
||||
}
|
||||
|
||||
const General general_;
|
||||
const Log log_;
|
||||
const Server server_;
|
||||
const Agent agent_;
|
||||
|
||||
explicit Config(const Config::pointer &config);
|
||||
|
||||
~Config();
|
||||
|
||||
const General &general() const;
|
||||
const Log &log() const;
|
||||
const Server &server() const;
|
||||
const Agent &agent() const;
|
||||
const std::vector<User> &users() const;
|
||||
const std::vector<std::string> &warnings() const;
|
||||
bool hasUserList() const;
|
||||
const std::string &usageFile() const;
|
||||
int usageResetDay() const;
|
||||
|
||||
ReloadResult reload();
|
||||
|
||||
unsigned short threads() const;
|
||||
|
||||
@@ -116,4 +131,26 @@ public:
|
||||
std::string randomMethod() const;
|
||||
|
||||
std::string randomEndPoint() const;
|
||||
};
|
||||
|
||||
private:
|
||||
explicit Config(RunMode mode, const std::string &filePath);
|
||||
|
||||
static std::unique_ptr<Settings> load(RunMode mode, const std::string &filePath);
|
||||
|
||||
const Settings ¤t() const;
|
||||
|
||||
void publish(std::unique_ptr<Settings> settings);
|
||||
|
||||
RunMode runMode_;
|
||||
std::string filePath_;
|
||||
|
||||
unsigned short threads_;
|
||||
std::string listenIp_;
|
||||
unsigned short listenPort_;
|
||||
|
||||
mutable std::mutex configMutex_;
|
||||
|
||||
std::atomic<const Settings *> current_{nullptr};
|
||||
std::vector<std::unique_ptr<const Settings>> snapshots_;
|
||||
std::mutex reloadMutex_;
|
||||
};
|
||||
+289
-35
@@ -1,8 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#include <openssl/conf.h>
|
||||
#include <openssl/crypto.h>
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/hmac.h>
|
||||
#include <openssl/rand.h>
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
@@ -14,6 +16,7 @@
|
||||
#include <boost/uuid/uuid.hpp>
|
||||
#include <boost/uuid/uuid_generators.hpp>
|
||||
#include <boost/uuid/uuid_io.hpp>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <fstream>
|
||||
@@ -196,12 +199,10 @@ inline std::string deriveAesKey(const std::string &token) {
|
||||
return std::string(reinterpret_cast<char *>(digest), digestLen);
|
||||
}
|
||||
|
||||
inline BoolStr aes256Encrypt(const std::string &plaintext,
|
||||
const std::string &token) {
|
||||
inline BoolStr aes256EncryptWithKey(const std::string &plaintext,
|
||||
const std::string &key) {
|
||||
BoolStr result{false, "Encryption failed"};
|
||||
|
||||
const std::string key = deriveAesKey(token);
|
||||
|
||||
unsigned char nonce[AesGcmNonceLength];
|
||||
if (!RAND_bytes(nonce, sizeof(nonce))) {
|
||||
result.message = "Nonce generation failed";
|
||||
@@ -257,8 +258,8 @@ inline BoolStr aes256Encrypt(const std::string &plaintext,
|
||||
return result;
|
||||
}
|
||||
|
||||
inline BoolStr aes256Decrypt(const std::string &sealed,
|
||||
const std::string &token) {
|
||||
inline BoolStr aes256DecryptWithKey(const std::string &sealed,
|
||||
const std::string &key) {
|
||||
BoolStr result{false, "Decryption failed"};
|
||||
|
||||
if (sealed.size() < AesGcmNonceLength + AesGcmTagLength) {
|
||||
@@ -266,8 +267,6 @@ inline BoolStr aes256Decrypt(const std::string &sealed,
|
||||
return result;
|
||||
}
|
||||
|
||||
const std::string key = deriveAesKey(token);
|
||||
|
||||
const auto *nonce = reinterpret_cast<const unsigned char *>(sealed.data());
|
||||
const auto *ciphertext = nonce + AesGcmNonceLength;
|
||||
const std::size_t ciphertextLen = sealed.size() - AesGcmNonceLength - AesGcmTagLength;
|
||||
@@ -318,6 +317,40 @@ inline BoolStr aes256Decrypt(const std::string &sealed,
|
||||
return result;
|
||||
}
|
||||
|
||||
constexpr std::size_t HmacTagLength = 32;
|
||||
|
||||
inline std::string hmacSha256(const std::string &data, const std::string &key) {
|
||||
unsigned char tag[EVP_MAX_MD_SIZE];
|
||||
unsigned int tagLen = 0;
|
||||
HMAC(EVP_sha256(), key.data(), static_cast<int>(key.size()),
|
||||
reinterpret_cast<const unsigned char *>(data.data()), data.size(), tag, &tagLen);
|
||||
return std::string(reinterpret_cast<char *>(tag), tagLen);
|
||||
}
|
||||
|
||||
inline std::string signWithKey(const std::string &payload, const std::string &key) {
|
||||
return payload + hmacSha256(payload, key);
|
||||
}
|
||||
|
||||
inline BoolStr verifyWithKey(const std::string &signedPayload, const std::string &key) {
|
||||
if (signedPayload.size() < HmacTagLength) return {false, "payload too short for a signature"};
|
||||
const std::string payload = signedPayload.substr(0, signedPayload.size() - HmacTagLength);
|
||||
const std::string tag = hmacSha256(payload, key);
|
||||
if (CRYPTO_memcmp(tag.data(), signedPayload.data() + payload.size(), HmacTagLength) != 0) {
|
||||
return {false, "signature does not match"};
|
||||
}
|
||||
return {true, payload};
|
||||
}
|
||||
|
||||
inline BoolStr aes256Encrypt(const std::string &plaintext,
|
||||
const std::string &token) {
|
||||
return aes256EncryptWithKey(plaintext, deriveAesKey(token));
|
||||
}
|
||||
|
||||
inline BoolStr aes256Decrypt(const std::string &sealed,
|
||||
const std::string &token) {
|
||||
return aes256DecryptWithKey(sealed, deriveAesKey(token));
|
||||
}
|
||||
|
||||
inline std::string makeEnvelope(const std::string &action,
|
||||
const std::string &session,
|
||||
const std::string &data) {
|
||||
@@ -343,30 +376,105 @@ inline bool parseEnvelope(const std::string &raw, Envelope &out) {
|
||||
return true;
|
||||
}
|
||||
|
||||
inline BoolStr validateConfig(int argc, const char *argv[]) {
|
||||
inline bool parseByteSize(const std::string &text, std::uint64_t &out) {
|
||||
std::size_t i = 0;
|
||||
while (i < text.size() && text[i] == ' ') ++i;
|
||||
const std::size_t numStart = i;
|
||||
bool dot = false;
|
||||
while (i < text.size() && ((text[i] >= '0' && text[i] <= '9') || (text[i] == '.' && !dot))) {
|
||||
if (text[i] == '.') dot = true;
|
||||
++i;
|
||||
}
|
||||
if (i == numStart) return false;
|
||||
double value = 0;
|
||||
try {
|
||||
value = std::stod(text.substr(numStart, i - numStart));
|
||||
} catch (const std::exception &) {
|
||||
return false;
|
||||
}
|
||||
while (i < text.size() && text[i] == ' ') ++i;
|
||||
std::string unit = text.substr(i);
|
||||
while (!unit.empty() && unit.back() == ' ') unit.pop_back();
|
||||
for (auto &c: unit) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
|
||||
|
||||
double multiplier = 0;
|
||||
if (unit == "b") multiplier = 1;
|
||||
else if (unit == "kb")
|
||||
multiplier = 1e3;
|
||||
else if (unit == "mb")
|
||||
multiplier = 1e6;
|
||||
else if (unit == "gb")
|
||||
multiplier = 1e9;
|
||||
else if (unit == "tb")
|
||||
multiplier = 1e12;
|
||||
else if (unit == "kib")
|
||||
multiplier = 1024.0;
|
||||
else if (unit == "mib")
|
||||
multiplier = 1024.0 * 1024;
|
||||
else if (unit == "gib")
|
||||
multiplier = 1024.0 * 1024 * 1024;
|
||||
else if (unit == "tib")
|
||||
multiplier = 1024.0 * 1024 * 1024 * 1024;
|
||||
else
|
||||
return false;
|
||||
|
||||
const double bytes = value * multiplier;
|
||||
if (bytes < 1 || bytes > 1.8e19) return false;
|
||||
out = static_cast<std::uint64_t>(bytes);
|
||||
return true;
|
||||
}
|
||||
|
||||
inline std::string formatBytes(std::uint64_t bytes) {
|
||||
const char *units[] = {"B", "KB", "MB", "GB", "TB", "PB"};
|
||||
double value = static_cast<double>(bytes);
|
||||
int unit = 0;
|
||||
while (value >= 1000 && unit < 5) {
|
||||
value /= 1000;
|
||||
++unit;
|
||||
}
|
||||
std::ostringstream out;
|
||||
if (unit == 0) out << bytes << " B";
|
||||
else
|
||||
out << std::fixed << std::setprecision(2) << value << " " << units[unit];
|
||||
return out.str();
|
||||
}
|
||||
|
||||
inline bool isValidUserName(const std::string &name) {
|
||||
if (name.empty() || name.size() > 64) return false;
|
||||
for (const char c: name) {
|
||||
const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
|
||||
(c >= '0' && c <= '9') || c == '.' || c == '_' ||
|
||||
c == '-' || c == '@';
|
||||
if (!ok) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline YAML::Node movedSetting(const YAML::Node &yaml, const char *block, const char *key) {
|
||||
if (yaml[block][key]) return yaml[block][key];
|
||||
return yaml["general"][key];
|
||||
}
|
||||
|
||||
inline bool isDeprecatedSetting(const YAML::Node &yaml, const char *block, const char *key) {
|
||||
return !yaml[block][key] && yaml["general"][key];
|
||||
}
|
||||
|
||||
inline BoolStr validateConfigFile(const std::string &mode, const std::string &path) {
|
||||
BoolStr result{false, "Validation failed"};
|
||||
|
||||
if (argc != 3) {
|
||||
result.message =
|
||||
"Requires 2 arguments: mode [server|agent] and config file "
|
||||
"path\nExample: nipovpn server config.yaml\n";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (std::string(argv[1]) != "server" && std::string(argv[1]) != "agent") {
|
||||
if (mode != "server" && mode != "agent") {
|
||||
result.message = "First argument must be one of [server|agent]\n";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (!fileExists(argv[2])) {
|
||||
result.message =
|
||||
std::string("Config file ") + argv[2] + " does not exist\n";
|
||||
if (!fileExists(path)) {
|
||||
result.message = "Config file " + path + " does not exist\n";
|
||||
return result;
|
||||
}
|
||||
|
||||
YAML::Node configYaml;
|
||||
try {
|
||||
configYaml = YAML::LoadFile(argv[2]);
|
||||
configYaml = YAML::LoadFile(path);
|
||||
} catch (const std::exception &e) {
|
||||
result.message =
|
||||
std::string("Error parsing config file: ") + e.what() + "\n";
|
||||
@@ -374,14 +482,8 @@ inline BoolStr validateConfig(int argc, const char *argv[]) {
|
||||
}
|
||||
|
||||
try {
|
||||
configYaml["general"]["token"].as<std::string>();
|
||||
configYaml["general"]["protocol"].as<std::string>();
|
||||
configYaml["general"]["bufferSize"].as<unsigned int>();
|
||||
configYaml["general"]["fakeUrls"].as<std::vector<std::string>>();
|
||||
configYaml["general"]["methods"].as<std::vector<std::string>>();
|
||||
configYaml["general"]["endPoints"].as<std::vector<std::string>>();
|
||||
configYaml["general"]["token"].as<std::string>("");
|
||||
configYaml["general"]["timeout"].as<unsigned short>();
|
||||
configYaml["general"]["pullTimeout"].as<unsigned short>();
|
||||
configYaml["general"]["tunnelEnable"].as<bool>();
|
||||
} catch (const std::exception &e) {
|
||||
result.message = std::string("Error in 'general' block: ") + e.what() + "\n";
|
||||
@@ -416,23 +518,175 @@ inline BoolStr validateConfig(int argc, const char *argv[]) {
|
||||
return result;
|
||||
}
|
||||
|
||||
if (configYaml["general"]["protocol"].as<std::string>() != "http" && configYaml["general"]["protocol"].as<std::string>() != "socks5") {
|
||||
result.message = "protocol must be one of [http|socks5]\n";
|
||||
const char *side = mode == "agent" ? "agent" : "server";
|
||||
std::string key;
|
||||
try {
|
||||
auto check = [&](const char *name, auto sample) {
|
||||
key = name;
|
||||
const YAML::Node node = movedSetting(configYaml, side, name);
|
||||
if (node) node.as<decltype(sample)>();
|
||||
};
|
||||
if (mode == "agent") {
|
||||
check("protocol", std::string());
|
||||
check("fakeUrls", std::vector<std::string>());
|
||||
check("methods", std::vector<std::string>());
|
||||
check("endPoints", std::vector<std::string>());
|
||||
check("pullTimeout", static_cast<unsigned short>(0));
|
||||
check("connectionReuse", false);
|
||||
check("tlsVerifyPeer", false);
|
||||
check("tlsCaFile", std::string());
|
||||
} else {
|
||||
check("bufferSize", 0u);
|
||||
check("tlsCertFile", std::string());
|
||||
check("tlsKeyFile", std::string());
|
||||
}
|
||||
} catch (const std::exception &e) {
|
||||
result.message = std::string("Error in ") + side + "." + key + ": " + e.what() + "\n";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (configYaml["general"]["bufferSize"].as<unsigned int>() < 1 || configYaml["general"]["bufferSize"].as<unsigned int>() > 65536) {
|
||||
result.message = "bufferSize must be between 1 and 65536\n";
|
||||
if (mode == "agent") {
|
||||
const std::string protocol = movedSetting(configYaml, "agent", "protocol").as<std::string>("");
|
||||
if (protocol != "http" && protocol != "socks5") {
|
||||
result.message = "agent.protocol must be one of [http|socks5]\n";
|
||||
return result;
|
||||
}
|
||||
} else {
|
||||
const unsigned int bufferSize = movedSetting(configYaml, "server", "bufferSize").as<unsigned int>(65536);
|
||||
if (bufferSize < 1 || bufferSize > 65536) {
|
||||
result.message = "server.bufferSize must be between 1 and 65536\n";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
const std::string logLevel = configYaml["log"]["logLevel"].as<std::string>();
|
||||
if (logLevel != "INFO" && logLevel != "TRACE" && logLevel != "DEBUG") {
|
||||
result.message = "logLevel must be one of [INFO|TRACE|DEBUG]\n";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (configYaml["general"]["aesEnable"].as<bool>(true) &&
|
||||
configYaml["general"]["token"].as<std::string>().size() < MinTokenLength) {
|
||||
result.message = "token must be at least 32 bytes when aesEnable is true\n";
|
||||
const bool aesEnable = configYaml["general"]["aesEnable"].as<bool>(true);
|
||||
|
||||
std::string agentToken;
|
||||
try {
|
||||
agentToken = configYaml["agent"]["token"].as<std::string>("");
|
||||
} catch (const std::exception &e) {
|
||||
result.message = std::string("Error in agent.token: ") + e.what() + "\n";
|
||||
return result;
|
||||
}
|
||||
const std::string legacyToken = configYaml["general"]["token"].as<std::string>("");
|
||||
|
||||
for (const char *block: {"users", "usage"}) {
|
||||
if (configYaml[block]) {
|
||||
result.message = std::string(block) + " belongs under the server block: move it to server." +
|
||||
block + "\n";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
const YAML::Node users = configYaml["server"]["users"];
|
||||
const bool serverUsers = mode == "server" && users && !users.IsNull();
|
||||
|
||||
if (mode == "agent") {
|
||||
const std::string token = agentToken.empty() ? legacyToken : agentToken;
|
||||
if (token.empty()) {
|
||||
result.message = "agent.token is required\n";
|
||||
return result;
|
||||
}
|
||||
if (token.size() < MinTokenLength) {
|
||||
result.message = "agent.token must be at least 32 bytes\n";
|
||||
return result;
|
||||
}
|
||||
} else if (serverUsers) {
|
||||
if (!users.IsSequence()) {
|
||||
result.message = "server.users must be a list\n";
|
||||
return result;
|
||||
}
|
||||
if (users.size() == 0) {
|
||||
result.message = "server.users must have at least one entry\n";
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<std::string> names;
|
||||
std::vector<std::string> tokens;
|
||||
for (std::size_t i = 0; i < users.size(); ++i) {
|
||||
const YAML::Node user = users[i];
|
||||
const std::string where = "server.users[" + std::to_string(i) + "]";
|
||||
std::string name;
|
||||
std::string userToken;
|
||||
try {
|
||||
if (!user.IsMap()) throw std::runtime_error("must be a map with name and token");
|
||||
name = user["name"].as<std::string>();
|
||||
userToken = user["token"].as<std::string>();
|
||||
user["enabled"].as<bool>(true);
|
||||
if (user["limit"]) {
|
||||
std::uint64_t limit = 0;
|
||||
if (!parseByteSize(user["limit"].as<std::string>(), limit)) {
|
||||
throw std::runtime_error(
|
||||
"limit must be a size with a unit, such as 2GB, 500MB or 1.5GiB");
|
||||
}
|
||||
}
|
||||
} catch (const std::exception &e) {
|
||||
result.message = "Error in " + where + ": " + e.what() + "\n";
|
||||
return result;
|
||||
}
|
||||
if (!isValidUserName(name)) {
|
||||
result.message = where + ".name must be 1-64 characters of [A-Za-z0-9._@-]\n";
|
||||
return result;
|
||||
}
|
||||
if (userToken.size() < MinTokenLength) {
|
||||
result.message = "token of user " + name + " must be at least " +
|
||||
std::to_string(MinTokenLength) + " bytes\n";
|
||||
return result;
|
||||
}
|
||||
for (const auto &n: names) {
|
||||
if (n == name) {
|
||||
result.message = "user name " + name + " is used more than once\n";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
for (std::size_t j = 0; j < tokens.size(); ++j) {
|
||||
if (tokens[j] == userToken) {
|
||||
result.message = "users " + names[j] + " and " + name + " have the same token\n";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
names.push_back(name);
|
||||
tokens.push_back(userToken);
|
||||
}
|
||||
if (const YAML::Node usage = configYaml["server"]["usage"]) {
|
||||
try {
|
||||
usage["file"].as<std::string>("");
|
||||
const int resetDay = usage["resetDay"].as<int>(1);
|
||||
if (resetDay < 1 || resetDay > 28) {
|
||||
throw std::runtime_error("resetDay must be between 1 and 28");
|
||||
}
|
||||
} catch (const std::exception &e) {
|
||||
result.message = std::string("Error in server.usage: ") + e.what() + "\n";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
} else if (aesEnable) {
|
||||
if (legacyToken.empty()) {
|
||||
result.message = "the server needs a server.users list with at least one user\n";
|
||||
return result;
|
||||
}
|
||||
if (legacyToken.size() < MinTokenLength) {
|
||||
result.message = "general.token must be at least 32 bytes when aesEnable is true\n";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
result.ok = true;
|
||||
result.message = "OK";
|
||||
return result;
|
||||
}
|
||||
|
||||
inline BoolStr validateConfig(int argc, const char *argv[]) {
|
||||
if (argc != 3) {
|
||||
return {false,
|
||||
"Requires 2 arguments: mode [server|agent] and config file "
|
||||
"path\nExample: nipovpn server config.yaml\n"};
|
||||
}
|
||||
return validateConfigFile(argv[1], argv[2]);
|
||||
}
|
||||
@@ -22,10 +22,8 @@ HTTP::HTTP(const HTTP &http)
|
||||
uuid_(http.uuid_) {
|
||||
}
|
||||
|
||||
|
||||
HTTP::~HTTP() {}
|
||||
|
||||
|
||||
bool HTTP::detectType() {
|
||||
std::string requestStr{hexStreambufToStr(buffer_)};
|
||||
std::string tmpStr;
|
||||
@@ -155,29 +153,6 @@ bool HTTP::parseTls() {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string HTTP::genHttpPostReqString(const std::string &body) const {
|
||||
auto fakeUrl = config_->randomFakeUrl();
|
||||
return std::string(config_->randomMethod() + " " +
|
||||
fakeUrl + " HTTP/" +
|
||||
config_->agent().httpVersion + "\r\n") +
|
||||
"Host: " + fakeUrl + "\r\n" +
|
||||
"User-Agent: " + config_->agent().userAgent + "\r\n" +
|
||||
"Accept: */*\r\n" + "Connection: keep-alive\r\n" +
|
||||
"Content-Length: " + std::to_string(body.length()) + "\r\n" +
|
||||
"Content-Type: application/x-www-form-urlencoded\r\n" + "\r\n" + body + "COMP\r\n\r\n";
|
||||
}
|
||||
|
||||
std::string HTTP::genHttpRestPostReqString() const {
|
||||
auto fakeUrl = config_->randomFakeUrl();
|
||||
return std::string(config_->randomMethod() + " " +
|
||||
fakeUrl + " HTTP/" +
|
||||
config_->agent().httpVersion + "\r\n") +
|
||||
"Host: " + fakeUrl + "\r\n" +
|
||||
"User-Agent: " + config_->agent().userAgent + "\r\n" +
|
||||
"Accept: */*\r\n" + "Connection: keep-alive\r\n" +
|
||||
"Rest: yes\r\n" + "COMP\r\n\r\n";
|
||||
}
|
||||
|
||||
std::string HTTP::genHttpOkResString(const std::string &body) const {
|
||||
return std::string("HTTP/1.1 200 OK\r\n") +
|
||||
"Content-Type: application/x-www-form-urlencoded\r\n" +
|
||||
@@ -186,7 +161,6 @@ std::string HTTP::genHttpOkResString(const std::string &body) const {
|
||||
"Pragma: no-cache\r\n" + "\r\n" + body + "COMP\r\n\r\n";
|
||||
}
|
||||
|
||||
|
||||
bool HTTP::parseHostPort(const std::string &input,
|
||||
std::string &host,
|
||||
unsigned short &port,
|
||||
|
||||
@@ -60,9 +60,6 @@ public:
|
||||
|
||||
bool parseTls();
|
||||
|
||||
std::string genHttpPostReqString(const std::string &body) const;
|
||||
|
||||
std::string genHttpRestPostReqString() const;
|
||||
|
||||
std::string genHttpOkResString(const std::string &body) const;
|
||||
|
||||
|
||||
+22
-10
@@ -14,14 +14,27 @@ Log::Log(const std::shared_ptr<Config> &config)
|
||||
<< ". Make sure the directory and file exist.\n";
|
||||
}
|
||||
|
||||
const auto &logLevel = config_->log().level;
|
||||
applyConfigLevel();
|
||||
}
|
||||
|
||||
if (logLevel == "INFO") {
|
||||
level_ = Level::INFO;
|
||||
} else if (logLevel == "TRACE") {
|
||||
level_ = Level::TRACE;
|
||||
} else if (logLevel == "DEBUG") {
|
||||
level_ = Level::DEBUG;
|
||||
bool Log::parseLevel(const std::string &name, Level &out) {
|
||||
if (name == "INFO") {
|
||||
out = Level::INFO;
|
||||
} else if (name == "TRACE") {
|
||||
out = Level::TRACE;
|
||||
} else if (name == "DEBUG") {
|
||||
out = Level::DEBUG;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void Log::applyConfigLevel() {
|
||||
const std::string logLevel = config_->log().level;
|
||||
Level parsed;
|
||||
if (parseLevel(logLevel, parsed)) {
|
||||
level_.store(parsed);
|
||||
} else {
|
||||
std::cerr << "Invalid log level: " << logLevel
|
||||
<< ". It should be one of [INFO|TRACE|DEBUG].\n";
|
||||
@@ -29,20 +42,19 @@ Log::Log(const std::shared_ptr<Config> &config)
|
||||
}
|
||||
|
||||
Log::Log(const std::shared_ptr<Log> &log)
|
||||
: config_(log->config_), level_(log->level_) {}
|
||||
: config_(log->config_), level_(log->level_.load()) {}
|
||||
|
||||
Log::~Log() {}
|
||||
|
||||
void Log::write(const std::string &message, Level level) const {
|
||||
std::lock_guard<std::mutex> lock(logMutex_);
|
||||
|
||||
if (level <= level_ || level == Level::ERROR) {
|
||||
if (level <= level_.load() || level == Level::ERROR) {
|
||||
|
||||
std::ofstream logFile(config_->log().file, std::ios::out | std::ios::app);
|
||||
|
||||
if (logFile.is_open()) {
|
||||
|
||||
|
||||
auto now = std::time(nullptr);
|
||||
auto localTime = *std::localtime(&now);
|
||||
|
||||
|
||||
+7
-2
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <ctime>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
@@ -31,7 +32,9 @@ public:
|
||||
|
||||
std::shared_ptr<Config> config() const { return config_; }
|
||||
|
||||
Level level() const { return level_; }
|
||||
Level level() const { return level_.load(); }
|
||||
|
||||
void applyConfigLevel();
|
||||
|
||||
void write(const std::string &message, Level level) const;
|
||||
|
||||
@@ -40,8 +43,10 @@ private:
|
||||
|
||||
static std::string levelToString(Level level);
|
||||
|
||||
static bool parseLevel(const std::string &name, Level &out);
|
||||
|
||||
std::shared_ptr<Config> config_;
|
||||
Level level_;
|
||||
std::atomic<Level> level_;
|
||||
std::string mode_;
|
||||
|
||||
mutable std::mutex logMutex_;
|
||||
|
||||
+136
-8
@@ -1,5 +1,7 @@
|
||||
#include "runner.hpp"
|
||||
|
||||
#include "usage.hpp"
|
||||
|
||||
Runner::Runner(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log)
|
||||
: config_(config),
|
||||
@@ -7,7 +9,10 @@ Runner::Runner(const std::shared_ptr<Config> &config,
|
||||
io_context_(),
|
||||
work_guard_(boost::asio::make_work_guard(io_context_)),
|
||||
running_(true),
|
||||
strand_(boost::asio::make_strand(io_context_)) {}
|
||||
strand_(boost::asio::make_strand(io_context_)),
|
||||
signals_(io_context_),
|
||||
stopSignals_(io_context_),
|
||||
usageTimer_(io_context_) {}
|
||||
|
||||
Runner::~Runner() {
|
||||
running_.store(false);
|
||||
@@ -18,6 +23,8 @@ Runner::~Runner() {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
|
||||
ServerHandler::closeAllSessions();
|
||||
}
|
||||
|
||||
void Runner::run() {
|
||||
@@ -25,15 +32,14 @@ void Runner::run() {
|
||||
log_->write("Config initialized in " + config_->modeToString() + " mode", Log::Level::INFO);
|
||||
log_->write(config_->toString(), Log::Level::INFO);
|
||||
|
||||
if (config_->general().aesEnable && config_->general().token == SampleToken) {
|
||||
log_->write(
|
||||
"[WARNING] general.token is the public sample token; "
|
||||
"set a unique random token on both agent and server",
|
||||
Log::Level::ERROR);
|
||||
}
|
||||
warnAboutSampleToken();
|
||||
|
||||
auto tcpServer = TCPServer::create(io_context_, config_, log_);
|
||||
|
||||
waitForReloadSignal();
|
||||
waitForStopSignal();
|
||||
startUsage();
|
||||
|
||||
for (auto i = 0; i < config_->threads(); ++i) {
|
||||
threadPool_.emplace_back([this] { workerThread(); });
|
||||
}
|
||||
@@ -67,4 +73,126 @@ void Runner::workerThread() {
|
||||
void Runner::stop() {
|
||||
running_.store(false);
|
||||
io_context_.stop();
|
||||
}
|
||||
}
|
||||
|
||||
void Runner::warnAboutSampleToken() {
|
||||
for (const auto &warning: config_->warnings()) {
|
||||
log_->write("[WARNING] " + warning, Log::Level::ERROR);
|
||||
}
|
||||
|
||||
if (config_->runMode() == RunMode::agent) {
|
||||
if (config_->agent().token == SampleToken) {
|
||||
log_->write(
|
||||
"[WARNING] agent.token is the public sample token; "
|
||||
"set a unique random token for each user",
|
||||
Log::Level::ERROR);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (const auto &user: config_->users()) {
|
||||
if (user.enabled && user.token == SampleToken) {
|
||||
log_->write("[WARNING] user " + user.name +
|
||||
" uses the public sample token; "
|
||||
"set a unique random token for each user",
|
||||
Log::Level::ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Runner::waitForReloadSignal() {
|
||||
#if defined(SIGHUP)
|
||||
boost::system::error_code ec;
|
||||
signals_.add(SIGHUP, ec);
|
||||
if (ec) {
|
||||
log_->write("[Runner] cannot handle SIGHUP, reload disabled: " + ec.message(),
|
||||
Log::Level::ERROR);
|
||||
return;
|
||||
}
|
||||
|
||||
signals_.async_wait([this](const boost::system::error_code &error, int) {
|
||||
if (error) return;
|
||||
reload();
|
||||
waitForReloadSignal();
|
||||
});
|
||||
#endif
|
||||
}
|
||||
|
||||
void Runner::reload() {
|
||||
log_->write("[Runner reload] reloading " + config_->filePath(), Log::Level::INFO);
|
||||
|
||||
const Config::ReloadResult result = config_->reload();
|
||||
if (!result.ok) {
|
||||
log_->write("[Runner reload] " + result.message, Log::Level::ERROR);
|
||||
return;
|
||||
}
|
||||
|
||||
log_->applyConfigLevel();
|
||||
log_->write("[Runner reload] " + result.message, Log::Level::INFO);
|
||||
warnAboutSampleToken();
|
||||
|
||||
if (config_->runMode() == RunMode::server) {
|
||||
Usage::instance().configure(*config_, nullptr, *log_);
|
||||
Usage::instance().flush(*log_);
|
||||
}
|
||||
|
||||
if (!result.revokedUsers.empty()) {
|
||||
const std::size_t connections = TCPConnection::revokeUsers(result.revokedUsers);
|
||||
const std::size_t sessions = ServerHandler::revokeSessions(result.revokedUsers);
|
||||
log_->write("[Runner reload] closed " + std::to_string(connections) +
|
||||
" connections and " + std::to_string(sessions) +
|
||||
" tunnel sessions of revoked users",
|
||||
Log::Level::INFO);
|
||||
}
|
||||
}
|
||||
|
||||
void Runner::startUsage() {
|
||||
if (config_->runMode() != RunMode::server) return;
|
||||
|
||||
Usage::instance().configure(
|
||||
*config_, [this](const std::string &user) { onUsageLimit(user); }, *log_);
|
||||
if (!config_->hasUserList()) return;
|
||||
|
||||
Usage::instance().flush(*log_);
|
||||
log_->write("[Usage] tracking usage in " + config_->usageFile() + ", period from " +
|
||||
Usage::periodStart(config_->usageResetDay()),
|
||||
Log::Level::INFO);
|
||||
scheduleUsageFlush();
|
||||
}
|
||||
|
||||
void Runner::scheduleUsageFlush() {
|
||||
usageTimer_.expires_after(std::chrono::seconds(30));
|
||||
usageTimer_.async_wait([this](const boost::system::error_code &error) {
|
||||
if (error) return;
|
||||
Usage::instance().flush(*log_);
|
||||
scheduleUsageFlush();
|
||||
});
|
||||
}
|
||||
|
||||
void Runner::onUsageLimit(const std::string &user) {
|
||||
std::string limit;
|
||||
for (const auto &u: config_->users()) {
|
||||
if (u.name == user) limit = formatBytes(u.limit);
|
||||
}
|
||||
log_->write("[Usage] user " + user + " reached their limit of " + limit +
|
||||
"; blocked until the next period",
|
||||
Log::Level::INFO);
|
||||
TCPConnection::revokeUsers({user});
|
||||
ServerHandler::revokeSessions({user});
|
||||
}
|
||||
|
||||
void Runner::waitForStopSignal() {
|
||||
boost::system::error_code ec;
|
||||
stopSignals_.add(SIGINT, ec);
|
||||
stopSignals_.add(SIGTERM, ec);
|
||||
|
||||
stopSignals_.async_wait([this](const boost::system::error_code &error, int signal) {
|
||||
if (error) return;
|
||||
log_->write("[Runner] received signal " + std::to_string(signal) + ", stopping",
|
||||
Log::Level::INFO);
|
||||
if (config_->runMode() == RunMode::server) {
|
||||
Usage::instance().flush(*log_);
|
||||
}
|
||||
stop();
|
||||
});
|
||||
}
|
||||
@@ -3,6 +3,9 @@
|
||||
#include <atomic>
|
||||
#include <boost/asio/executor_work_guard.hpp>
|
||||
#include <boost/asio/io_context.hpp>
|
||||
#include <boost/asio/signal_set.hpp>
|
||||
#include <boost/asio/steady_timer.hpp>
|
||||
#include <csignal>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
@@ -31,6 +34,18 @@ private:
|
||||
|
||||
void stop();
|
||||
|
||||
void reload();
|
||||
|
||||
void waitForReloadSignal();
|
||||
|
||||
void warnAboutSampleToken();
|
||||
|
||||
void startUsage();
|
||||
void scheduleUsageFlush();
|
||||
void onUsageLimit(const std::string &user);
|
||||
|
||||
void waitForStopSignal();
|
||||
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
|
||||
@@ -43,4 +58,8 @@ private:
|
||||
std::vector<runnerThread> threadPool_;
|
||||
|
||||
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
|
||||
|
||||
boost::asio::signal_set signals_;
|
||||
boost::asio::signal_set stopSignals_;
|
||||
boost::asio::steady_timer usageTimer_;
|
||||
};
|
||||
+148
-32
@@ -5,9 +5,41 @@
|
||||
#include <vector>
|
||||
|
||||
#include "http_utils.hpp"
|
||||
#include "usage.hpp"
|
||||
|
||||
std::mutex ServerHandler::sessionsMutex_;
|
||||
std::unordered_map<std::string, TCPClient::pointer> ServerHandler::sessions_;
|
||||
std::unordered_map<std::string, ServerHandler::Session> ServerHandler::sessions_;
|
||||
|
||||
std::size_t ServerHandler::revokeSessions(const std::vector<std::string> &users) {
|
||||
std::lock_guard<std::mutex> lock(sessionsMutex_);
|
||||
std::size_t closed = 0;
|
||||
for (auto it = sessions_.begin(); it != sessions_.end();) {
|
||||
bool revoked = false;
|
||||
for (const auto &name: users) {
|
||||
if (it->second.user == name) {
|
||||
revoked = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (revoked) {
|
||||
it->second.client->socketShutdown();
|
||||
it = sessions_.erase(it);
|
||||
++closed;
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
return closed;
|
||||
}
|
||||
|
||||
void ServerHandler::closeAllSessions() {
|
||||
std::unordered_map<std::string, Session> sessions;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(sessionsMutex_);
|
||||
sessions.swap(sessions_);
|
||||
}
|
||||
for (auto &[key, session]: sessions) session.client->socketShutdown();
|
||||
}
|
||||
|
||||
std::string ServerHandler::HttpUtils::lowerCopy(std::string s) {
|
||||
return http_utils::toLowerCopy(std::move(s));
|
||||
@@ -32,7 +64,8 @@ ServerHandler::ServerHandler(boost::asio::streambuf &readBuffer,
|
||||
const std::shared_ptr<Log> &log,
|
||||
TCPClient::pointer client,
|
||||
std::string clientConnStr,
|
||||
boost::uuids::uuid uuid)
|
||||
boost::uuids::uuid uuid,
|
||||
std::string &userHint)
|
||||
: config_(config),
|
||||
log_(log),
|
||||
client_(std::move(client)),
|
||||
@@ -40,13 +73,70 @@ ServerHandler::ServerHandler(boost::asio::streambuf &readBuffer,
|
||||
writeBuffer_(writeBuffer),
|
||||
request_(HTTP::create(config, log, readBuffer, uuid)),
|
||||
clientConnStr_(std::move(clientConnStr)),
|
||||
uuid_(uuid) {
|
||||
uuid_(uuid),
|
||||
userHint_(userHint) {
|
||||
end_ = false;
|
||||
connect_ = false;
|
||||
}
|
||||
|
||||
BoolStr ServerHandler::authenticate(const std::string &payload) {
|
||||
const std::vector<User> &users = config_->users();
|
||||
|
||||
const bool aes = config_->general().aesEnable;
|
||||
|
||||
BoolStr result{false, "no enabled user's token authenticates the request"};
|
||||
auto tryUser = [&](const User &u) {
|
||||
if (!u.enabled) return false;
|
||||
BoolStr r = aes ? aes256DecryptWithKey(payload, u.key) : verifyWithKey(payload, u.key);
|
||||
if (!r.ok) return false;
|
||||
result = std::move(r);
|
||||
user_ = &u;
|
||||
userHint_ = u.name;
|
||||
return true;
|
||||
};
|
||||
|
||||
if (!userHint_.empty()) {
|
||||
for (const auto &u: users) {
|
||||
if (u.name == userHint_) {
|
||||
if (tryUser(u)) return result;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto &u: users) {
|
||||
if (u.name != userHint_ && tryUser(u)) return result;
|
||||
}
|
||||
|
||||
if (!aes && !config_->hasUserList() && !users.empty()) {
|
||||
user_ = &users.front();
|
||||
return {true, withoutUnverifiedSignature(payload)};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string ServerHandler::withoutUnverifiedSignature(const std::string &payload) {
|
||||
const auto actionEnd = payload.find('\n');
|
||||
const auto sessionEnd = actionEnd == std::string::npos ? actionEnd : payload.find('\n', actionEnd + 1);
|
||||
if (sessionEnd == std::string::npos || payload.size() < sessionEnd + 1 + HmacTagLength) return payload;
|
||||
|
||||
static const char *hex = "0123456789abcdefABCDEF";
|
||||
const std::size_t dataStart = sessionEnd + 1;
|
||||
const std::size_t tagStart = payload.size() - HmacTagLength;
|
||||
if (payload.find_first_not_of(hex, dataStart) == std::string::npos) return payload;
|
||||
if (payload.find_first_not_of(hex, dataStart) < tagStart) return payload;
|
||||
return payload.substr(0, tagStart);
|
||||
}
|
||||
|
||||
std::string ServerHandler::srcTag() const {
|
||||
return clientConnStr_ + (user_ ? "] [USER " + user_->name : std::string());
|
||||
}
|
||||
|
||||
ServerHandler::~ServerHandler() {}
|
||||
|
||||
std::string ServerHandler::connectionHeader() const {
|
||||
return requestKeepAlive_ ? "keep-alive" : "close";
|
||||
}
|
||||
|
||||
void ServerHandler::makePlainHttpResponse(const std::string &body,
|
||||
const std::string &status,
|
||||
const std::string &connection) {
|
||||
@@ -60,6 +150,7 @@ void ServerHandler::makePlainHttpResponse(const std::string &body,
|
||||
<< body;
|
||||
|
||||
copyStringToStreambuf(outer.str(), writeBuffer_);
|
||||
keepAlive_ = connection == "keep-alive";
|
||||
|
||||
end_ = false;
|
||||
connect_ = false;
|
||||
@@ -68,9 +159,12 @@ void ServerHandler::makePlainHttpResponse(const std::string &body,
|
||||
void ServerHandler::makePayloadHttpResponse(const std::string &plainBody,
|
||||
const std::string &status,
|
||||
const std::string &connection) {
|
||||
BoolStr encryption = config_->general().aesEnable
|
||||
? aes256Encrypt(plainBody, config_->general().token)
|
||||
: BoolStr{true, plainBody};
|
||||
BoolStr encryption{false, "no authenticated user to encrypt for"};
|
||||
if (!config_->general().aesEnable) {
|
||||
encryption = {true, plainBody};
|
||||
} else if (user_) {
|
||||
encryption = aes256EncryptWithKey(plainBody, user_->key);
|
||||
}
|
||||
|
||||
if (!encryption.ok) {
|
||||
log_->write("[" + to_string(uuid_) + "] [ServerHandler] [Encryption Failed] " + encryption.message,
|
||||
@@ -98,6 +192,7 @@ void ServerHandler::handle() {
|
||||
}
|
||||
|
||||
const auto &outerReq = request_->parsedHttpRequest();
|
||||
requestKeepAlive_ = outerReq.keep_alive();
|
||||
|
||||
const std::string outerRaw = streambufToString(readBuffer_);
|
||||
|
||||
@@ -110,10 +205,7 @@ void ServerHandler::handle() {
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
|
||||
try {
|
||||
const std::string payload = decode64(requestBody);
|
||||
decryption = config_->general().aesEnable
|
||||
? aes256Decrypt(payload, config_->general().token)
|
||||
: BoolStr{true, payload};
|
||||
decryption = authenticate(decode64(requestBody));
|
||||
} catch (const std::exception &e) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
@@ -135,6 +227,15 @@ void ServerHandler::handle() {
|
||||
return;
|
||||
}
|
||||
|
||||
usage_ = user_ ? Usage::instance().counter(user_->name) : nullptr;
|
||||
if (usage_ && Usage::overLimit(*usage_)) {
|
||||
log_->write("[" + to_string(uuid_) + "] [ServerHandler handle] [USER " + user_->name +
|
||||
"] refused: usage limit reached",
|
||||
Log::Level::DEBUG);
|
||||
makePlainHttpResponse("", "403 Forbidden", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
Envelope envelope;
|
||||
if (!parseEnvelope(decryption.message, envelope)) {
|
||||
log_->write(
|
||||
@@ -161,21 +262,22 @@ void ServerHandler::handle() {
|
||||
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
|
||||
auto it = sessions_.find(session);
|
||||
|
||||
if (it != sessions_.end()) {
|
||||
targetClient = it->second;
|
||||
if (it != sessions_.end() && it->second.user == userName()) {
|
||||
targetClient = it->second.client;
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetClient || !targetClient->isOpen()) {
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
makePayloadHttpResponse("", "200 OK", connectionHeader());
|
||||
return;
|
||||
}
|
||||
|
||||
boost::asio::streambuf tunnelBuf;
|
||||
copyStringToStreambuf(hexToASCII(decryption.message), tunnelBuf);
|
||||
Usage::instance().add(usage_, tunnelBuf.size());
|
||||
targetClient->doWrite(tunnelBuf);
|
||||
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
makePayloadHttpResponse("", "200 OK", connectionHeader());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -186,13 +288,13 @@ void ServerHandler::handle() {
|
||||
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
|
||||
auto it = sessions_.find(session);
|
||||
|
||||
if (it != sessions_.end()) {
|
||||
targetClient = it->second;
|
||||
if (it != sessions_.end() && it->second.user == userName()) {
|
||||
targetClient = it->second.client;
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetClient || !targetClient->isOpen()) {
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
makePayloadHttpResponse("", "200 OK", connectionHeader());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -200,24 +302,26 @@ void ServerHandler::handle() {
|
||||
std::size_t available = targetClient->socket().available(ec);
|
||||
|
||||
if (ec || available == 0) {
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
makePayloadHttpResponse("", "200 OK", connectionHeader());
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<char> data(std::min<std::size_t>(available, config_->general().bufferSize));
|
||||
std::vector<char> data(std::min<std::size_t>(available, config_->server().bufferSize));
|
||||
std::size_t n = targetClient->socket().read_some(
|
||||
boost::asio::buffer(data),
|
||||
ec);
|
||||
|
||||
if (ec || n == 0) {
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
makePayloadHttpResponse("", "200 OK", connectionHeader());
|
||||
return;
|
||||
}
|
||||
|
||||
Usage::instance().add(usage_, n);
|
||||
|
||||
makePayloadHttpResponse(
|
||||
std::string(data.data(), n),
|
||||
"200 OK",
|
||||
(config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
connectionHeader());
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -226,12 +330,12 @@ void ServerHandler::handle() {
|
||||
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
|
||||
auto it = sessions_.find(session);
|
||||
|
||||
if (it != sessions_.end()) {
|
||||
it->second->socketShutdown();
|
||||
if (it != sessions_.end() && it->second.user == userName()) {
|
||||
it->second.client->socketShutdown();
|
||||
sessions_.erase(it);
|
||||
}
|
||||
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
makePayloadHttpResponse("", "200 OK", connectionHeader());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -274,7 +378,7 @@ void ServerHandler::handle() {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [ERROR] [Resolving Host] [SRC " +
|
||||
clientConnStr_ + "] [DST " +
|
||||
srcTag() + "] [DST " +
|
||||
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
|
||||
@@ -291,7 +395,7 @@ void ServerHandler::handle() {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [SRC " +
|
||||
clientConnStr_ + "] [DST " +
|
||||
srcTag() + "] [DST " +
|
||||
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
|
||||
@@ -317,7 +421,7 @@ void ServerHandler::handle() {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [ERROR] [Resolving Host] [SRC " +
|
||||
clientConnStr_ + "] [DST " +
|
||||
srcTag() + "] [DST " +
|
||||
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
|
||||
@@ -334,25 +438,35 @@ void ServerHandler::handle() {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [SRC " +
|
||||
clientConnStr_ + "] [ORIGIN " +
|
||||
srcTag() + "] [ORIGIN " +
|
||||
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
|
||||
if (!pendingTunnelData.empty()) {
|
||||
boost::asio::streambuf pendingBuf;
|
||||
copyStringToStreambuf(pendingTunnelData, pendingBuf);
|
||||
Usage::instance().add(usage_, pendingBuf.size());
|
||||
targetClient->doWrite(pendingBuf);
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
|
||||
sessions_[session.empty() ? to_string(uuid_) : session] = targetClient;
|
||||
const std::string key = session.empty() ? to_string(uuid_) : session;
|
||||
auto it = sessions_.find(key);
|
||||
|
||||
if (it != sessions_.end() && it->second.user != userName()) {
|
||||
targetClient->socketShutdown();
|
||||
makePayloadHttpResponse("", "403 Forbidden", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
sessions_[key] = Session{targetClient, userName()};
|
||||
}
|
||||
|
||||
makePayloadHttpResponse(
|
||||
"HTTP/1.1 200 Connection Established\r\n\r\n",
|
||||
"200 OK",
|
||||
"keep-alive");
|
||||
connectionHeader());
|
||||
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
@@ -371,19 +485,21 @@ void ServerHandler::handle() {
|
||||
}
|
||||
}
|
||||
|
||||
Usage::instance().add(usage_, readBuffer_.size());
|
||||
client_->doWrite(readBuffer_);
|
||||
client_->doReadServer();
|
||||
Usage::instance().add(usage_, client_->readBuffer().size());
|
||||
|
||||
if (client_->readBuffer().size() == 0) {
|
||||
client_->socket().close();
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
makePayloadHttpResponse("", "200 OK", connectionHeader());
|
||||
return;
|
||||
}
|
||||
|
||||
makePayloadHttpResponse(
|
||||
streambufToString(client_->readBuffer()),
|
||||
"200 OK",
|
||||
(config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
connectionHeader());
|
||||
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "config.hpp"
|
||||
#include "general.hpp"
|
||||
#include "http.hpp"
|
||||
#include "log.hpp"
|
||||
#include "tcpclient.hpp"
|
||||
#include "usage.hpp"
|
||||
|
||||
class ServerHandler : private Uncopyable {
|
||||
public:
|
||||
@@ -21,10 +23,17 @@ public:
|
||||
const std::shared_ptr<Log> &log,
|
||||
TCPClient::pointer client,
|
||||
std::string clientConnStr,
|
||||
boost::uuids::uuid uuid) {
|
||||
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log, client, clientConnStr, uuid));
|
||||
boost::uuids::uuid uuid,
|
||||
std::string &userHint) {
|
||||
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log, client, clientConnStr, uuid, userHint));
|
||||
}
|
||||
|
||||
static std::size_t revokeSessions(const std::vector<std::string> &users);
|
||||
|
||||
static void closeAllSessions();
|
||||
|
||||
std::string userName() const { return user_ ? user_->name : std::string(); }
|
||||
|
||||
~ServerHandler();
|
||||
|
||||
void handle();
|
||||
@@ -33,6 +42,7 @@ public:
|
||||
|
||||
bool end_;
|
||||
bool connect_;
|
||||
bool keepAlive_ = false;
|
||||
|
||||
private:
|
||||
struct HttpUtils {
|
||||
@@ -48,18 +58,33 @@ private:
|
||||
const std::shared_ptr<Log> &log,
|
||||
TCPClient::pointer client,
|
||||
std::string clientConnStr,
|
||||
boost::uuids::uuid uuid);
|
||||
boost::uuids::uuid uuid,
|
||||
std::string &userHint);
|
||||
|
||||
BoolStr authenticate(const std::string &payload);
|
||||
|
||||
std::string srcTag() const;
|
||||
|
||||
static std::string withoutUnverifiedSignature(const std::string &payload);
|
||||
|
||||
void makePayloadHttpResponse(const std::string &plainBody,
|
||||
const std::string &status = "200 OK",
|
||||
const std::string &connection = "close");
|
||||
|
||||
std::string connectionHeader() const;
|
||||
bool requestKeepAlive_ = false;
|
||||
|
||||
void makePlainHttpResponse(const std::string &body,
|
||||
const std::string &status = "200 OK",
|
||||
const std::string &connection = "close");
|
||||
|
||||
struct Session {
|
||||
TCPClient::pointer client;
|
||||
std::string user;
|
||||
};
|
||||
|
||||
static std::mutex sessionsMutex_;
|
||||
static std::unordered_map<std::string, TCPClient::pointer> sessions_;
|
||||
static std::unordered_map<std::string, Session> sessions_;
|
||||
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
@@ -70,4 +95,8 @@ private:
|
||||
std::string clientConnStr_;
|
||||
boost::uuids::uuid uuid_;
|
||||
std::mutex mutex_;
|
||||
|
||||
std::string &userHint_;
|
||||
const User *user_ = nullptr;
|
||||
std::shared_ptr<Usage::Counter> usage_;
|
||||
};
|
||||
@@ -89,7 +89,7 @@ namespace {
|
||||
socket.close(ignored);
|
||||
}
|
||||
|
||||
}
|
||||
}// namespace
|
||||
|
||||
TCPClient::TCPClient(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
@@ -131,11 +131,11 @@ bool TCPClient::enableTlsClient() {
|
||||
|
||||
SSL_CTX_set_min_proto_version(sslContext_.native_handle(), TLS1_2_VERSION);
|
||||
|
||||
if (config_->general().tlsVerifyPeer) {
|
||||
if (config_->agent().tlsVerifyPeer) {
|
||||
sslContext_.set_verify_mode(boost::asio::ssl::verify_peer);
|
||||
|
||||
if (!config_->general().tlsCaFile.empty()) {
|
||||
sslContext_.load_verify_file(config_->general().tlsCaFile);
|
||||
if (!config_->agent().tlsCaFile.empty()) {
|
||||
sslContext_.load_verify_file(config_->agent().tlsCaFile);
|
||||
}
|
||||
} else {
|
||||
sslContext_.set_verify_mode(boost::asio::ssl::verify_none);
|
||||
@@ -374,7 +374,6 @@ void TCPClient::writeBuffer(boost::asio::streambuf &buffer) {
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
}
|
||||
|
||||
|
||||
bool TCPClient::doWrite(boost::asio::streambuf &buffer) {
|
||||
try {
|
||||
writeBuffer_.consume(writeBuffer_.size());
|
||||
|
||||
+89
-25
@@ -9,6 +9,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include "http_utils.hpp"
|
||||
#include "usage.hpp"
|
||||
|
||||
TCPConnection::TCPConnection(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
@@ -36,6 +37,41 @@ namespace {
|
||||
constexpr unsigned int MaxPollDelayMs = 50;
|
||||
}
|
||||
|
||||
std::mutex TCPConnection::registryMutex_;
|
||||
std::unordered_map<std::string, std::vector<std::weak_ptr<TCPConnection>>> TCPConnection::byUser_;
|
||||
|
||||
void TCPConnection::trackUser(const std::string &user) {
|
||||
if (user.empty() || user == trackedUser_) return;
|
||||
trackedUser_ = user;
|
||||
usage_ = Usage::instance().counter(user);
|
||||
|
||||
std::lock_guard<std::mutex> lock(registryMutex_);
|
||||
auto &list = byUser_[user];
|
||||
list.erase(std::remove_if(list.begin(), list.end(),
|
||||
[](const std::weak_ptr<TCPConnection> &w) { return w.expired(); }),
|
||||
list.end());
|
||||
list.push_back(weak_from_this());
|
||||
}
|
||||
|
||||
std::size_t TCPConnection::revokeUsers(const std::vector<std::string> &users) {
|
||||
std::vector<pointer> open;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(registryMutex_);
|
||||
for (const auto &name: users) {
|
||||
auto it = byUser_.find(name);
|
||||
if (it == byUser_.end()) continue;
|
||||
for (const auto &w: it->second) {
|
||||
if (auto conn = w.lock()) open.push_back(conn);
|
||||
}
|
||||
byUser_.erase(it);
|
||||
}
|
||||
}
|
||||
for (const auto &conn: open) {
|
||||
boost::asio::post(conn->strand_, [conn] { conn->socketShutdown(); });
|
||||
}
|
||||
return open.size();
|
||||
}
|
||||
|
||||
boost::asio::ip::tcp::socket &TCPConnection::socket() { return socket_; }
|
||||
|
||||
TCPConnection::ssl_stream &TCPConnection::tlsSocket() { return *tlsSocket_; }
|
||||
@@ -52,9 +88,9 @@ bool TCPConnection::initTlsServerContext() {
|
||||
|
||||
SSL_CTX_set_min_proto_version(sslContext_.native_handle(), TLS1_2_VERSION);
|
||||
|
||||
sslContext_.use_certificate_chain_file(config_->general().tlsCertFile);
|
||||
sslContext_.use_certificate_chain_file(config_->server().tlsCertFile);
|
||||
sslContext_.use_private_key_file(
|
||||
config_->general().tlsKeyFile,
|
||||
config_->server().tlsKeyFile,
|
||||
boost::asio::ssl::context::pem);
|
||||
|
||||
if (!SSL_CTX_check_private_key(sslContext_.native_handle())) {
|
||||
@@ -195,7 +231,7 @@ void TCPConnection::handleReadAgent(const boost::system::error_code &error, size
|
||||
|
||||
boost::system::error_code errorIn;
|
||||
|
||||
if (config_->general().protocol == "socks5") {
|
||||
if (config_->agent().protocol == "socks5") {
|
||||
if (!handleSocks5Handshake()) {
|
||||
socketShutdown();
|
||||
return;
|
||||
@@ -260,7 +296,7 @@ void TCPConnection::handleReadAgent(const boost::system::error_code &error, size
|
||||
end_ = agentHandler_->end_;
|
||||
connect_ = agentHandler_->connect_;
|
||||
|
||||
if (config_->general().protocol == "socks5" && connect_) {
|
||||
if (config_->agent().protocol == "socks5" && connect_) {
|
||||
writeBuffer_.consume(writeBuffer_.size());
|
||||
|
||||
const unsigned char ok[10] = {
|
||||
@@ -300,11 +336,11 @@ void TCPConnection::handleReadAgent(const boost::system::error_code &error, size
|
||||
self->relayClientToServer();
|
||||
self->relayServerToClient();
|
||||
} else {
|
||||
if (!self->config_->general().connectionReuse) {
|
||||
if (!self->config_->agent().connectionReuse) {
|
||||
self->client_->socketShutdown();
|
||||
}
|
||||
|
||||
self->pollDelayMs_ = self->config_->general().pullTimeout;
|
||||
self->pollDelayMs_ = self->config_->agent().pullTimeout;
|
||||
self->startTunnelReadFromClient();
|
||||
self->startTunnelPollServer();
|
||||
}
|
||||
@@ -370,9 +406,11 @@ void TCPConnection::handleReadServer(const boost::system::error_code &error, siz
|
||||
log_,
|
||||
client_,
|
||||
remotePeer,
|
||||
uuid_);
|
||||
uuid_,
|
||||
userHint_);
|
||||
|
||||
serverHandler_->handle();
|
||||
trackUser(serverHandler_->userName());
|
||||
|
||||
end_ = serverHandler_->end_;
|
||||
connect_ = serverHandler_->connect_;
|
||||
@@ -385,7 +423,7 @@ void TCPConnection::handleReadServer(const boost::system::error_code &error, siz
|
||||
resetTimeout();
|
||||
|
||||
auto writeHandler =
|
||||
[self = shared_from_this()](
|
||||
[self = shared_from_this(), keepAlive = serverHandler_->keepAlive_](
|
||||
const boost::system::error_code &ec,
|
||||
std::size_t) {
|
||||
self->cancelTimeout();
|
||||
@@ -402,7 +440,7 @@ void TCPConnection::handleReadServer(const boost::system::error_code &error, siz
|
||||
return;
|
||||
}
|
||||
|
||||
if (self->config_->general().connectionReuse) {
|
||||
if (keepAlive) {
|
||||
self->doReadServer();
|
||||
} else {
|
||||
self->socketShutdown();
|
||||
@@ -443,8 +481,8 @@ std::string TCPConnection::makeRelayHostHeader() const {
|
||||
return hostHeader;
|
||||
}
|
||||
|
||||
std::string TCPConnection::postTunnelAction(const std::string &action,
|
||||
const std::string &rawBody) {
|
||||
std::optional<std::string> TCPConnection::postTunnelAction(const std::string &action,
|
||||
const std::string &rawBody) {
|
||||
std::lock_guard<std::mutex> relayLock(relayMutex_);
|
||||
|
||||
client_->uuid_ = uuid_;
|
||||
@@ -472,15 +510,15 @@ std::string TCPConnection::postTunnelAction(const std::string &action,
|
||||
hexArrToStr(reinterpret_cast<const unsigned char *>(rawBody.data()),
|
||||
rawBody.size()));
|
||||
BoolStr enc = config_->general().aesEnable
|
||||
? aes256Encrypt(payload, config_->general().token)
|
||||
: BoolStr{true, payload};
|
||||
? aes256Encrypt(payload, config_->agent().token)
|
||||
: BoolStr{true, signWithKey(payload, deriveAesKey(config_->agent().token))};
|
||||
|
||||
if (!enc.ok) return "";
|
||||
|
||||
const std::string encodedBody = encode64(enc.message);
|
||||
|
||||
const bool keepAlive =
|
||||
config_->general().connectionReuse && action != "close";
|
||||
config_->agent().connectionReuse && action != "close";
|
||||
|
||||
std::ostringstream req;
|
||||
req << config_->randomMethod() + " /" + config_->randomEndPoint()
|
||||
@@ -533,22 +571,27 @@ std::string TCPConnection::postTunnelAction(const std::string &action,
|
||||
std::string response = sendOnce();
|
||||
|
||||
if (response.empty() &&
|
||||
config_->general().connectionReuse &&
|
||||
config_->agent().connectionReuse &&
|
||||
action != "close") {
|
||||
client_->socketShutdown();
|
||||
response = sendOnce();
|
||||
}
|
||||
|
||||
const auto pos = response.find("\r\n\r\n");
|
||||
if (pos == std::string::npos) return "";
|
||||
if (pos == std::string::npos) return std::nullopt;
|
||||
|
||||
const auto space = response.find(' ');
|
||||
if (space == std::string::npos || response.compare(space + 1, 3, "200") != 0) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const std::string responseBody = response.substr(pos + 4);
|
||||
if (responseBody.empty()) return "";
|
||||
if (responseBody.empty()) return std::string();
|
||||
|
||||
BoolStr dec = config_->general().aesEnable
|
||||
? aes256Decrypt(responseBody, config_->general().token)
|
||||
? aes256Decrypt(responseBody, config_->agent().token)
|
||||
: BoolStr{true, responseBody};
|
||||
if (!dec.ok) return "";
|
||||
if (!dec.ok) return std::nullopt;
|
||||
|
||||
return dec.message;
|
||||
}
|
||||
@@ -613,7 +656,6 @@ bool TCPConnection::handleSocks5Handshake() {
|
||||
std::to_string(header[0]),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
|
||||
unsigned char req[4];
|
||||
if (!readExactFromClient(req, 4)) return false;
|
||||
|
||||
@@ -680,7 +722,6 @@ bool TCPConnection::handleSocks5Handshake() {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
void TCPConnection::startTunnelReadFromClient() {
|
||||
if (tunnelClosed_ || !socket_.is_open()) return;
|
||||
|
||||
@@ -697,9 +738,12 @@ void TCPConnection::startTunnelReadFromClient() {
|
||||
|
||||
std::string raw(self->downstreamBuf_.data(), bytes);
|
||||
|
||||
self->postTunnelAction("send", raw);
|
||||
if (!self->postTunnelAction("send", raw)) {
|
||||
self->abortTunnel("send refused or failed");
|
||||
return;
|
||||
}
|
||||
|
||||
self->pollDelayMs_ = self->config_->general().pullTimeout;
|
||||
self->pollDelayMs_ = self->config_->agent().pullTimeout;
|
||||
if (self->pollInProgress_) self->pollTimer_.cancel();
|
||||
|
||||
self->startTunnelReadFromClient();
|
||||
@@ -727,9 +771,14 @@ void TCPConnection::startTunnelPollServer() {
|
||||
|
||||
if (ec) return;
|
||||
|
||||
std::string data = self->postTunnelAction("recv", "");
|
||||
std::optional<std::string> reply = self->postTunnelAction("recv", "");
|
||||
if (!reply) {
|
||||
self->abortTunnel("recv refused or failed");
|
||||
return;
|
||||
}
|
||||
std::string data = std::move(*reply);
|
||||
|
||||
const unsigned int baseDelay = self->config_->general().pullTimeout;
|
||||
const unsigned int baseDelay = self->config_->agent().pullTimeout;
|
||||
self->pollDelayMs_ =
|
||||
data.empty()
|
||||
? std::min(std::max(self->pollDelayMs_ * 2, 1u), std::max(MaxPollDelayMs, baseDelay))
|
||||
@@ -757,6 +806,17 @@ void TCPConnection::startTunnelPollServer() {
|
||||
}));
|
||||
}
|
||||
|
||||
void TCPConnection::abortTunnel(const std::string &reason) {
|
||||
if (tunnelClosed_) return;
|
||||
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPConnection] [Tunnel closed] " + reason,
|
||||
Log::Level::INFO);
|
||||
|
||||
tunnelClosed_ = true;
|
||||
pollTimer_.cancel();
|
||||
socketShutdown();
|
||||
}
|
||||
|
||||
void TCPConnection::closeTunnelSession() {
|
||||
if (tunnelClosed_) return;
|
||||
|
||||
@@ -1029,6 +1089,8 @@ void TCPConnection::relayAgentToTarget() {
|
||||
return;
|
||||
}
|
||||
|
||||
Usage::instance().add(self->usage_, bytes);
|
||||
|
||||
boost::asio::async_write(
|
||||
self->client_->socket(),
|
||||
boost::asio::buffer(self->downstreamBuf_.data(), bytes),
|
||||
@@ -1063,6 +1125,8 @@ void TCPConnection::relayTargetToAgent() {
|
||||
return;
|
||||
}
|
||||
|
||||
Usage::instance().add(self->usage_, bytes);
|
||||
|
||||
self->asyncWriteToAgentConnection(
|
||||
self->upstreamBuf_.data(),
|
||||
bytes,
|
||||
|
||||
@@ -12,11 +12,15 @@
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "agenthandler.hpp"
|
||||
#include "general.hpp"
|
||||
#include "serverhandler.hpp"
|
||||
#include "usage.hpp"
|
||||
|
||||
class TCPConnection : public std::enable_shared_from_this<TCPConnection> {
|
||||
public:
|
||||
@@ -55,6 +59,8 @@ public:
|
||||
|
||||
void socketShutdown();
|
||||
|
||||
static std::size_t revokeUsers(const std::vector<std::string> &users);
|
||||
|
||||
void enableDirectTunnelMode();
|
||||
|
||||
void relayClientToServer();
|
||||
@@ -120,10 +126,13 @@ private:
|
||||
|
||||
void startTunnelReadFromClient();
|
||||
void startTunnelPollServer();
|
||||
std::string postTunnelAction(const std::string &action, const std::string &rawBody);
|
||||
std::optional<std::string> postTunnelAction(const std::string &action, const std::string &rawBody);
|
||||
void abortTunnel(const std::string &reason);
|
||||
std::string makeRelayHostHeader() const;
|
||||
void closeTunnelSession();
|
||||
|
||||
void trackUser(const std::string &user);
|
||||
|
||||
boost::asio::ip::tcp::socket socket_;
|
||||
boost::asio::ssl::context sslContext_;
|
||||
std::unique_ptr<ssl_stream> tlsSocket_;
|
||||
@@ -151,6 +160,13 @@ private:
|
||||
unsigned int pollDelayMs_;
|
||||
std::atomic_bool closed_{false};
|
||||
|
||||
std::string userHint_;
|
||||
std::string trackedUser_;
|
||||
std::shared_ptr<Usage::Counter> usage_;
|
||||
|
||||
static std::mutex registryMutex_;
|
||||
static std::unordered_map<std::string, std::vector<std::weak_ptr<TCPConnection>>> byUser_;
|
||||
|
||||
std::array<char, BufferSize> downstreamBuf_;
|
||||
std::array<char, BufferSize> upstreamBuf_;
|
||||
};
|
||||
@@ -0,0 +1,220 @@
|
||||
#include "usage.hpp"
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <ctime>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
Usage &Usage::instance() {
|
||||
static Usage usage;
|
||||
return usage;
|
||||
}
|
||||
|
||||
std::string Usage::periodStart(int resetDay) {
|
||||
const std::time_t now = std::time(nullptr);
|
||||
std::tm local{};
|
||||
#if defined(_WIN32)
|
||||
localtime_s(&local, &now);
|
||||
#else
|
||||
localtime_r(&now, &local);
|
||||
#endif
|
||||
int year = local.tm_year + 1900;
|
||||
int month = local.tm_mon + 1;
|
||||
if (local.tm_mday < resetDay) {
|
||||
if (--month == 0) {
|
||||
month = 12;
|
||||
--year;
|
||||
}
|
||||
}
|
||||
char buf[40];
|
||||
std::snprintf(buf, sizeof(buf), "%04d-%02d-%02d", year, month, resetDay);
|
||||
return buf;
|
||||
}
|
||||
|
||||
bool Usage::overLimit(const Counter &counter) {
|
||||
const std::uint64_t limit = counter.limit.load();
|
||||
return limit != 0 && counter.used.load() >= limit;
|
||||
}
|
||||
|
||||
void Usage::configure(const Config &config, LimitHandler onLimit, Log &log) {
|
||||
std::vector<std::string> newlyBlocked;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (!onLimit_) onLimit_ = std::move(onLimit);
|
||||
|
||||
enabled_ = config.runMode() == RunMode::server && config.hasUserList();
|
||||
if (!enabled_) return;
|
||||
|
||||
file_ = config.usageFile();
|
||||
resetDay_ = config.usageResetDay();
|
||||
|
||||
active_.clear();
|
||||
for (const auto &user: config.users()) {
|
||||
auto &counter = counters_[user.name];
|
||||
if (!counter) counter = std::make_shared<Counter>(user.name);
|
||||
counter->limit.store(user.limit);
|
||||
active_.insert(user.name);
|
||||
}
|
||||
newlyBlocked = refreshBlocked(log);
|
||||
}
|
||||
for (const auto &name: newlyBlocked) onLimit_(name);
|
||||
}
|
||||
|
||||
Usage::CounterPtr Usage::counter(const std::string &user) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!enabled_) return nullptr;
|
||||
auto it = counters_.find(user);
|
||||
return it == counters_.end() ? nullptr : it->second;
|
||||
}
|
||||
|
||||
void Usage::add(const CounterPtr &counter, std::uint64_t bytes) {
|
||||
if (!counter || bytes == 0) return;
|
||||
|
||||
const std::uint64_t after = counter->used.fetch_add(bytes) + bytes;
|
||||
const std::uint64_t limit = counter->limit.load();
|
||||
|
||||
if (limit != 0 && after >= limit && !counter->blocked.exchange(true) && onLimit_) {
|
||||
onLimit_(counter->name);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> Usage::refreshBlocked(Log &log) {
|
||||
std::vector<std::string> newlyBlocked;
|
||||
for (const auto &[name, counter]: counters_) {
|
||||
const bool over = overLimit(*counter);
|
||||
if (over && !counter->blocked.exchange(true)) {
|
||||
newlyBlocked.push_back(name);
|
||||
} else if (!over && counter->blocked.exchange(false)) {
|
||||
log.write("[Usage] user " + name + " is below their limit again", Log::Level::INFO);
|
||||
}
|
||||
}
|
||||
return newlyBlocked;
|
||||
}
|
||||
|
||||
void Usage::flush(Log &log) {
|
||||
std::vector<std::string> newlyBlocked;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!enabled_) return;
|
||||
|
||||
YAML::Node doc;
|
||||
bool haveFile = false;
|
||||
if (fileExists(file_)) {
|
||||
try {
|
||||
doc = YAML::LoadFile(file_);
|
||||
haveFile = true;
|
||||
} catch (const std::exception &e) {
|
||||
log.write("[Usage] cannot read " + file_ + ": " + e.what() +
|
||||
"; usage is not saved until the file is fixed",
|
||||
Log::Level::ERROR);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const std::string filePeriod = haveFile ? doc["period"].as<std::string>("") : "";
|
||||
const bool firstFlush = !loaded_;
|
||||
if (firstFlush) {
|
||||
period_ = filePeriod.empty() ? periodStart(resetDay_) : filePeriod;
|
||||
loaded_ = true;
|
||||
}
|
||||
|
||||
const YAML::Node fileUsers = haveFile ? doc["users"] : YAML::Node();
|
||||
if (haveFile && filePeriod == period_ && fileUsers.IsMap()) {
|
||||
for (auto &[name, counter]: counters_) {
|
||||
const YAML::Node entry = fileUsers[name];
|
||||
if (!entry || !entry["used"]) continue;
|
||||
|
||||
std::uint64_t value = 0;
|
||||
try {
|
||||
value = entry["used"].as<std::uint64_t>();
|
||||
} catch (const std::exception &) {
|
||||
log.write("[Usage] used of " + name + " in " + file_ +
|
||||
" is not a number of bytes; ignored",
|
||||
Log::Level::ERROR);
|
||||
continue;
|
||||
}
|
||||
if (value == counter->lastWritten) continue;
|
||||
|
||||
counter->used.fetch_add(value - counter->lastWritten);
|
||||
counter->lastWritten = value;
|
||||
if (!firstFlush) {
|
||||
log.write("[Usage] usage of " + name + " set to " + formatBytes(value) +
|
||||
" from " + file_,
|
||||
Log::Level::INFO);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const std::string current = periodStart(resetDay_);
|
||||
if (current != period_) {
|
||||
for (auto &[name, counter]: counters_) counter->used.store(0);
|
||||
log.write("[Usage] new usage period from " + current + "; usage of all users reset",
|
||||
Log::Level::INFO);
|
||||
period_ = current;
|
||||
}
|
||||
|
||||
newlyBlocked = refreshBlocked(log);
|
||||
|
||||
std::vector<std::string> names;
|
||||
for (const auto &[name, counter]: counters_) names.push_back(name);
|
||||
std::sort(names.begin(), names.end());
|
||||
|
||||
std::ostringstream out;
|
||||
out << "# NipoVPN usage: bytes each user sent and received since " << period_ << ".\n"
|
||||
<< "# To change a user's usage, edit their \"used\" (for example set it to 0).\n"
|
||||
<< "# The server applies the change within 30 seconds. Do not edit \"period\".\n"
|
||||
<< "period: \"" << period_ << "\"\n"
|
||||
<< "users:\n";
|
||||
|
||||
std::vector<std::pair<Counter *, std::uint64_t>> written;
|
||||
for (const auto &name: names) {
|
||||
Counter &counter = *counters_[name];
|
||||
const std::uint64_t used = counter.used.load();
|
||||
const std::uint64_t limit = counter.limit.load();
|
||||
out << " " << name << ": {used: " << used << "} # " << formatBytes(used);
|
||||
if (!active_.count(name)) {
|
||||
out << ", not in the users list";
|
||||
} else if (limit != 0) {
|
||||
out << " of " << formatBytes(limit) << " ("
|
||||
<< std::min<std::uint64_t>(used * 100 / limit, 999) << "%)"
|
||||
<< (used >= limit ? ", blocked" : "");
|
||||
} else {
|
||||
out << ", no limit";
|
||||
}
|
||||
out << "\n";
|
||||
written.emplace_back(&counter, used);
|
||||
}
|
||||
|
||||
if (haveFile && filePeriod == period_ && fileUsers.IsMap()) {
|
||||
for (const auto &entry: fileUsers) {
|
||||
const std::string name = entry.first.as<std::string>("");
|
||||
if (name.empty() || counters_.count(name) || !isValidUserName(name)) continue;
|
||||
out << " " << name << ": {used: " << entry.second["used"].as<std::uint64_t>(0)
|
||||
<< "} # not in the users list\n";
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const std::filesystem::path path(file_);
|
||||
if (path.has_parent_path()) std::filesystem::create_directories(path.parent_path());
|
||||
const std::string tmp = file_ + ".tmp";
|
||||
{
|
||||
std::ofstream f(tmp, std::ios::out | std::ios::trunc);
|
||||
if (!f) throw std::runtime_error("cannot open " + tmp + " for writing");
|
||||
f << out.str();
|
||||
f.flush();
|
||||
if (!f) throw std::runtime_error("cannot write " + tmp);
|
||||
}
|
||||
std::filesystem::rename(tmp, path);
|
||||
for (const auto &[counter, used]: written) counter->lastWritten = used;
|
||||
} catch (const std::exception &e) {
|
||||
log.write(std::string("[Usage] cannot save usage: ") + e.what(), Log::Level::ERROR);
|
||||
}
|
||||
}
|
||||
for (const auto &name: newlyBlocked) onLimit_(name);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
#include "config.hpp"
|
||||
#include "log.hpp"
|
||||
|
||||
class Usage : private Uncopyable {
|
||||
public:
|
||||
struct Counter {
|
||||
explicit Counter(std::string userName) : name(std::move(userName)) {}
|
||||
|
||||
const std::string name;
|
||||
std::atomic<std::uint64_t> used{0};
|
||||
std::atomic<std::uint64_t> limit{0};
|
||||
std::atomic<bool> blocked{false};
|
||||
std::uint64_t lastWritten = 0;
|
||||
};
|
||||
using CounterPtr = std::shared_ptr<Counter>;
|
||||
|
||||
using LimitHandler = std::function<void(const std::string &user)>;
|
||||
|
||||
static Usage &instance();
|
||||
|
||||
void configure(const Config &config, LimitHandler onLimit, Log &log);
|
||||
|
||||
CounterPtr counter(const std::string &user);
|
||||
|
||||
void add(const CounterPtr &counter, std::uint64_t bytes);
|
||||
|
||||
static bool overLimit(const Counter &counter);
|
||||
|
||||
void flush(Log &log);
|
||||
|
||||
static std::string periodStart(int resetDay);
|
||||
|
||||
private:
|
||||
Usage() = default;
|
||||
|
||||
std::vector<std::string> refreshBlocked(Log &log);
|
||||
|
||||
std::mutex mutex_;
|
||||
std::unordered_map<std::string, CounterPtr> counters_;
|
||||
std::unordered_set<std::string> active_;
|
||||
LimitHandler onLimit_;
|
||||
bool enabled_ = false;
|
||||
std::string file_;
|
||||
int resetDay_ = 1;
|
||||
std::string period_;
|
||||
bool loaded_ = false;
|
||||
};
|
||||
@@ -17,10 +17,13 @@ services:
|
||||
volumes:
|
||||
- ../nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro
|
||||
- nipovpn_logs:/var/log/nipovpn
|
||||
# Per-user usage (server with a users list); keeps counts across restarts.
|
||||
- nipovpn_state:/var/lib/nipovpn
|
||||
|
||||
command:
|
||||
- ${NIPOVPN_MODE:-server}
|
||||
- /etc/nipovpn/config.yaml
|
||||
|
||||
volumes:
|
||||
nipovpn_logs:
|
||||
nipovpn_logs:
|
||||
nipovpn_state:
|
||||
@@ -1,3 +0,0 @@
|
||||
theme: jekyll-theme-minimal
|
||||
title: NipoVPN's homepage
|
||||
description: Safe and powerful http proxy
|
||||
@@ -1,74 +0,0 @@
|
||||
body {
|
||||
font-family: 'Karla', sans-serif;
|
||||
background-image: url("../images/bg.jpg");
|
||||
background-size: cover;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
color: #ffffff;
|
||||
padding-bottom: 75px; }
|
||||
@media (min-width: 768px) {
|
||||
body {
|
||||
padding-bottom: 110px; } }
|
||||
|
||||
.navbar-brand {
|
||||
margin-right: 0; }
|
||||
.navbar-brand img {
|
||||
height: 21px; }
|
||||
|
||||
.navbar-dark {
|
||||
padding-top: 35px;
|
||||
padding-bottom: 35px; }
|
||||
.navbar-dark .navbar-text {
|
||||
color: #ffffff;
|
||||
opacity: 1;
|
||||
padding: 0 20px;
|
||||
border-right: 1px solid #ffffff;
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
text-align: center; }
|
||||
.navbar-dark .navbar-text:last-child {
|
||||
border-right: 0; }
|
||||
@media (max-width: 767px) {
|
||||
.navbar-dark {
|
||||
padding-bottom: 0; } }
|
||||
|
||||
.page-title {
|
||||
font-size: 80px;
|
||||
font-weight: bold;
|
||||
margin-bottom: 6px; }
|
||||
@media (max-width: 767px) {
|
||||
.page-title {
|
||||
font-size: 35px;
|
||||
margin-bottom: 14px; } }
|
||||
|
||||
.page-description {
|
||||
max-width: 465px;
|
||||
font-size: 18px;
|
||||
margin-bottom: 59px; }
|
||||
@media (max-width: 767px) {
|
||||
.page-description {
|
||||
font-size: 14px; } }
|
||||
|
||||
p {
|
||||
font-size: 14px;
|
||||
margin-bottom: 21px; }
|
||||
|
||||
.footer-social-links .social-link {
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
line-height: 40px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background-color: #ffffff;
|
||||
color: #000000;
|
||||
margin-right: 16px;
|
||||
transition: all 0.3s ease-in-out; }
|
||||
.footer-social-links .social-link:last-child {
|
||||
margin-right: 0; }
|
||||
.footer-social-links .social-link:hover {
|
||||
text-decoration: none;
|
||||
background-color: #000000;
|
||||
color: #ffffff; }
|
||||
|
||||
/*# sourceMappingURL=bd-coming-soon.css.map */
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["bd-coming-soon.scss"],"names":[],"mappings":"AAAA;EACI,gCAAgC;EAChC,yCAAyC;EACzC,sBAAsB;EACtB,4BAA4B;EAC5B,2BAA2B;EAC3B,cAAc;EACd,oBAAoB,EAAA;EAEpB;IATJ;MAUQ,qBAAqB,EAAA,EAE5B;;AACD;EACI,eAAe,EAAA;EADnB;IAIQ,YAAY,EAAA;;AAGpB;EACI,iBAAiB;EACjB,oBAAoB,EAAA;EAFxB;IAIQ,cAAc;IACd,UAAU;IACV,eAAe;IACf,+BAA+B;IAC/B,eAAe;IACf,iBAAiB;IACjB,kBAAkB,EAAA;IAV1B;MAaY,eAAe,EAAA;EAIvB;IAjBJ;MAkBQ,iBAAiB,EAAA,EAExB;;AACD;EACI,eAAe;EACf,iBAAiB;EACjB,kBAAkB,EAAA;EAElB;IALJ;MAMQ,eAAe;MACf,mBAAmB,EAAA,EAE1B;;AACD;EACI,gBAAgB;EAChB,eAAe;EACf,mBAAmB,EAAA;EAEnB;IALJ;MAMQ,eAAe,EAAA,EAEtB;;AAED;EACI,eAAe;EACf,mBAAmB,EAAA;;AAGvB;EAEQ,qBAAqB;EACrB,kBAAkB;EAClB,iBAAiB;EACjB,WAAW;EACX,YAAY;EACZ,kBAAkB;EAClB,yBAAyB;EACzB,cAAc;EACd,kBAAkB;EAClB,gCAAgC,EAAA;EAXxC;IAcY,eAAe,EAAA;EAd3B;IAkBY,qBAAqB;IACrB,yBAAyB;IACzB,cAAc,EAAA","file":"bd-coming-soon.css","sourcesContent":["body {\n font-family: 'Karla', sans-serif;\n background-image: url(\"../images/bg.jpg\");\n background-size: cover;\n background-repeat: no-repeat;\n background-position: center;\n color: #ffffff;\n padding-bottom: 75px;\n\n @media (min-width: 768px) {\n padding-bottom: 110px;\n }\n}\n.navbar-brand {\n margin-right: 0;\n\n img {\n height: 21px;\n }\n}\n.navbar-dark {\n padding-top: 35px;\n padding-bottom: 35px;\n .navbar-text {\n color: #ffffff;\n opacity: 1;\n padding: 0 20px;\n border-right: 1px solid #ffffff;\n font-size: 18px;\n font-weight: bold;\n text-align: center;\n\n &:last-child {\n border-right: 0;\n }\n }\n\n @media (max-width: 767px) {\n padding-bottom: 0;\n }\n}\n.page-title {\n font-size: 80px;\n font-weight: bold;\n margin-bottom: 6px;\n\n @media (max-width: 767px) {\n font-size: 35px;\n margin-bottom: 14px; \n }\n}\n.page-description {\n max-width: 465px;\n font-size: 18px;\n margin-bottom: 59px;\n\n @media (max-width: 767px) {\n font-size: 14px; \n }\n}\n\np {\n font-size: 14px;\n margin-bottom: 21px;\n}\n\n.footer-social-links {\n .social-link {\n display: inline-block;\n text-align: center;\n line-height: 40px;\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background-color: #ffffff;\n color: #000000;\n margin-right: 16px;\n transition: all 0.3s ease-in-out;\n\n &:last-child {\n margin-right: 0;\n }\n\n &:hover {\n text-decoration: none;\n background-color: #000000;\n color: #ffffff;\n }\n }\n}"]}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 215 KiB |
@@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="59" height="25" viewBox="0 0 59 25" fill="#FFFFFF">
|
||||
<path d="M4.125,15.3 L10.05,15.3 L10.05,18 L0.6,18 L0.6,0.35 L4.125,0.35 L4.125,15.3 Z M18.55,3.975 C19.9000067,3.975 21.1124946,4.2583305 22.1875,4.825 C23.2625054,5.3916695 24.1083302,6.21249462 24.725,7.2875 C25.3416697,8.36250537 25.65,9.62499275 25.65,11.075 C25.65,12.5250073 25.3416697,13.783328 24.725,14.85 C24.1083302,15.916672 23.2625054,16.7374971 22.1875,17.3125 C21.1124946,17.8875029 19.9000067,18.175 18.55,18.175 C17.1999933,18.175 15.9875054,17.8875029 14.9125,17.3125 C13.8374946,16.7374971 12.9916697,15.916672 12.375,14.85 C11.7583302,13.783328 11.45,12.5250073 11.45,11.075 C11.45,9.62499275 11.7583302,8.36250537 12.375,7.2875 C12.9916697,6.21249462 13.8374946,5.3916695 14.9125,4.825 C15.9875054,4.2583305 17.1999933,3.975 18.55,3.975 Z M18.55,7.025 C17.5666618,7.025 16.7333368,7.37082987 16.05,8.0625 C15.3666633,8.75417013 15.025,9.75832675 15.025,11.075 C15.025,12.3916733 15.3666633,13.3958299 16.05,14.0875 C16.7333368,14.7791701 17.5666618,15.125 18.55,15.125 C19.5333382,15.125 20.3666633,14.7791701 21.05,14.0875 C21.7333367,13.3958299 22.075,12.3916733 22.075,11.075 C22.075,9.75832675 21.7333367,8.75417013 21.05,8.0625 C20.3666633,7.37082987 19.5333382,7.025 18.55,7.025 Z M33.575,3.975 C34.7416725,3.975 35.7416625,4.24999725 36.575,4.8 C37.4083375,5.35000275 37.9999982,6.091662 38.35,7.025 L38.35,4.15 L41.85,4.15 L41.85,18.05 C41.85,19.3333398 41.5958359,20.4874949 41.0875,21.5125 C40.5791641,22.5375051 39.8208384,23.3416638 38.8125,23.925 C37.8041616,24.5083363 36.5833405,24.8 35.15,24.8 C33.14999,24.8 31.5333395,24.3250048 30.3,23.375 C29.0666605,22.4249953 28.316668,21.1333415 28.05,19.5 L31.525,19.5 C31.725001,20.2000035 32.1124971,20.7458314 32.6875,21.1375 C33.2625029,21.5291686 33.9999955,21.725 34.9,21.725 C35.9333385,21.725 36.7666635,21.4208364 37.4,20.8125 C38.0333365,20.2041636 38.35,19.2833395 38.35,18.05 L38.35,15.1 C37.9999982,16.033338 37.4083375,16.7791639 36.575,17.3375 C35.7416625,17.8958361 34.7416725,18.175 33.575,18.175 C32.4083275,18.175 31.358338,17.8916695 30.425,17.325 C29.491662,16.7583305 28.7625026,15.9375054 28.2375,14.8625 C27.7124974,13.7874946 27.45,12.5250073 27.45,11.075 C27.45,9.62499275 27.7124974,8.36250537 28.2375,7.2875 C28.7625026,6.21249462 29.491662,5.3916695 30.425,4.825 C31.358338,4.2583305 32.4083275,3.975 33.575,3.975 Z M34.675,7.05 C33.5749945,7.05 32.69167,7.40832975 32.025,8.125 C31.35833,8.84167025 31.025,9.82499375 31.025,11.075 C31.025,12.3250063 31.35833,13.3041631 32.025,14.0125 C32.69167,14.7208369 33.5749945,15.075 34.675,15.075 C35.741672,15.075 36.6208299,14.7125036 37.3125,13.9875 C38.0041701,13.2624964 38.35,12.2916728 38.35,11.075 C38.35,9.8416605 38.0041701,8.86250363 37.3125,8.1375 C36.6208299,7.41249637 35.741672,7.05 34.675,7.05 Z M51.45,3.975 C52.8000068,3.975 54.0124946,4.2583305 55.0875,4.825 C56.1625054,5.3916695 57.0083302,6.21249462 57.625,7.2875 C58.2416697,8.36250537 58.55,9.62499275 58.55,11.075 C58.55,12.5250073 58.2416697,13.783328 57.625,14.85 C57.0083302,15.916672 56.1625054,16.7374971 55.0875,17.3125 C54.0124946,17.8875029 52.8000068,18.175 51.45,18.175 C50.0999933,18.175 48.8875054,17.8875029 47.8125,17.3125 C46.7374946,16.7374971 45.8916698,15.916672 45.275,14.85 C44.6583303,13.783328 44.35,12.5250073 44.35,11.075 C44.35,9.62499275 44.6583303,8.36250537 45.275,7.2875 C45.8916698,6.21249462 46.7374946,5.3916695 47.8125,4.825 C48.8875054,4.2583305 50.0999933,3.975 51.45,3.975 Z M51.45,7.025 C50.4666618,7.025 49.6333367,7.37082987 48.95,8.0625 C48.2666633,8.75417013 47.925,9.75832675 47.925,11.075 C47.925,12.3916733 48.2666633,13.3958299 48.95,14.0875 C49.6333367,14.7791701 50.4666618,15.125 51.45,15.125 C52.4333383,15.125 53.2666633,14.7791701 53.95,14.0875 C54.6333367,13.3958299 54.975,12.3916733 54.975,11.075 C54.975,9.75832675 54.6333367,8.75417013 53.95,8.0625 C53.2666633,7.37082987 52.4333383,7.025 51.45,7.025 Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 3.9 KiB |
@@ -1,90 +0,0 @@
|
||||
body {
|
||||
font-family: 'Karla', sans-serif;
|
||||
background-image: url("../images/bg.jpg");
|
||||
background-size: cover;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
color: #ffffff;
|
||||
padding-bottom: 75px;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
padding-bottom: 110px;
|
||||
}
|
||||
}
|
||||
.navbar-brand {
|
||||
margin-right: 0;
|
||||
|
||||
img {
|
||||
height: 21px;
|
||||
}
|
||||
}
|
||||
.navbar-dark {
|
||||
padding-top: 35px;
|
||||
padding-bottom: 35px;
|
||||
.navbar-text {
|
||||
color: #ffffff;
|
||||
opacity: 1;
|
||||
padding: 0 20px;
|
||||
border-right: 1px solid #ffffff;
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
|
||||
&:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
}
|
||||
.page-title {
|
||||
font-size: 80px;
|
||||
font-weight: bold;
|
||||
margin-bottom: 6px;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
font-size: 35px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
}
|
||||
.page-description {
|
||||
max-width: 465px;
|
||||
font-size: 18px;
|
||||
margin-bottom: 59px;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 14px;
|
||||
margin-bottom: 21px;
|
||||
}
|
||||
|
||||
.footer-social-links {
|
||||
.social-link {
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
line-height: 40px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background-color: #ffffff;
|
||||
color: #000000;
|
||||
margin-right: 16px;
|
||||
transition: all 0.3s ease-in-out;
|
||||
|
||||
&:last-child {
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
text-decoration: none;
|
||||
background-color: #000000;
|
||||
color: #ffffff;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
//Import
|
||||
|
||||
const gulp = require('gulp');
|
||||
const sass = require('gulp-sass');
|
||||
const sourceMaps = require('gulp-sourcemaps');
|
||||
const autoprefixer = require('gulp-autoprefixer');
|
||||
const browserSync = require('browser-sync');
|
||||
|
||||
//SCSS
|
||||
|
||||
function style() {
|
||||
return gulp.src('./assets/scss/*.scss')
|
||||
.pipe(sourceMaps.init())
|
||||
.pipe(sass().on('error', sass.logError))
|
||||
.pipe(autoprefixer())
|
||||
.pipe(sourceMaps.write('./'))
|
||||
.pipe(gulp.dest('./assets/css'))
|
||||
.pipe(browserSync.stream());
|
||||
}
|
||||
|
||||
//Serve and watch
|
||||
|
||||
function watch() {
|
||||
browserSync.init({
|
||||
server: {
|
||||
baseDir: './',
|
||||
},
|
||||
startPath: './index.html',
|
||||
ghostMode: false,
|
||||
notify: false
|
||||
});
|
||||
gulp.watch('./assets/scss/*.scss', style);
|
||||
gulp.watch('./*.html').on('change', browserSync.reload);
|
||||
gulp.watch('./assets/js/*.js').on('change', browserSync.reload);
|
||||
|
||||
}
|
||||
|
||||
exports.style = style;
|
||||
exports.watch = watch;
|
||||
@@ -1,45 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
||||
<title>NipoVPN documentation</title>
|
||||
<link href="https://fonts.googleapis.com/css?family=Karla:400,700&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="https://cdn.materialdesignicons.com/4.8.95/css/materialdesignicons.min.css">
|
||||
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="assets/css/bd-coming-soon.css">
|
||||
</head>
|
||||
|
||||
<body class="min-vh-100 d-flex flex-column">
|
||||
|
||||
<header>
|
||||
<div class="container">
|
||||
<nav class="navbar navbar-dark bg-transparenet">
|
||||
<a class="navbar-brand" href="#">
|
||||
<img src="assets/images/logo.svg" alt="logo">
|
||||
</a>
|
||||
<span class="navbar-text ml-auto d-none d-sm-inline-block">Email</span>
|
||||
<span class="navbar-text d-none d-sm-inline-block">morteza.bashsiz@gmail.com</span>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
<main class="my-auto">
|
||||
<div class="container">
|
||||
<h1 class="page-title">We're coming soon</h1>
|
||||
<p class="page-description">We are working hard to make it possible
|
||||
</p>
|
||||
<p>Stay connected</p>
|
||||
<!-- <nav class="footer-social-links">
|
||||
<a href="#!" class="social-link"><i class="mdi mdi-facebook-box"></i></a>
|
||||
<a href="#!" class="social-link"><i class="mdi mdi-twitter"></i></a>
|
||||
<a href="#!" class="social-link"><i class="mdi mdi-google"></i></a>
|
||||
<a href="#!" class="social-link"><i class="mdi mdi-slack"></i></a>
|
||||
<a href="#!" class="social-link"><i class="mdi mdi-skype"></i></a>
|
||||
</nav> -->
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
Generated
-4995
File diff suppressed because it is too large.
Load diff
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"name": "bd-wizard-free-1",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"browser-sync": "^3.0.2",
|
||||
"gulp": "^5.0.0",
|
||||
"gulp-autoprefixer": "^7.0.1",
|
||||
"gulp-sass": "^5.1.0",
|
||||
"gulp-sourcemaps": "^2.6.5",
|
||||
"node-sass": "^9.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1,74 +1,24 @@
|
||||
---
|
||||
# This block contains general and global configuration which is in both modes
|
||||
# This block holds settings both the agent and the server use.
|
||||
# aesEnable, tunnelEnable and tlsEnable must be the same on both.
|
||||
general:
|
||||
# token: at least 32 bytes of string. The AES-256-GCM key is derived from it. Must match on agent and server.
|
||||
# This sample value is public: replace it, e.g. with the output of `openssl rand -hex 16`
|
||||
token: "af445adb-2434-4975-9445-2c1b2231"
|
||||
# aesEnable: bool (default: true)
|
||||
# Enables AES-256-GCM payload encryption (confidentiality and integrity). Must match on the agent and server.
|
||||
# When false, requests are signed (HMAC-SHA256) instead, so users still work,
|
||||
# but traffic is readable on the path unless tlsEnable is true.
|
||||
# Independent of tlsEnable; request encoding remains enabled.
|
||||
aesEnable: true
|
||||
# protocol:
|
||||
# Defines the protocol between client and agent
|
||||
# Choose http or socks5
|
||||
protocol: socks5
|
||||
# bufferSize: unsigned short
|
||||
# Defines the maximum buffer size for each request in Bytes. Default is 65536
|
||||
# Do not use less than 1 and more than 65536
|
||||
bufferSize: 65536
|
||||
# fakeUrls:
|
||||
# Defines the list of fake urls between agent and server
|
||||
fakeUrls:
|
||||
- nipo.ciron.net
|
||||
- sudoer.ir
|
||||
- sudoer.net
|
||||
- google.com
|
||||
- cloudflare.com
|
||||
# methods:
|
||||
# Defines the list of using methods
|
||||
# you like to send requests from agent to server
|
||||
# Program will choose randomly from this list
|
||||
methods:
|
||||
- GET
|
||||
- POST
|
||||
- PUT
|
||||
- DELETE
|
||||
# endPoints:
|
||||
# Defines the list of using endpoints
|
||||
# you like to send requests from agent to server
|
||||
# Program will choose randomly from this list
|
||||
endPoints:
|
||||
- api
|
||||
- login
|
||||
- user
|
||||
- update
|
||||
aesEnable: false
|
||||
# timeout: unsigned short
|
||||
# Defines the timeout for I/O Operation in seconds. 0 indicates no timeout.
|
||||
# Useful to automatically close stalled connections.
|
||||
timeout: 10
|
||||
# pullTimeout: unsigned short
|
||||
# Defines the timeout for I/O Operation in milliseconds.
|
||||
# Useful to expire serverside read timer.
|
||||
pullTimeout: 1
|
||||
# tunnelEnable: bool
|
||||
# Defines the connection mode between agent and server. If enabled then the traffic
|
||||
# will be TCP/TLS tunnel like.
|
||||
tunnelEnable: false
|
||||
# connectionReuse: bool
|
||||
# If true then it will use same connection between agent and server to handle client request
|
||||
# If false then it will create new connection for each request between agent and server
|
||||
connectionReuse: true
|
||||
tunnelEnable: true
|
||||
# tlsEnable: bool
|
||||
# It enables or disables tls between agent and server
|
||||
tlsEnable: true
|
||||
# tlsVerifyPeer: bool
|
||||
# Use it to controll if the certificate should be validated or not
|
||||
tlsVerifyPeer: false
|
||||
# Use following configurations to specify the key and cert which will be used between agent and server
|
||||
tlsCertFile: "/etc/nipovpn/server.crt"
|
||||
tlsKeyFile: "/etc/nipovpn/server.key"
|
||||
tlsCaFile: ""
|
||||
|
||||
|
||||
# This block is to define log directives
|
||||
log:
|
||||
@@ -86,21 +36,94 @@ server:
|
||||
listenIp: "0.0.0.0"
|
||||
# listenPort: the port number which will be used on server
|
||||
listenPort: 443
|
||||
# bufferSize: maximum bytes read from a destination at a time in polling mode,
|
||||
# 1-65536 (default: 65536)
|
||||
bufferSize: 65536
|
||||
# tlsCertFile, tlsKeyFile: the server's certificate (PEM, chain allowed) and
|
||||
# private key, used when tlsEnable is true
|
||||
tlsCertFile: "/etc/nipovpn/server.crt"
|
||||
tlsKeyFile: "/etc/nipovpn/server.key"
|
||||
|
||||
# usage: optional per-user usage tracking.
|
||||
# Usage (bytes each user sends and receives) is kept in the usage file, which
|
||||
# you can also edit to change or reset a user's usage (e.g. set "used" to 0).
|
||||
usage:
|
||||
# file: where usage is kept (default: /var/lib/nipovpn/usage.yaml)
|
||||
file: "/var/lib/nipovpn/usage.yaml"
|
||||
# resetDay: day of the month (1-28) on which everyone's usage resets (default: 1)
|
||||
resetDay: 1
|
||||
|
||||
# users: the users allowed to connect.
|
||||
# Each user has their own token, and that user's agent puts the same token in
|
||||
# agent.token. Add, disable or remove users without a
|
||||
# restart: edit this file and run `systemctl reload nipovpn-server`.
|
||||
users:
|
||||
- name: adas
|
||||
# token: at least 32 bytes, unique per user, e.g. `openssl rand -hex 16`
|
||||
token: "b354d990-1d1e-4956-94dd-75adfc692668"
|
||||
# enabled: bool (default: true). false rejects the user and, on reload,
|
||||
# closes their open connections.
|
||||
# limit: optional traffic allowance per month (upload + download), e.g. 2GB,
|
||||
# 500MB or 1.5GiB. When reached, the user is blocked until the next period.
|
||||
enabled: true
|
||||
- name: nokhod
|
||||
token: "4bc22ec2-b29b-4279-acc2-bfa1702e8dec"
|
||||
enabled: true
|
||||
limit: 1GB
|
||||
|
||||
|
||||
# This block is to define agent directives
|
||||
agent:
|
||||
# threads: number of threads in agent
|
||||
threads: 8
|
||||
threads: 16
|
||||
# listenIp: which must be IPv4 which is used on agent
|
||||
listenIp: "0.0.0.0"
|
||||
# listenPort: the port number which will be used on agent
|
||||
listenPort: 8080
|
||||
# protocol: the protocol local applications use to connect to the agent
|
||||
# Choose http or socks5
|
||||
protocol: socks5
|
||||
# fakeUrls: hosts used at random for the Host header and TLS SNI of
|
||||
# the requests the agent sends to the server
|
||||
fakeUrls:
|
||||
- nipo.sudoer.net
|
||||
- sudoer.ir
|
||||
- sudoer.net
|
||||
- google.com
|
||||
- cloudflare.com
|
||||
# methods: HTTP methods used at random for those requests
|
||||
methods:
|
||||
- GET
|
||||
- POST
|
||||
- PUT
|
||||
- DELETE
|
||||
# endPoints: URL paths used at random for those requests
|
||||
endPoints:
|
||||
- api
|
||||
- login
|
||||
- user
|
||||
- update
|
||||
# pullTimeout: base interval in milliseconds between polls in polling mode
|
||||
pullTimeout: 1
|
||||
# connectionReuse: bool
|
||||
# true: send requests to the server over one kept-alive connection
|
||||
# false: open a new connection to the server for each request
|
||||
# The server follows the agent's choice.
|
||||
connectionReuse: true
|
||||
# tlsVerifyPeer: bool. Verify the server's certificate when tlsEnable is true
|
||||
tlsVerifyPeer: false
|
||||
# tlsCaFile: CA file used to verify the server's certificate
|
||||
tlsCaFile: ""
|
||||
# serverIp: IPv4 of the nipoServer
|
||||
serverIp: "127.0.0.10"
|
||||
serverIp: "127.0.0.1"
|
||||
# serverPort: port number of the nipoServer
|
||||
serverPort: 443
|
||||
# httpVersion: This version will be used between agent and server
|
||||
# Supported values are 1.0 or 1.1
|
||||
httpVersion: "1.1"
|
||||
# userAgent: This is the http user agent which will be used between agent and server
|
||||
userAgent : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0"
|
||||
# token: the token this agent sends; it must be the token of an enabled user
|
||||
# in the server's users list. At least 32 bytes. The AES-256-GCM key is derived from it.
|
||||
# Generate one with `openssl rand -hex 16`
|
||||
token: "4bc22ec2-b29b-4279-acc2-bfa1702e8dec"
|
||||
@@ -12,4 +12,3 @@ LimitNOFILE=1048576
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Alias=sshd.service
|
||||
@@ -12,4 +12,3 @@ LimitNOFILE=1048576
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Alias=sshd.service
|
||||
Executable
+101
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
sys.exit("PyYAML is required: pip install pyyaml (or install python-yaml)")
|
||||
|
||||
DEFAULT_CONFIG = "/etc/nipovpn/config.yaml"
|
||||
|
||||
|
||||
def to_str(value):
|
||||
return "" if value is None else str(value)
|
||||
|
||||
|
||||
def to_lines(value):
|
||||
if isinstance(value, (list, tuple)):
|
||||
return "\n".join(str(v) for v in value)
|
||||
return to_str(value)
|
||||
|
||||
|
||||
def build_payload(cfg, name=None, server_ip=None):
|
||||
general = cfg.get("general", {}) or {}
|
||||
log = cfg.get("log", {}) or {}
|
||||
agent = cfg.get("agent", {}) or {}
|
||||
server = cfg.get("server", {}) or {}
|
||||
|
||||
def moved(block, key, default=None):
|
||||
# Settings used by one side moved out of general; general is the deprecated location.
|
||||
return block.get(key, general.get(key, default))
|
||||
|
||||
server_ip = server_ip or to_str(agent.get("serverIp"))
|
||||
config = {
|
||||
# agent.token; general.token is the deprecated location.
|
||||
"token": to_str(agent.get("token") or general.get("token")),
|
||||
"protocol": to_str(moved(agent, "protocol")),
|
||||
"fakeUrls": to_lines(moved(agent, "fakeUrls")),
|
||||
"methods": to_lines(moved(agent, "methods")),
|
||||
"endPoints": to_lines(moved(agent, "endPoints")),
|
||||
"timeout": to_str(general.get("timeout")),
|
||||
"pullTimeout": to_str(moved(agent, "pullTimeout")),
|
||||
"tunnelEnable": bool(general.get("tunnelEnable", False)),
|
||||
"connectionReuse": bool(moved(agent, "connectionReuse", False)),
|
||||
"tlsEnable": bool(general.get("tlsEnable", False)),
|
||||
"tlsVerifyPeer": bool(moved(agent, "tlsVerifyPeer", False)),
|
||||
"tlsCertFile": to_str(moved(server, "tlsCertFile")),
|
||||
"tlsKeyFile": to_str(moved(server, "tlsKeyFile")),
|
||||
"tlsCaFile": to_str(moved(agent, "tlsCaFile")),
|
||||
"logLevel": to_str(log.get("logLevel")),
|
||||
"listenIp": to_str(agent.get("listenIp")),
|
||||
"listenPort": to_str(agent.get("listenPort")),
|
||||
"serverIp": server_ip,
|
||||
"serverPort": to_str(agent.get("serverPort")),
|
||||
"httpVersion": to_str(agent.get("httpVersion")),
|
||||
"userAgent": to_str(agent.get("userAgent")),
|
||||
}
|
||||
return {"name": name or server_ip, "config": config}
|
||||
|
||||
|
||||
def encode(payload):
|
||||
text = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
|
||||
text = text.replace("/", "\\/")
|
||||
return "nipovpn://" + base64.b64encode(text.encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def decode(url):
|
||||
data = url.strip()
|
||||
if data.startswith("nipovpn://"):
|
||||
data = data[len("nipovpn://"):]
|
||||
data += "=" * (-len(data) % 4)
|
||||
return json.loads(base64.b64decode(data).decode("utf-8"))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Convert nipovpn config.yaml to a nipovpn:// URL")
|
||||
parser.add_argument("config", nargs="?", default=DEFAULT_CONFIG,
|
||||
help=f"path to config.yaml (default: {DEFAULT_CONFIG})")
|
||||
parser.add_argument("--name", help="profile name (default: serverIp)")
|
||||
parser.add_argument("--server-ip", help="override agent.serverIp (e.g. the public IP of the server)")
|
||||
parser.add_argument("--decode", metavar="URL", help="decode a nipovpn:// URL and print its JSON")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.decode:
|
||||
print(json.dumps(decode(args.decode), indent=2, ensure_ascii=False))
|
||||
return
|
||||
|
||||
try:
|
||||
with open(args.config, "r", encoding="utf-8") as f:
|
||||
cfg = yaml.safe_load(f) or {}
|
||||
except OSError as e:
|
||||
sys.exit(f"Cannot read {args.config}: {e}")
|
||||
|
||||
print(encode(build_payload(cfg, args.name, args.server_ip)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+866
@@ -0,0 +1,866 @@
|
||||
#!/usr/bin/env python3
|
||||
"""End-to-end tests for NipoVPN.
|
||||
|
||||
Starts a real server and agent on localhost for each test, sends traffic
|
||||
through them with curl and checks that every byte arrives intact.
|
||||
|
||||
python3 tests/e2e.py --binary build/core/nipovpn
|
||||
python3 tests/e2e.py --binary build/core/nipovpn -k matrix # only matching tests
|
||||
python3 tests/e2e.py --binary build/core/nipovpn --list
|
||||
|
||||
Needs: python3 with PyYAML, curl and openssl.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import hashlib
|
||||
import http.server
|
||||
import itertools
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
sys.exit("PyYAML is required: pip install pyyaml (or apt install python3-yaml)")
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SAMPLE_CONFIG = os.path.join(ROOT, "nipovpn", "etc", "nipovpn", "config.yaml")
|
||||
|
||||
CRASH_MARKERS = (
|
||||
"terminate called",
|
||||
"Segmentation fault",
|
||||
"Aborted",
|
||||
"AddressSanitizer",
|
||||
"runtime error:",
|
||||
)
|
||||
|
||||
|
||||
class TestFailure(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def check(condition, message):
|
||||
if not condition:
|
||||
raise TestFailure(message)
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def sha256(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def new_token():
|
||||
return secrets.token_hex(20)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- origin server
|
||||
|
||||
|
||||
class Origin:
|
||||
"""Local web server the traffic is sent to.
|
||||
|
||||
GET /<name> returns a fixed random blob, GET /slow streams the big blob
|
||||
over about 3 seconds, and POST /upload returns the SHA-256
|
||||
of the request body. Accepts absolute-form request targets
|
||||
(GET http://host/path), which an HTTP proxy forwards unchanged.
|
||||
"""
|
||||
|
||||
SIZES = {"small": 64 * 1024, "mid": 512 * 1024, "big": 2 * 1024 * 1024}
|
||||
|
||||
def __init__(self):
|
||||
self.blobs = {name: os.urandom(size) for name, size in self.SIZES.items()}
|
||||
blobs = self.blobs
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def _send(self, status, body):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/octet-stream")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
name = urlsplit(self.path).path.strip("/")
|
||||
if name == "slow":
|
||||
body = blobs["big"]
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
try:
|
||||
for i in range(0, len(body), 64 * 1024):
|
||||
self.wfile.write(body[i:i + 64 * 1024])
|
||||
self.wfile.flush()
|
||||
time.sleep(0.1)
|
||||
except OSError:
|
||||
pass
|
||||
elif name in blobs:
|
||||
self._send(200, blobs[name])
|
||||
else:
|
||||
self._send(404, b"not found")
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
body = self.rfile.read(length)
|
||||
self._send(200, sha256(body).encode())
|
||||
|
||||
self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
self.server.daemon_threads = True
|
||||
self.port = self.server.server_address[1]
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
|
||||
def url(self, name):
|
||||
return f"http://127.0.0.1:{self.port}/{name}"
|
||||
|
||||
def close(self):
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- processes
|
||||
|
||||
|
||||
class Node:
|
||||
"""One nipovpn process (server or agent)."""
|
||||
|
||||
def __init__(self, env, mode, config, name):
|
||||
self.env = env
|
||||
self.mode = mode
|
||||
self.name = name
|
||||
self.config = config
|
||||
self.config_path = os.path.join(env.dir, f"{name}.yaml")
|
||||
self.log_path = config["log"]["logFile"]
|
||||
self.out_path = os.path.join(env.dir, f"{name}.out")
|
||||
self.proc = None
|
||||
self.write_config(config)
|
||||
|
||||
def write_config(self, config):
|
||||
self.config = config
|
||||
tmp = self.config_path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
yaml.safe_dump(config, f, sort_keys=False)
|
||||
os.replace(tmp, self.config_path)
|
||||
|
||||
@property
|
||||
def port(self):
|
||||
return self.config[self.mode]["listenPort"]
|
||||
|
||||
def start(self):
|
||||
open(self.log_path, "a").close()
|
||||
self.out = open(self.out_path, "w")
|
||||
self.proc = subprocess.Popen(
|
||||
[self.env.binary, self.mode, self.config_path],
|
||||
stdout=self.out,
|
||||
stderr=subprocess.STDOUT,
|
||||
start_new_session=True,
|
||||
)
|
||||
self.env.nodes.append(self)
|
||||
deadline = time.time() + 15
|
||||
while time.time() < deadline:
|
||||
if self.proc.poll() is not None:
|
||||
raise TestFailure(f"{self.name} exited at startup:\n{self.output()}")
|
||||
try:
|
||||
with socket.create_connection(("127.0.0.1", self.port), timeout=0.5):
|
||||
return self
|
||||
except OSError:
|
||||
time.sleep(0.05)
|
||||
raise TestFailure(f"{self.name} did not start listening on port {self.port}")
|
||||
|
||||
def alive(self):
|
||||
return self.proc is not None and self.proc.poll() is None
|
||||
|
||||
def send_signal(self, sig):
|
||||
self.proc.send_signal(sig)
|
||||
|
||||
def stop(self):
|
||||
if self.proc is None:
|
||||
return
|
||||
if self.alive():
|
||||
self.proc.send_signal(signal.SIGTERM)
|
||||
try:
|
||||
self.proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.proc.kill()
|
||||
self.proc.wait()
|
||||
self.out.close()
|
||||
|
||||
def output(self):
|
||||
try:
|
||||
with open(self.out_path, errors="replace") as f:
|
||||
return f.read()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
def log(self):
|
||||
try:
|
||||
with open(self.log_path, errors="replace") as f:
|
||||
return f.read()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
def wait_for_log(self, pattern, count=1, timeout=15):
|
||||
regex = re.compile(pattern)
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if len(regex.findall(self.log())) >= count:
|
||||
return
|
||||
time.sleep(0.1)
|
||||
raise TestFailure(f"{self.name} log never showed /{pattern}/ (x{count})")
|
||||
|
||||
def crash_report(self):
|
||||
text = self.output()
|
||||
for marker in CRASH_MARKERS:
|
||||
if marker in text:
|
||||
start = max(0, text.find("ERROR:") if "ERROR:" in text else text.find(marker))
|
||||
return f"{self.name} crashed ({marker}):\n{text[start:start + 6000]}"
|
||||
if self.proc is not None and self.proc.returncode not in (None, 0, -signal.SIGTERM):
|
||||
return f"{self.name} exited with code {self.proc.returncode}:\n{text[-2000:]}"
|
||||
return None
|
||||
|
||||
|
||||
class Env:
|
||||
"""Per-test working directory, configs and processes."""
|
||||
|
||||
def __init__(self, runner, name):
|
||||
self.binary = runner.binary
|
||||
self.origin = runner.origin
|
||||
self.cert, self.key = runner.cert, runner.key
|
||||
self.dir = tempfile.mkdtemp(prefix=re.sub(r"[^A-Za-z0-9]+", "_", name)[:60] + "_",
|
||||
dir=runner.workdir)
|
||||
self.nodes = []
|
||||
with open(SAMPLE_CONFIG) as f:
|
||||
self.sample = yaml.safe_load(f)
|
||||
|
||||
# -- configs
|
||||
|
||||
def base(self, tls=True, tunnel=False, aes=True, reuse=True, protocol="socks5",
|
||||
users=None, agent_token=None):
|
||||
"""A config derived from the shipped sample config."""
|
||||
cfg = copy.deepcopy(self.sample)
|
||||
server_port, agent_port = free_port(), free_port()
|
||||
if users is None:
|
||||
users = [{"name": "alice", "token": new_token(), "enabled": True}]
|
||||
cfg["general"].update(aesEnable=aes, tunnelEnable=tunnel, tlsEnable=tls, timeout=10)
|
||||
cfg["log"]["logLevel"] = "INFO"
|
||||
cfg["server"].update(
|
||||
threads=4,
|
||||
listenIp="127.0.0.1",
|
||||
listenPort=server_port,
|
||||
tlsCertFile=self.cert,
|
||||
tlsKeyFile=self.key,
|
||||
usage={"file": os.path.join(self.dir, "usage.yaml"), "resetDay": 1},
|
||||
users=users,
|
||||
)
|
||||
cfg["agent"].update(
|
||||
threads=8,
|
||||
listenIp="127.0.0.1",
|
||||
listenPort=agent_port,
|
||||
serverIp="127.0.0.1",
|
||||
serverPort=server_port,
|
||||
protocol=protocol,
|
||||
connectionReuse=reuse,
|
||||
tlsVerifyPeer=False,
|
||||
tlsCaFile="",
|
||||
token=agent_token or users[0]["token"],
|
||||
)
|
||||
return cfg
|
||||
|
||||
def server(self, cfg, name="server"):
|
||||
cfg = copy.deepcopy(cfg)
|
||||
cfg["log"]["logFile"] = os.path.join(self.dir, f"{name}.log")
|
||||
return Node(self, "server", cfg, name).start()
|
||||
|
||||
def agent(self, cfg, name="agent", token=None):
|
||||
cfg = copy.deepcopy(cfg)
|
||||
cfg["log"]["logFile"] = os.path.join(self.dir, f"{name}.log")
|
||||
cfg["agent"]["listenPort"] = free_port()
|
||||
if token:
|
||||
cfg["agent"]["token"] = token
|
||||
return Node(self, "agent", cfg, name).start()
|
||||
|
||||
# -- traffic
|
||||
|
||||
def curl(self, agent, url, protocol=None, connect=True, data_file=None, timeout=60):
|
||||
protocol = protocol or agent.config["agent"].get("protocol") or agent.config["general"]["protocol"]
|
||||
cmd = ["curl", "-sS", "--fail", "--max-time", str(timeout), "-o", "-"]
|
||||
if protocol == "socks5":
|
||||
cmd += ["--socks5-hostname", f"127.0.0.1:{agent.port}"]
|
||||
else:
|
||||
cmd += ["-x", f"http://127.0.0.1:{agent.port}"]
|
||||
if connect:
|
||||
cmd.append("-p")
|
||||
if data_file:
|
||||
cmd += ["--data-binary", "@" + data_file, "-H", "Content-Type: application/octet-stream"]
|
||||
cmd.append(url)
|
||||
result = subprocess.run(cmd, capture_output=True, timeout=timeout + 10)
|
||||
return result.returncode, result.stdout, result.stderr.decode(errors="replace").strip()
|
||||
|
||||
@staticmethod
|
||||
def how(agent, kw):
|
||||
protocol = kw.get("protocol") or agent.config["agent"].get("protocol") or agent.config["general"]["protocol"]
|
||||
if protocol == "socks5":
|
||||
return "over SOCKS5"
|
||||
return "over HTTP CONNECT" if kw.get("connect", True) else "as a plain HTTP proxy request"
|
||||
|
||||
def download_ok(self, agent, name="big", **kw):
|
||||
rc, body, err = self.curl(agent, self.origin.url(name), **kw)
|
||||
what = f"download of /{name} {self.how(agent, kw)}"
|
||||
check(rc == 0, f"{what} failed (curl exit {rc}: {err})")
|
||||
check(sha256(body) == sha256(self.origin.blobs[name]),
|
||||
f"{what} corrupted: got {len(body)} bytes, "
|
||||
f"expected {len(self.origin.blobs[name])}")
|
||||
|
||||
def download_fails(self, agent, name="small", **kw):
|
||||
rc, body, _ = self.curl(agent, self.origin.url(name), timeout=15, **kw)
|
||||
check(rc != 0 or sha256(body) != sha256(self.origin.blobs[name]),
|
||||
f"download of /{name} succeeded but should have been refused")
|
||||
|
||||
def upload_ok(self, agent, size=1024 * 1024, **kw):
|
||||
data = os.urandom(size)
|
||||
path = os.path.join(self.dir, f"upload_{secrets.token_hex(4)}.bin")
|
||||
with open(path, "wb") as f:
|
||||
f.write(data)
|
||||
rc, body, err = self.curl(agent, self.origin.url("upload"), data_file=path, **kw)
|
||||
what = f"upload of {size} bytes {self.how(agent, kw)}"
|
||||
check(rc == 0, f"{what} failed (curl exit {rc}: {err})")
|
||||
check(body.decode(errors="replace") == sha256(data), f"{what} corrupted on the way")
|
||||
|
||||
def parallel_downloads_ok(self, agent, count=4, name="mid", **kw):
|
||||
errors = []
|
||||
|
||||
def one():
|
||||
try:
|
||||
self.download_ok(agent, name, **kw)
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
|
||||
threads = [threading.Thread(target=one) for _ in range(count)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
check(not errors, f"{len(errors)} of {count} parallel downloads failed: {errors[0] if errors else ''}")
|
||||
|
||||
def usage(self):
|
||||
path = os.path.join(self.dir, "usage.yaml")
|
||||
check(os.path.exists(path), "usage file was not written")
|
||||
with open(path) as f:
|
||||
doc = yaml.safe_load(f) or {}
|
||||
return {name: entry.get("used", 0) for name, entry in (doc.get("users") or {}).items()}
|
||||
|
||||
# -- teardown
|
||||
|
||||
def close(self):
|
||||
crashes = []
|
||||
for node in reversed(self.nodes):
|
||||
node.stop()
|
||||
report = node.crash_report()
|
||||
if report:
|
||||
crashes.append(report)
|
||||
return crashes
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- tests
|
||||
|
||||
TESTS = []
|
||||
|
||||
|
||||
def test(name):
|
||||
def register(fn):
|
||||
TESTS.append((name, fn))
|
||||
return fn
|
||||
|
||||
return register
|
||||
|
||||
|
||||
def onoff(value):
|
||||
return "on" if value else "off"
|
||||
|
||||
|
||||
def make_matrix_test(tls, tunnel, reuse, aes, protocol):
|
||||
def run(env):
|
||||
cfg = env.base(tls=tls, tunnel=tunnel, reuse=reuse, aes=aes, protocol=protocol)
|
||||
env.server(cfg)
|
||||
agent = env.agent(cfg)
|
||||
if protocol == "socks5":
|
||||
env.download_ok(agent, "big")
|
||||
env.download_ok(agent, "small")
|
||||
env.upload_ok(agent)
|
||||
env.parallel_downloads_ok(agent)
|
||||
else:
|
||||
env.download_ok(agent, "big", connect=True)
|
||||
env.download_ok(agent, "small", connect=True)
|
||||
env.upload_ok(agent, connect=True)
|
||||
env.parallel_downloads_ok(agent, connect=True)
|
||||
|
||||
return run
|
||||
|
||||
|
||||
for _tls, _tunnel, _reuse, _aes, _protocol in itertools.product(
|
||||
(True, False), (False, True), (True, False), (True, False), ("socks5", "http")):
|
||||
TESTS.append((
|
||||
f"matrix tls={onoff(_tls)} tunnel={onoff(_tunnel)} reuse={onoff(_reuse)} "
|
||||
f"aes={onoff(_aes)} protocol={_protocol}",
|
||||
make_matrix_test(_tls, _tunnel, _reuse, _aes, _protocol),
|
||||
))
|
||||
|
||||
|
||||
KNOWN_BUG_PLAIN_HTTP = (
|
||||
"the server returns only its first read (up to 16 KB) from the destination as the "
|
||||
"response to a plain HTTP proxy request; also in 1.1.60")
|
||||
|
||||
for _tunnel, _tls in itertools.product((False, True), (True, False)):
|
||||
def _plain_http_test(env, tunnel=_tunnel, tls=_tls):
|
||||
cfg = env.base(tls=tls, tunnel=tunnel, protocol="http")
|
||||
env.server(cfg)
|
||||
agent = env.agent(cfg)
|
||||
env.download_ok(agent, "small", connect=False)
|
||||
env.download_ok(agent, "big", connect=False)
|
||||
env.upload_ok(agent, connect=False)
|
||||
|
||||
_plain_http_test.known_bug = KNOWN_BUG_PLAIN_HTTP
|
||||
TESTS.append((f"plain HTTP proxy request tls={onoff(_tls)} tunnel={onoff(_tunnel)}",
|
||||
_plain_http_test))
|
||||
|
||||
|
||||
@test("http version 1.0 between agent and server")
|
||||
def _(env):
|
||||
for tunnel in (False, True):
|
||||
cfg = env.base(tunnel=tunnel)
|
||||
cfg["agent"]["httpVersion"] = "1.0"
|
||||
env.server(cfg, name=f"server_{tunnel}")
|
||||
agent = env.agent(cfg, name=f"agent_{tunnel}")
|
||||
env.download_ok(agent)
|
||||
env.upload_ok(agent)
|
||||
|
||||
|
||||
def two_users(env, **kw):
|
||||
users = [
|
||||
{"name": "alice", "token": new_token(), "enabled": True},
|
||||
{"name": "bob", "token": new_token(), "enabled": True},
|
||||
]
|
||||
return env.base(users=users, **kw), users
|
||||
|
||||
|
||||
for _aes, _tunnel in itertools.product((True, False), (False, True)):
|
||||
def _users_test(env, aes=_aes, tunnel=_tunnel):
|
||||
cfg, users = two_users(env, aes=aes, tunnel=tunnel)
|
||||
server = env.server(cfg)
|
||||
alice = env.agent(cfg, name="agent_alice", token=users[0]["token"])
|
||||
bob = env.agent(cfg, name="agent_bob", token=users[1]["token"])
|
||||
|
||||
errors = []
|
||||
|
||||
def traffic(agent, name):
|
||||
try:
|
||||
env.download_ok(agent, name)
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
|
||||
threads = [threading.Thread(target=traffic, args=(bob, "big")),
|
||||
threading.Thread(target=traffic, args=(bob, "mid")),
|
||||
threading.Thread(target=traffic, args=(alice, "small"))]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
check(not errors, f"traffic of two users at once failed: {errors}")
|
||||
|
||||
server.stop()
|
||||
log = server.log()
|
||||
check("[USER alice]" in log and "[USER bob]" in log,
|
||||
"server log does not name both users")
|
||||
used = env.usage()
|
||||
big = len(env.origin.blobs["big"]) + len(env.origin.blobs["mid"])
|
||||
check(used.get("bob", 0) >= big, f"bob's usage {used.get('bob')} < {big} bytes downloaded")
|
||||
check(0 < used.get("alice", 0) < big,
|
||||
f"alice's usage {used.get('alice')} does not match her small download")
|
||||
|
||||
TESTS.append((f"users identified and counted aes={onoff(_aes)} tunnel={onoff(_tunnel)}",
|
||||
_users_test))
|
||||
|
||||
|
||||
for _aes in (True, False):
|
||||
def _unknown_test(env, aes=_aes):
|
||||
cfg = env.base(aes=aes)
|
||||
server = env.server(cfg)
|
||||
stranger = env.agent(cfg, name="agent_unknown", token=new_token())
|
||||
env.download_fails(stranger)
|
||||
check(server.alive(), "server died after an unknown token")
|
||||
good = env.agent(cfg, name="agent_alice")
|
||||
env.download_ok(good, "small")
|
||||
|
||||
TESTS.append((f"unknown token refused aes={onoff(_aes)}", _unknown_test))
|
||||
|
||||
|
||||
@test("disabled user refused")
|
||||
def _(env):
|
||||
cfg, users = two_users(env)
|
||||
users[1]["enabled"] = False
|
||||
env.server(cfg)
|
||||
env.download_fails(env.agent(cfg, name="agent_bob", token=users[1]["token"]))
|
||||
env.download_ok(env.agent(cfg, name="agent_alice", token=users[0]["token"]), "small")
|
||||
|
||||
|
||||
@test("reload disables and re-enables a user")
|
||||
def _(env):
|
||||
cfg, users = two_users(env)
|
||||
server = env.server(cfg)
|
||||
bob = env.agent(cfg, name="agent_bob", token=users[1]["token"])
|
||||
alice = env.agent(cfg, name="agent_alice", token=users[0]["token"])
|
||||
env.download_ok(bob, "small")
|
||||
|
||||
users[1]["enabled"] = False
|
||||
server.write_config(server.config | {"server": cfg["server"]})
|
||||
server.send_signal(signal.SIGHUP)
|
||||
server.wait_for_log(r"config reloaded.*access revoked for: bob")
|
||||
env.download_fails(bob)
|
||||
env.download_ok(alice, "small")
|
||||
|
||||
users[1]["enabled"] = True
|
||||
server.write_config(server.config | {"server": cfg["server"]})
|
||||
server.send_signal(signal.SIGHUP)
|
||||
server.wait_for_log(r"config reloaded", count=2)
|
||||
env.download_ok(bob, "small")
|
||||
|
||||
|
||||
@test("reload revokes a user in the middle of a download")
|
||||
def _(env):
|
||||
for tunnel in (False, True):
|
||||
cfg, users = two_users(env, tunnel=tunnel)
|
||||
server = env.server(cfg, name=f"server_{tunnel}")
|
||||
bob = env.agent(cfg, name=f"agent_bob_{tunnel}", token=users[1]["token"])
|
||||
result = {}
|
||||
|
||||
def slow_download():
|
||||
result["rc"], result["body"], _ = env.curl(bob, env.origin.url("slow"), timeout=60)
|
||||
|
||||
t = threading.Thread(target=slow_download)
|
||||
t.start()
|
||||
time.sleep(0.8)
|
||||
users[1]["enabled"] = False
|
||||
server.write_config(server.config | {"server": cfg["server"]})
|
||||
server.send_signal(signal.SIGHUP)
|
||||
server.wait_for_log(r"access revoked for: bob")
|
||||
t.join()
|
||||
check(result.get("rc") != 0 or len(result.get("body", b"")) < len(env.origin.blobs["big"]),
|
||||
f"tunnel={onoff(tunnel)}: the download continued after bob was revoked")
|
||||
env.download_fails(bob)
|
||||
|
||||
|
||||
@test("reload with an invalid config keeps the old one")
|
||||
def _(env):
|
||||
cfg = env.base()
|
||||
server = env.server(cfg)
|
||||
agent = env.agent(cfg)
|
||||
with open(server.config_path, "w") as f:
|
||||
f.write("general: [this is: not valid\n")
|
||||
server.send_signal(signal.SIGHUP)
|
||||
server.wait_for_log(r"config not reloaded")
|
||||
check(server.alive(), "server died on an invalid reload")
|
||||
env.download_ok(agent, "small")
|
||||
|
||||
|
||||
for _tunnel in (False, True):
|
||||
def _limit_test(env, tunnel=_tunnel):
|
||||
cfg, users = two_users(env, tunnel=tunnel)
|
||||
users[1]["limit"] = "1MB"
|
||||
server = env.server(cfg)
|
||||
bob = env.agent(cfg, name="agent_bob", token=users[1]["token"])
|
||||
alice = env.agent(cfg, name="agent_alice", token=users[0]["token"])
|
||||
|
||||
rc, body, _ = env.curl(bob, env.origin.url("big"), timeout=30)
|
||||
check(rc != 0 or len(body) < len(env.origin.blobs["big"]),
|
||||
"bob downloaded 2 MB despite a 1MB limit")
|
||||
server.wait_for_log(r"user bob reached their limit")
|
||||
env.download_fails(bob)
|
||||
env.download_ok(alice, "small")
|
||||
|
||||
users[1]["limit"] = "100MB"
|
||||
server.write_config(server.config | {"server": cfg["server"]})
|
||||
server.send_signal(signal.SIGHUP)
|
||||
server.wait_for_log(r"user bob is below their limit again")
|
||||
env.download_ok(bob, "small")
|
||||
|
||||
TESTS.append((f"usage limit blocks and reload unblocks tunnel={onoff(_tunnel)}", _limit_test))
|
||||
|
||||
|
||||
@test("usage survives a server restart")
|
||||
def _(env):
|
||||
cfg = env.base()
|
||||
server = env.server(cfg)
|
||||
agent = env.agent(cfg)
|
||||
env.download_ok(agent, "big")
|
||||
server.stop()
|
||||
first = env.usage().get("alice", 0)
|
||||
check(first >= len(env.origin.blobs["big"]), f"usage {first} lower than the download")
|
||||
|
||||
server = env.server(cfg, name="server2")
|
||||
env.download_ok(agent, "small")
|
||||
server.stop()
|
||||
second = env.usage().get("alice", 0)
|
||||
check(second >= first + len(env.origin.blobs["small"]),
|
||||
f"usage went from {first} to {second}; the restart lost it")
|
||||
|
||||
|
||||
def legacy_config(env, aes=True, tunnel=False, token=True):
|
||||
"""The 1.1.x layout: everything shared in general, one general.token."""
|
||||
cfg = env.base(aes=aes, tunnel=tunnel)
|
||||
legacy = copy.deepcopy(cfg)
|
||||
for key in ("protocol", "fakeUrls", "methods", "endPoints", "pullTimeout",
|
||||
"connectionReuse", "tlsVerifyPeer", "tlsCaFile"):
|
||||
if key in legacy["agent"]:
|
||||
legacy["general"][key] = legacy["agent"].pop(key)
|
||||
for key in ("bufferSize", "tlsCertFile", "tlsKeyFile"):
|
||||
if key in legacy["server"]:
|
||||
legacy["general"][key] = legacy["server"].pop(key)
|
||||
agent_token = legacy["agent"].pop("token")
|
||||
legacy["server"].pop("users")
|
||||
legacy["server"].pop("usage")
|
||||
if token:
|
||||
legacy["general"]["token"] = agent_token
|
||||
return legacy, agent_token
|
||||
|
||||
|
||||
for _aes, _tunnel in itertools.product((True, False), (False, True)):
|
||||
def _legacy_test(env, aes=_aes, tunnel=_tunnel):
|
||||
cfg, _ = legacy_config(env, aes=aes, tunnel=tunnel)
|
||||
server = env.server(cfg)
|
||||
agent = env.agent(cfg)
|
||||
env.download_ok(agent, "big")
|
||||
env.upload_ok(agent)
|
||||
check("moved out of general" in server.log(), "server did not warn about the old layout")
|
||||
check("moved out of general" in agent.log(), "agent did not warn about the old layout")
|
||||
check("general.token is deprecated" in agent.log(), "agent did not warn about general.token")
|
||||
|
||||
TESTS.append((f"1.1.x config layout still works aes={onoff(_aes)} tunnel={onoff(_tunnel)}",
|
||||
_legacy_test))
|
||||
|
||||
|
||||
@test("aes off server without users or token")
|
||||
def _(env):
|
||||
cfg, token = legacy_config(env, aes=False, token=False)
|
||||
env.server(cfg)
|
||||
agent_cfg = copy.deepcopy(cfg)
|
||||
agent_cfg["agent"]["token"] = token
|
||||
agent = env.agent(agent_cfg)
|
||||
env.download_ok(agent, "big")
|
||||
env.upload_ok(agent)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- validation
|
||||
|
||||
|
||||
def mutate(path, value):
|
||||
def apply(cfg):
|
||||
node = cfg
|
||||
for key in path[:-1]:
|
||||
node = node[key]
|
||||
if value is DELETE:
|
||||
node.pop(path[-1], None)
|
||||
else:
|
||||
node[path[-1]] = value
|
||||
|
||||
return apply
|
||||
|
||||
|
||||
DELETE = object()
|
||||
|
||||
VALIDATION_CASES = [
|
||||
("server", mutate(("server", "bufferSize"), 70000), "server.bufferSize must be between 1 and 65536"),
|
||||
("server", mutate(("server", "bufferSize"), 0), "server.bufferSize must be between 1 and 65536"),
|
||||
("agent", mutate(("agent", "protocol"), "ftp"), "agent.protocol must be one of"),
|
||||
("agent", mutate(("agent", "fakeUrls"), {"a": 1}), "Error in agent.fakeUrls"),
|
||||
("agent", mutate(("agent", "token"), "short"), "agent.token must be at least 32 bytes"),
|
||||
("agent", mutate(("agent", "token"), DELETE), "agent.token is required"),
|
||||
("server", mutate(("log", "logLevel"), "LOUD"), "logLevel must be one of"),
|
||||
("server", mutate(("server", "users"), []), "server.users must have at least one entry"),
|
||||
("server", mutate(("server", "users"), "alice"), "server.users must be a list"),
|
||||
("server", mutate(("server", "users"), [{"name": "bad name!", "token": "x" * 40}]),
|
||||
"name must be 1-64 characters"),
|
||||
("server", mutate(("server", "users"), [{"name": "a", "token": "short"}]),
|
||||
"token of user a must be at least"),
|
||||
("server", mutate(("server", "users"), [{"name": "a", "token": "x" * 40},
|
||||
{"name": "a", "token": "y" * 40}]),
|
||||
"user name a is used more than once"),
|
||||
("server", mutate(("server", "users"), [{"name": "a", "token": "x" * 40},
|
||||
{"name": "b", "token": "x" * 40}]),
|
||||
"have the same token"),
|
||||
("server", mutate(("server", "users"), [{"name": "a", "token": "x" * 40, "limit": "2048"}]),
|
||||
"limit must be a size with a unit"),
|
||||
("server", mutate(("server", "usage"), {"resetDay": 40}), "resetDay must be between 1 and 28"),
|
||||
]
|
||||
|
||||
|
||||
def _validation_test(env):
|
||||
failures = []
|
||||
for mode, apply, expected in VALIDATION_CASES:
|
||||
cfg = env.base()
|
||||
cfg["log"]["logFile"] = os.path.join(env.dir, "validation.log")
|
||||
apply(cfg)
|
||||
path = os.path.join(env.dir, "invalid.yaml")
|
||||
with open(path, "w") as f:
|
||||
yaml.safe_dump(cfg, f, sort_keys=False)
|
||||
open(cfg["log"]["logFile"], "a").close()
|
||||
try:
|
||||
result = subprocess.run([env.binary, mode, path], capture_output=True, timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
failures.append(f"{mode}: expected '{expected}' but the program started")
|
||||
continue
|
||||
output = (result.stdout + result.stderr).decode(errors="replace")
|
||||
if result.returncode == 0 or expected not in output:
|
||||
failures.append(f"{mode}: expected '{expected}', got exit {result.returncode}: "
|
||||
f"{output.strip()[-300:]}")
|
||||
|
||||
for mode, text, expected in [
|
||||
("server", "users:\n - name: a\n", "users belongs under the server block"),
|
||||
("server", "general: [broken\n", "Error parsing config file"),
|
||||
]:
|
||||
cfg = env.base()
|
||||
cfg["log"]["logFile"] = os.path.join(env.dir, "validation.log")
|
||||
path = os.path.join(env.dir, "invalid.yaml")
|
||||
with open(path, "w") as f:
|
||||
if text.startswith("users"):
|
||||
yaml.safe_dump(cfg, f, sort_keys=False)
|
||||
f.write(text)
|
||||
result = subprocess.run([env.binary, mode, path], capture_output=True, timeout=10)
|
||||
output = (result.stdout + result.stderr).decode(errors="replace")
|
||||
if result.returncode == 0 or expected not in output:
|
||||
failures.append(f"{mode}: expected '{expected}', got exit {result.returncode}: "
|
||||
f"{output.strip()[-300:]}")
|
||||
|
||||
check(not failures, "\n".join(failures))
|
||||
|
||||
|
||||
TESTS.append(("invalid configs are rejected with a clear message", _validation_test))
|
||||
|
||||
|
||||
@test("sample config passes validation")
|
||||
def _(env):
|
||||
for mode in ("server", "agent"):
|
||||
cfg = copy.deepcopy(env.sample)
|
||||
cfg["log"]["logFile"] = os.path.join(env.dir, "sample.log")
|
||||
cfg["server"]["usage"] = {"file": os.path.join(env.dir, "usage.yaml")}
|
||||
cfg["server"]["listenIp"], cfg["server"]["listenPort"] = "127.0.0.1", free_port()
|
||||
cfg["agent"]["listenIp"], cfg["agent"]["listenPort"] = "127.0.0.1", free_port()
|
||||
cfg["server"]["tlsCertFile"], cfg["server"]["tlsKeyFile"] = env.cert, env.key
|
||||
node = Node(env, mode, cfg, f"sample_{mode}")
|
||||
node.start()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- runner
|
||||
|
||||
|
||||
class Runner:
|
||||
def __init__(self, args):
|
||||
self.binary = os.path.abspath(args.binary)
|
||||
if not os.access(self.binary, os.X_OK):
|
||||
sys.exit(f"{self.binary} is not an executable")
|
||||
for tool in ("curl", "openssl"):
|
||||
if not shutil.which(tool):
|
||||
sys.exit(f"{tool} is required")
|
||||
self.workdir = tempfile.mkdtemp(prefix="nipovpn-e2e-")
|
||||
self.artifacts = args.artifacts
|
||||
self.cert = os.path.join(self.workdir, "server.crt")
|
||||
self.key = os.path.join(self.workdir, "server.key")
|
||||
subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
|
||||
"-keyout", self.key, "-out", self.cert, "-days", "2",
|
||||
"-subj", "/CN=nipovpn-test"], check=True, capture_output=True)
|
||||
self.origin = Origin()
|
||||
|
||||
def run(self, tests):
|
||||
passed, failed, known, fixed = [], [], [], []
|
||||
started = time.time()
|
||||
for index, (name, fn) in enumerate(tests, 1):
|
||||
env = Env(self, name)
|
||||
t0 = time.time()
|
||||
error = None
|
||||
try:
|
||||
fn(env)
|
||||
except TestFailure as e:
|
||||
error = str(e)
|
||||
except Exception:
|
||||
error = traceback.format_exc()
|
||||
crashes = env.close()
|
||||
if crashes:
|
||||
error = (error + "\n" if error else "") + "\n".join(crashes)
|
||||
duration = time.time() - t0
|
||||
known_bug = getattr(fn, "known_bug", None)
|
||||
if known_bug and error is not None and not crashes:
|
||||
status = "KNOWN BUG"
|
||||
elif known_bug and error is None:
|
||||
status = "FIXED?"
|
||||
else:
|
||||
status = "PASS" if error is None else "FAIL"
|
||||
print(f"[{index:>2}/{len(tests)}] {status} {name} ({duration:.1f}s)", flush=True)
|
||||
if status == "KNOWN BUG":
|
||||
known.append(name)
|
||||
print(f" {known_bug}\n {error.splitlines()[0]}", flush=True)
|
||||
shutil.rmtree(env.dir, ignore_errors=True)
|
||||
elif status == "FIXED?":
|
||||
fixed.append(name)
|
||||
print(" passes now: remove its known_bug marker", flush=True)
|
||||
shutil.rmtree(env.dir, ignore_errors=True)
|
||||
elif error is None:
|
||||
passed.append(name)
|
||||
shutil.rmtree(env.dir, ignore_errors=True)
|
||||
else:
|
||||
failed.append(name)
|
||||
print(" " + error.replace("\n", "\n "), flush=True)
|
||||
if self.artifacts:
|
||||
dest = os.path.join(self.artifacts, os.path.basename(env.dir))
|
||||
shutil.copytree(env.dir, dest, dirs_exist_ok=True)
|
||||
|
||||
print(f"\n{len(passed)} passed, {len(failed)} failed, {len(known)} known bugs, "
|
||||
f"{len(fixed)} known bugs passing in {time.time() - started:.0f}s")
|
||||
for name in failed:
|
||||
print(f" FAILED: {name}")
|
||||
self.origin.close()
|
||||
if not failed:
|
||||
shutil.rmtree(self.workdir, ignore_errors=True)
|
||||
return not failed
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--binary", default=os.path.join(ROOT, "build", "core", "nipovpn"),
|
||||
help="nipovpn binary to test (default: build/core/nipovpn)")
|
||||
parser.add_argument("-k", dest="filter", action="append", default=[],
|
||||
help="run only tests whose name contains this text (repeatable)")
|
||||
parser.add_argument("--list", action="store_true", help="list tests and exit")
|
||||
parser.add_argument("--artifacts", help="copy logs and configs of failed tests here")
|
||||
args = parser.parse_args()
|
||||
|
||||
tests = [(n, f) for n, f in TESTS if not args.filter or any(k in n for k in args.filter)]
|
||||
if args.list:
|
||||
for name, _ in tests:
|
||||
print(name)
|
||||
return
|
||||
if not tests:
|
||||
sys.exit("no tests match")
|
||||
sys.exit(0 if Runner(args).run(tests) else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user