change config logic and replace directives

This commit is contained in:
Morteza Bashsiz committed 2026-11-21 20:38:43 +01:00
1 parent 4bacfbfd99
commit 933e373247
13 files changed
+226 -220

No files matched your search

+19 -15
View File
@@ -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.
@@ -236,10 +236,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
```
@@ -253,23 +253,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 |
|---|---|---|---|
| `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`
@@ -285,6 +277,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`
@@ -293,10 +288,18 @@ 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` | — | 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. |
### `server.users`
@@ -489,6 +492,7 @@ journalctl -u nipovpn-server.service -f
| `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. |
+2 -2
View File
@@ -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;
}
+55 -69
View File
@@ -13,26 +13,27 @@ std::unique_ptr<Config::Settings> Config::load(RunMode mode, const std::string &
const std::string legacyToken = yaml["general"]["token"].as<std::string>("");
s->general = {yaml["general"]["protocol"].as<std::string>(""),
yaml["general"]["bufferSize"].as<unsigned int>(65536),
yaml["general"]["fakeUrls"].as<std::vector<std::string>>(),
yaml["general"]["methods"].as<std::vector<std::string>>(),
yaml["general"]["endPoints"].as<std::vector<std::string>>(),
yaml["general"]["timeout"].as<unsigned short>(10),
yaml["general"]["pullTimeout"].as<unsigned short>(1),
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"]["connectionReuse"].as<bool>(false),
yaml["general"]["aesEnable"].as<bool>(true),
yaml["general"]["tlsEnable"].as<bool>(false),
yaml["general"]["tlsVerifyPeer"].as<bool>(false),
yaml["general"]["tlsCertFile"].as<std::string>(""),
yaml["general"]["tlsKeyFile"].as<std::string>(""),
yaml["general"]["tlsCaFile"].as<std::string>("")};
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)};
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),
@@ -40,7 +41,22 @@ std::unique_ptr<Config::Settings> Config::load(RunMode mode, const std::string &
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>("")};
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;
@@ -143,7 +159,7 @@ Config::ReloadResult Config::reload() {
keep(next->agent.listenPort, prev.agent.listenPort, "agent.listenPort");
keep(next->agent.threads, prev.agent.threads, "agent.threads");
}
keep(next->usageFile, prev.usageFile, "usage.file");
keep(next->usageFile, prev.usageFile, "server.usage.file");
keep(next->general.tlsEnable, prev.general.tlsEnable, "general.tlsEnable");
std::vector<std::string> revoked;
@@ -192,51 +208,10 @@ std::string Config::toString() const {
ss << "\nConfig :\n"
<< " General :\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"
@@ -246,6 +221,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"
@@ -255,6 +233,14 @@ std::string Config::toString() const {
<< " serverPort: " << agent_.serverPort << "\n"
<< " httpVersion: " << agent_.httpVersion << "\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) {
@@ -358,9 +344,9 @@ std::string Config::modeToString() const {
}
std::string Config::randomFakeUrl() const {
const General &general_ = current().general;
const Agent &agent_ = current().agent;
if (general_.fakeUrls.empty()) {
if (agent_.fakeUrls.empty()) {
return "www.google.com";
}
@@ -368,15 +354,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 {
const General &general_ = current().general;
const Agent &agent_ = current().agent;
if (general_.methods.empty()) {
if (agent_.methods.empty()) {
return "GET";
}
@@ -384,15 +370,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 {
const General &general_ = current().general;
const Agent &agent_ = current().agent;
if (general_.endPoints.empty()) {
if (agent_.endPoints.empty()) {
return "api";
}
@@ -400,7 +386,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)];
}
+11 -11
View File
@@ -29,21 +29,10 @@ struct User {
class Config : private Uncopyable {
public:
struct General {
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 {
@@ -55,6 +44,9 @@ public:
unsigned short threads;
std::string listenIp;
unsigned short listenPort;
unsigned int bufferSize;
std::string tlsCertFile;
std::string tlsKeyFile;
};
struct Agent {
@@ -66,6 +58,14 @@ public:
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;
};
struct Settings {
+45 -11
View File
@@ -424,6 +424,15 @@ inline bool isValidUserName(const std::string &name) {
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"};
@@ -448,13 +457,7 @@ inline BoolStr validateConfigFile(const std::string &mode, const std::string &pa
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"]["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";
@@ -489,14 +492,45 @@ inline BoolStr validateConfigFile(const std::string &mode, const std::string &pa
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";
return result;
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>();
-23
View File
@@ -153,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" +
-3
View File
@@ -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;
+17 -11
View File
@@ -109,6 +109,10 @@ std::string ServerHandler::srcTag() const {
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) {
@@ -122,6 +126,7 @@ void ServerHandler::makePlainHttpResponse(const std::string &body,
<< body;
copyStringToStreambuf(outer.str(), writeBuffer_);
keepAlive_ = connection == "keep-alive";
end_ = false;
connect_ = false;
@@ -163,6 +168,7 @@ void ServerHandler::handle() {
}
const auto &outerReq = request_->parsedHttpRequest();
requestKeepAlive_ = outerReq.keep_alive();
const std::string outerRaw = streambufToString(readBuffer_);
@@ -238,7 +244,7 @@ void ServerHandler::handle() {
}
if (!targetClient || !targetClient->isOpen()) {
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
makePayloadHttpResponse("", "200 OK", connectionHeader());
return;
}
@@ -247,7 +253,7 @@ void ServerHandler::handle() {
Usage::instance().add(usage_, tunnelBuf.size());
targetClient->doWrite(tunnelBuf);
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
makePayloadHttpResponse("", "200 OK", connectionHeader());
return;
}
@@ -264,7 +270,7 @@ void ServerHandler::handle() {
}
if (!targetClient || !targetClient->isOpen()) {
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
makePayloadHttpResponse("", "200 OK", connectionHeader());
return;
}
@@ -272,17 +278,17 @@ 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;
}
@@ -291,7 +297,7 @@ void ServerHandler::handle() {
makePayloadHttpResponse(
std::string(data.data(), n),
"200 OK",
(config_->general().connectionReuse ? "keep-alive" : "close"));
connectionHeader());
return;
}
@@ -305,7 +311,7 @@ void ServerHandler::handle() {
sessions_.erase(it);
}
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
makePayloadHttpResponse("", "200 OK", connectionHeader());
return;
}
@@ -436,7 +442,7 @@ void ServerHandler::handle() {
makePayloadHttpResponse(
"HTTP/1.1 200 Connection Established\r\n\r\n",
"200 OK",
"keep-alive");
connectionHeader());
connect_ = false;
end_ = false;
@@ -462,14 +468,14 @@ void ServerHandler::handle() {
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
View File
@@ -40,6 +40,7 @@ public:
bool end_;
bool connect_;
bool keepAlive_ = false;
private:
struct HttpUtils {
@@ -66,6 +67,9 @@ private:
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");
+3 -3
View File
@@ -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);
+12 -12
View File
@@ -88,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())) {
@@ -231,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;
@@ -296,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] = {
@@ -336,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();
}
@@ -423,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();
@@ -440,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();
@@ -518,7 +518,7 @@ std::optional<std::string> TCPConnection::postTunnelAction(const std::string &ac
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()
@@ -571,7 +571,7 @@ std::optional<std::string> TCPConnection::postTunnelAction(const std::string &ac
std::string response = sendOnce();
if (response.empty() &&
config_->general().connectionReuse &&
config_->agent().connectionReuse &&
action != "close") {
client_->socketShutdown();
response = sendOnce();
@@ -743,7 +743,7 @@ void TCPConnection::startTunnelReadFromClient() {
return;
}
self->pollDelayMs_ = self->config_->general().pullTimeout;
self->pollDelayMs_ = self->config_->agent().pullTimeout;
if (self->pollInProgress_) self->pollTimer_.cancel();
self->startTunnelReadFromClient();
@@ -778,7 +778,7 @@ void TCPConnection::startTunnelPollServer() {
}
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))
+43 -50
View File
@@ -1,71 +1,23 @@
---
# 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:
# aesEnable: bool (default: true)
# Enables AES-256-GCM payload encryption (confidentiality and integrity). Must match on the agent and server.
# Required on the server when using users: users are told apart by their AES key.
# 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.sudoer.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
# 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
# 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:
@@ -83,6 +35,13 @@ 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
@@ -120,6 +79,40 @@ 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"
# serverPort: port number of the nipoServer
+15 -10
View File
@@ -27,24 +27,29 @@ 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(general.get("protocol")),
"fakeUrls": to_lines(general.get("fakeUrls")),
"methods": to_lines(general.get("methods")),
"endPoints": to_lines(general.get("endPoints")),
"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(general.get("pullTimeout")),
"pullTimeout": to_str(moved(agent, "pullTimeout")),
"tunnelEnable": bool(general.get("tunnelEnable", False)),
"connectionReuse": bool(general.get("connectionReuse", False)),
"connectionReuse": bool(moved(agent, "connectionReuse", False)),
"tlsEnable": bool(general.get("tlsEnable", False)),
"tlsVerifyPeer": bool(general.get("tlsVerifyPeer", False)),
"tlsCertFile": to_str(general.get("tlsCertFile")),
"tlsKeyFile": to_str(general.get("tlsKeyFile")),
"tlsCaFile": to_str(general.get("tlsCaFile")),
"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")),