Add users usage control

This commit is contained in:
Morteza Bashsiz committed 2026-11-21 19:13:14 +01:00
1 parent 87fc8a3f3c
commit f1ae8d598c
20 files changed
+636 -114

No files matched your search

+93 -21
View File
@@ -78,6 +78,8 @@ 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
@@ -191,14 +193,15 @@ tokens from the shipped config.
openssl rand -hex 16 # prints 32 hex characters
```
On the server, list it in `users`. On that person's machine, put the same
token in `agent.token`:
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
users: agent:
- name: alice token: "<alice's token>"
token: "<alice's token>"
# server config # agent config
server: agent:
users: token: "<alice's token>"
- name: alice
token: "<alice's token>"
```
### 3. TLS certificate (if `tlsEnable: true`)
@@ -296,7 +299,7 @@ Settings marked **must match** have to be the same on agent and server.
| `userAgent` | `NipoAgent` | `User-Agent` header in decoy requests. |
| `token` | — | The token this agent sends, ≥ 32 bytes when `aesEnable` is on. Must be the token of an enabled user on the server. The AES key is derived from it. |
### `users` (server only)
### `server.users`
The users allowed to connect, each with their own token. Required on the server
when `aesEnable` is on. Agents do not use this block.
@@ -306,18 +309,28 @@ when `aesEnable` is on. Agents do not use this block.
| `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 `users`:
Every person gets their own token. The **server** lists them all in
`server.users`:
```yaml
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
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
@@ -330,10 +343,10 @@ everyone.
- 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 `users`
`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 `users` list. Agents of any version
`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
@@ -343,6 +356,61 @@ To add, disable or remove a user, edit the config and [reload](#reloading-the-co
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:
@@ -363,7 +431,7 @@ down. A successful reload logs a summary, for example:
```
New requests use the new settings at once. These settings only change on
restart: `listenIp`, `listenPort`, `threads` and `tlsEnable`. If you change
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.
@@ -396,7 +464,7 @@ Log lines look like:
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 `users` list, or `default`
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.
@@ -416,10 +484,14 @@ journalctl -u nipovpn-server.service -f
| `Configuration validation failed: ...` | A required key is missing or invalid; the message names the block. |
| `agent.token must be at least 32 bytes when aesEnable is true` | 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. With a `users` list: the agent's token is not an enabled user's token. |
| 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 users list with at least one user` | Add a `users` list to the server config. |
| `[WARNING] general.token is deprecated` | Move the token to `agent.token` (agent) or a `users` entry (server). |
| `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). |
| `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. |
| `users require general.aesEnable: true` | Users are told apart by their AES key; turn on `aesEnable`. |
| `[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. |
+2
View File
@@ -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
)
-1
View File
@@ -9,7 +9,6 @@
#include "log.hpp"
#include "tcpclient.hpp"
class AgentHandler : private Uncopyable {
public:
using pointer = std::shared_ptr<AgentHandler>;
+24 -11
View File
@@ -1,6 +1,5 @@
#include "config.hpp"
namespace {
std::string trimNewlines(std::string s) {
while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) s.pop_back();
@@ -12,7 +11,6 @@ std::unique_ptr<Config::Settings> Config::load(RunMode mode, const std::string &
const YAML::Node yaml = YAML::LoadFile(filePath);
auto s = std::make_unique<Settings>();
// Deprecated: the token used to live in general.
const std::string legacyToken = yaml["general"]["token"].as<std::string>("");
s->general = {yaml["general"]["protocol"].as<std::string>(""),
@@ -50,21 +48,25 @@ std::unique_ptr<Config::Settings> Config::load(RunMode mode, const std::string &
}
if (mode == RunMode::server) {
const YAML::Node users = yaml["users"];
s->usageFile = yaml["server"]["usage"]["file"].as<std::string>("/var/lib/nipovpn/usage.yaml");
s->usageResetDay = yaml["server"]["usage"]["resetDay"].as<int>(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>();
s->users.push_back({u["name"].as<std::string>(), token,
deriveAesKey(token), u["enabled"].as<bool>(true)});
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 {
// No users list: accept the deprecated general.token as one user.
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 users list instead");
"put the token in a server.users list instead");
}
}
}
@@ -126,7 +128,6 @@ Config::ReloadResult Config::reload() {
const Settings &prev = current();
std::vector<std::string> notes;
// Keep settings that are only applied at startup, and say so.
auto keep = [&notes](auto &field, const auto &old, const char *name) {
if (field != old) {
notes.push_back(std::string(name) + " changed but needs a restart");
@@ -142,10 +143,9 @@ Config::ReloadResult Config::reload() {
keep(next->agent.listenPort, prev.agent.listenPort, "agent.listenPort");
keep(next->agent.threads, prev.agent.threads, "agent.threads");
}
// Open connections are bound to TLS or plain TCP at accept time.
keep(next->usageFile, prev.usageFile, "usage.file");
keep(next->general.tlsEnable, prev.general.tlsEnable, "general.tlsEnable");
// A user loses access when they disappear, are disabled, or get a new token.
std::vector<std::string> revoked;
for (const auto &old: prev.users) {
if (!old.enabled) continue;
@@ -260,7 +260,8 @@ std::string Config::toString() const {
if (runMode_ == RunMode::server && cur.usersFromFile) {
ss << " Users :\n";
for (const auto &u: cur.users) {
ss << " " << u.name << (u.enabled ? "" : " (disabled)") << "\n";
ss << " " << u.name << (u.enabled ? "" : " (disabled)")
<< (u.limit ? " limit " + formatBytes(u.limit) : std::string()) << "\n";
}
}
@@ -291,6 +292,18 @@ 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 {
std::lock_guard<std::mutex> lock(configMutex_);
return threads_;
+8 -16
View File
@@ -3,6 +3,7 @@
#include <yaml-cpp/yaml.h>
#include <atomic>
#include <cstdint>
#include <memory>
#include <mutex>
#include <random>
@@ -17,13 +18,12 @@ enum class RunMode {
agent
};
// A server-side user. Users are told apart by their token: the server tries
// each enabled user's key until one authenticates the request.
struct User {
std::string name;
std::string token;
std::string key;// deriveAesKey(token), computed once at load time
std::string key;
bool enabled;
std::uint64_t limit = 0;
};
class Config : private Uncopyable {
@@ -65,30 +65,24 @@ public:
unsigned short serverPort;
std::string httpVersion;
std::string userAgent;
// The token this agent sends. On the server it must belong to an
// enabled user.
std::string token;
};
// Everything read from the config file. A snapshot is never modified
// after it is published.
struct Settings {
General general;
Log log;
Server server;
Agent agent;
// Server mode only. Without a users list in the file this holds one
// user named "default" with the deprecated general.token.
std::vector<User> users;
bool usersFromFile = false;
// Deprecated settings found in the file, to be logged.
std::string usageFile;
int usageResetDay = 1;
std::vector<std::string> warnings;
};
struct ReloadResult {
bool ok;
std::string message;
// Users whose access ended: removed, disabled, or given a new token.
std::vector<std::string> revokedUsers;
};
@@ -100,18 +94,16 @@ public:
~Config();
// These return references into the current snapshot. Snapshots are kept
// for the life of the process, so the references stay valid after a
// reload; they just stop being current.
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;
// Re-reads the config file. On any error the running config is kept.
// listenIp, listenPort, threads and tlsEnable only change on restart.
ReloadResult reload();
unsigned short threads() const;
+97 -13
View File
@@ -14,6 +14,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,7 +197,6 @@ inline std::string deriveAesKey(const std::string &token) {
return std::string(reinterpret_cast<char *>(digest), digestLen);
}
// key is a 32-byte AES-256 key, normally deriveAesKey(token).
inline BoolStr aes256EncryptWithKey(const std::string &plaintext,
const std::string &key) {
BoolStr result{false, "Encryption failed"};
@@ -256,7 +256,6 @@ inline BoolStr aes256EncryptWithKey(const std::string &plaintext,
return result;
}
// key is a 32-byte AES-256 key, normally deriveAesKey(token).
inline BoolStr aes256DecryptWithKey(const std::string &sealed,
const std::string &key) {
BoolStr result{false, "Decryption failed"};
@@ -351,6 +350,69 @@ inline bool parseEnvelope(const std::string &raw, Envelope &out) {
return true;
}
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) {
@@ -362,8 +424,6 @@ inline bool isValidUserName(const std::string &name) {
return true;
}
// Validates a config file for mode "server" or "agent". Used at startup and
// on every reload, so a bad file never replaces a running config.
inline BoolStr validateConfigFile(const std::string &mode, const std::string &path) {
BoolStr result{false, "Validation failed"};
@@ -454,11 +514,17 @@ inline BoolStr validateConfigFile(const std::string &mode, const std::string &pa
result.message = std::string("Error in agent.token: ") + e.what() + "\n";
return result;
}
// Deprecated location, still read so existing configs keep working.
const std::string legacyToken = configYaml["general"]["token"].as<std::string>("");
// The agent sends agent.token; the server accepts the tokens in users.
const YAML::Node users = configYaml["users"];
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") {
@@ -473,16 +539,16 @@ inline BoolStr validateConfigFile(const std::string &mode, const std::string &pa
}
} else if (serverUsers) {
if (!users.IsSequence()) {
result.message = "users must be a list\n";
result.message = "server.users must be a list\n";
return result;
}
if (users.size() == 0) {
result.message = "users must have at least one entry\n";
result.message = "server.users must have at least one entry\n";
return result;
}
if (!aesEnable) {
result.message =
"users require general.aesEnable: true; the server tells users apart by their AES key\n";
"server.users require general.aesEnable: true; the server tells users apart by their AES key\n";
return result;
}
@@ -490,7 +556,7 @@ inline BoolStr validateConfigFile(const std::string &mode, const std::string &pa
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 = "users[" + std::to_string(i) + "]";
const std::string where = "server.users[" + std::to_string(i) + "]";
std::string name;
std::string userToken;
try {
@@ -498,6 +564,13 @@ inline BoolStr validateConfigFile(const std::string &mode, const std::string &pa
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;
@@ -526,10 +599,21 @@ inline BoolStr validateConfigFile(const std::string &mode, const std::string &pa
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) {
// A server without users: only the deprecated general.token remains.
if (legacyToken.empty()) {
result.message = "the server needs a users list with at least one user\n";
result.message = "the server needs a server.users list with at least one user\n";
return result;
}
if (legacyToken.size() < MinTokenLength) {
-3
View File
@@ -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;
@@ -186,7 +184,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,
-1
View File
@@ -55,7 +55,6 @@ void Log::write(const std::string &message, Level level) const {
if (logFile.is_open()) {
auto now = std::time(nullptr);
auto localTime = *std::localtime(&now);
-1
View File
@@ -34,7 +34,6 @@ public:
Level level() const { return level_.load(); }
// Applies log.logLevel from the current config (used after a reload).
void applyConfigLevel();
void write(const std::string &message, Level level) const;
+64 -2
View File
@@ -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),
@@ -8,7 +10,9 @@ Runner::Runner(const std::shared_ptr<Config> &config,
work_guard_(boost::asio::make_work_guard(io_context_)),
running_(true),
strand_(boost::asio::make_strand(io_context_)),
signals_(io_context_) {}
signals_(io_context_),
stopSignals_(io_context_),
usageTimer_(io_context_) {}
Runner::~Runner() {
running_.store(false);
@@ -31,6 +35,8 @@ void Runner::run() {
auto tcpServer = TCPServer::create(io_context_, config_, log_);
waitForReloadSignal();
waitForStopSignal();
startUsage();
for (auto i = 0; i < config_->threads(); ++i) {
threadPool_.emplace_back([this] { workerThread(); });
@@ -105,7 +111,7 @@ void Runner::waitForReloadSignal() {
}
signals_.async_wait([this](const boost::system::error_code &error, int) {
if (error) return;// operation_aborted on shutdown
if (error) return;
reload();
waitForReloadSignal();
});
@@ -125,6 +131,11 @@ void Runner::reload() {
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);
@@ -134,3 +145,54 @@ void Runner::reload() {
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();
});
}
+9 -2
View File
@@ -4,6 +4,7 @@
#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>
@@ -33,14 +34,18 @@ private:
void stop();
// Re-reads the config file (on SIGHUP) and closes connections of users
// who lost access.
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_;
@@ -55,4 +60,6 @@ private:
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_;
};
+16 -3
View File
@@ -5,6 +5,7 @@
#include <vector>
#include "http_utils.hpp"
#include "usage.hpp"
std::mutex ServerHandler::sessionsMutex_;
std::unordered_map<std::string, ServerHandler::Session> ServerHandler::sessions_;
@@ -73,7 +74,6 @@ BoolStr ServerHandler::authenticate(const std::string &payload) {
const std::vector<User> &users = config_->users();
if (!config_->general().aesEnable) {
// Only possible without a users list: the single "default" user.
user_ = users.empty() ? nullptr : &users.front();
return {true, payload};
}
@@ -89,7 +89,6 @@ BoolStr ServerHandler::authenticate(const std::string &payload) {
return true;
};
// Most requests on a connection come from the same user.
if (!userHint_.empty()) {
for (const auto &u: users) {
if (u.name == userHint_) {
@@ -198,6 +197,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(
@@ -236,6 +244,7 @@ void ServerHandler::handle() {
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"));
@@ -277,6 +286,8 @@ void ServerHandler::handle() {
return;
}
Usage::instance().add(usage_, n);
makePayloadHttpResponse(
std::string(data.data(), n),
"200 OK",
@@ -404,6 +415,7 @@ void ServerHandler::handle() {
if (!pendingTunnelData.empty()) {
boost::asio::streambuf pendingBuf;
copyStringToStreambuf(pendingTunnelData, pendingBuf);
Usage::instance().add(usage_, pendingBuf.size());
targetClient->doWrite(pendingBuf);
}
@@ -412,7 +424,6 @@ void ServerHandler::handle() {
const std::string key = session.empty() ? to_string(uuid_) : session;
auto it = sessions_.find(key);
// Never let one user take over another user's session.
if (it != sessions_.end() && it->second.user != userName()) {
targetClient->socketShutdown();
makePayloadHttpResponse("", "403 Forbidden", "close");
@@ -444,8 +455,10 @@ 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();
+2 -6
View File
@@ -11,6 +11,7 @@
#include "http.hpp"
#include "log.hpp"
#include "tcpclient.hpp"
#include "usage.hpp"
class ServerHandler : private Uncopyable {
public:
@@ -27,10 +28,8 @@ public:
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log, client, clientConnStr, uuid, userHint));
}
// Closes the polling-mode sessions of these users. Returns how many.
static std::size_t revokeSessions(const std::vector<std::string> &users);
// The user who sent the request, or empty if it was not authenticated.
std::string userName() const { return user_ ? user_->name : std::string(); }
~ServerHandler();
@@ -59,10 +58,8 @@ private:
boost::uuids::uuid uuid,
std::string &userHint);
// Finds the user whose key authenticates payload and decrypts it.
BoolStr authenticate(const std::string &payload);
// "<client address>] [USER <name>" for log lines of the form "[SRC ...]".
std::string srcTag() const;
void makePayloadHttpResponse(const std::string &plainBody,
@@ -91,8 +88,7 @@ private:
boost::uuids::uuid uuid_;
std::mutex mutex_;
// Last user authenticated on this TCP connection; tried first next time.
std::string &userHint_;
// Points into a config snapshot, which is never freed.
const User *user_ = nullptr;
std::shared_ptr<Usage::Counter> usage_;
};
-1
View File
@@ -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());
+6 -5
View File
@@ -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,
@@ -42,6 +43,7 @@ std::unordered_map<std::string, std::vector<std::weak_ptr<TCPConnection>>> TCPCo
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];
@@ -578,8 +580,6 @@ std::optional<std::string> TCPConnection::postTunnelAction(const std::string &ac
const auto pos = response.find("\r\n\r\n");
if (pos == std::string::npos) return std::nullopt;
// "HTTP/1.1 200 OK": anything but 200 means the server refused the request,
// for example because this agent's token is no longer accepted.
const auto space = response.find(' ');
if (space == std::string::npos || response.compare(space + 1, 3, "200") != 0) {
return std::nullopt;
@@ -656,7 +656,6 @@ bool TCPConnection::handleSocks5Handshake() {
std::to_string(header[0]),
Log::Level::DEBUG);
unsigned char req[4];
if (!readExactFromClient(req, 4)) return false;
@@ -723,7 +722,6 @@ bool TCPConnection::handleSocks5Handshake() {
return true;
}
void TCPConnection::startTunnelReadFromClient() {
if (tunnelClosed_ || !socket_.is_open()) return;
@@ -814,7 +812,6 @@ void TCPConnection::abortTunnel(const std::string &reason) {
log_->write("[" + to_string(uuid_) + "] [TCPConnection] [Tunnel closed] " + reason,
Log::Level::INFO);
// No "close" action: the server has already dropped or refused the session.
tunnelClosed_ = true;
pollTimer_.cancel();
socketShutdown();
@@ -1092,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),
@@ -1126,6 +1125,8 @@ void TCPConnection::relayTargetToAgent() {
return;
}
Usage::instance().add(self->usage_, bytes);
self->asyncWriteToAgentConnection(
self->upstreamBuf_.data(),
bytes,
+2 -7
View File
@@ -20,6 +20,7 @@
#include "agenthandler.hpp"
#include "general.hpp"
#include "serverhandler.hpp"
#include "usage.hpp"
class TCPConnection : public std::enable_shared_from_this<TCPConnection> {
public:
@@ -58,8 +59,6 @@ public:
void socketShutdown();
// Closes every server-side connection authenticated as one of these
// users, from any thread. Returns how many were open.
static std::size_t revokeUsers(const std::vector<std::string> &users);
void enableDirectTunnelMode();
@@ -127,10 +126,7 @@ private:
void startTunnelReadFromClient();
void startTunnelPollServer();
// Returns the decrypted response body (empty when the server has no data),
// or nullopt when the server refused the request or could not be reached.
std::optional<std::string> postTunnelAction(const std::string &action, const std::string &rawBody);
// Closes a tunnel the server no longer serves (e.g. the user was revoked).
void abortTunnel(const std::string &reason);
std::string makeRelayHostHeader() const;
void closeTunnelSession();
@@ -164,10 +160,9 @@ private:
unsigned int pollDelayMs_;
std::atomic_bool closed_{false};
// Server mode: last user authenticated on this connection, and the user
// it is registered under for revocation.
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_;
+220
View File
@@ -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);
}
+59
View File
@@ -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;
};
+4 -1
View File
@@ -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:
+30 -20
View File
@@ -17,7 +17,7 @@ general:
# fakeUrls:
# Defines the list of fake urls between agent and server
fakeUrls:
- nipo.ciron.net
- nipo.sudoer.net
- sudoer.ir
- sudoer.net
- google.com
@@ -67,7 +67,6 @@ general:
tlsKeyFile: "/etc/nipovpn/server.key"
tlsCaFile: ""
# This block is to define log directives
log:
# logLevel: "INFO|TRACE|DEBUG"
@@ -85,11 +84,38 @@ server:
# listenPort: the port number which will be used on server
listenPort: 443
# 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. Requires aesEnable. 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: 2
# 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
@@ -105,20 +131,4 @@ agent:
# 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: "b354d990-1d1e-4956-94dd-75adfc692668"
# This block is used only by the server: the users allowed to connect.
# Each user has their own token, and that user's agent puts the same token in
# agent.token. Requires aesEnable. Add, disable or remove users without a
# restart: edit this file and run `systemctl reload nipovpn-server`.
users:
- name: alice
# 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.
enabled: true
- name: bob
token: "4bc22ec2-b29b-4279-acc2-bfa1702e8dec"
enabled: true
token: "4bc22ec2-b29b-4279-acc2-bfa1702e8dec"