Compare commits

..
Author SHA1 Message Date
Morteza Bashsiz 88782afbfd Release 1.1.60
. Switch payload encryption to AES-256-GCM and move session/action into the encrypted body (breaking: agent, server and Android app must all be 1.1.60)
. Add aesEnable option; require a token of at least 32 chars
. Fix proxy hangs from blocking connects to unreachable hosts
. Fix high CPU usage from tunnel polling
2026-10-28 09:39:07 +01:00
Morteza Bashsiz 6bcc946f58 Merge pull request #252 from MortezaBashsiz/mori/refactor
fix termux build issue
2026-10-27 23:17:08 +01:00
Morteza Bashsiz 6770764f2b fix termux build issue 2026-10-27 23:16:40 +01:00
Morteza Bashsiz 9199a0ded9 Merge pull request #251 from MortezaBashsiz/mori/refactor
Mori/refactor
2026-10-27 23:02:59 +01:00
Morteza Bashsiz 92de8a0bce change log level to infor in the config 2026-10-27 23:02:40 +01:00
Morteza Bashsiz 679ab77dc2 Fix CPU utilization issue 2026-10-27 22:52:25 +01:00
Morteza Bashsiz 04768f37de Test commit 2026-10-27 22:29:19 +01:00
Morteza Bashsiz e52743c051 Merge pull request #246 from MortezaBashsiz/dev
Dockerfile
2026-06-22 16:04:56 +02:00
Morteza Bashsiz ce61bfd8ad Merge pull request #245 from MortezaBashsiz/mori/add-docker
add docker file
2026-06-22 16:02:39 +02:00
Morteza Bashsiz 78188d8ac3 add docker file 2026-06-22 16:01:44 +02:00
Morteza Bashsiz 1af9ede5ff Merge pull request #243 from MortezaBashsiz/dev
Dev
2026-06-17 22:58:47 +02:00
Morteza Bashsiz 5f3594b6d2 Merge pull request #242 from MortezaBashsiz/mori
Mori
2026-06-17 22:56:49 +02:00
Morteza Bashsiz 95e05cf59c Update readme 2026-06-17 22:55:47 +02:00
Morteza Bashsiz a8205a716b Merge pull request #241 from MortezaBashsiz/dev
Dev
2026-06-17 11:08:29 +02:00
Morteza Bashsiz c76b23f93c Merge pull request #240 from MortezaBashsiz/mori
update readme
2026-06-17 11:06:53 +02:00
Morteza Bashsiz 555cad3654 Merge branch 'dev' into mori 2026-06-17 11:06:23 +02:00
Morteza Bashsiz df310303da update readme 2026-06-17 11:04:44 +02:00
Morteza Bashsiz 5056b7b907 Merge pull request #239 from MortezaBashsiz/dev
Add nix support
2026-06-16 14:16:47 +02:00
Morteza Bashsiz 5616828192 Merge pull request #225 from Grphq1/feat/add-flake-nix
feat: add nix flake support
2026-06-16 14:14:17 +02:00
Morteza Bashsiz 5a0c414f63 Version 1.1.59
Version 1.1.59
2026-06-16 11:49:39 +02:00
Morteza Bashsiz 5ddfcf1a0d Merge pull request #238 from MortezaBashsiz/mori
fix readme
2026-06-16 11:47:50 +02:00
Morteza Bashsiz 703595501c fix readme 2026-06-16 11:44:53 +02:00
Morteza Bashsiz 3b195208ff Merge pull request #236 from MortezaBashsiz/mori version 1.1.59
new version 1.1.59
2026-06-16 11:29:25 +02:00
Morteza Bashsiz a63d7ca141 new version 1.1.59 2026-06-16 11:28:42 +02:00
Morteza Bashsiz 882c68179f Merge pull request #235 from MortezaBashsiz/mori
change libyaml-cpp dependencies
2026-06-16 10:54:37 +02:00
Morteza Bashsiz 5e8b76769d change libyaml-cpp dependencies 2026-06-16 10:53:57 +02:00
Morteza Bashsiz c1afc7dab2 Merge pull request #233 from MortezaBashsiz/mori Version 1.1.59
Version 1.1.59
2026-06-16 10:29:57 +02:00
Morteza Bashsiz ef04fb3fb2 Fix config and log overwrite 2026-06-16 10:28:10 +02:00
Morteza Bashsiz ec5eaf824b Make logs better 2026-06-15 11:43:53 +02:00
Morteza Bashsiz de4606d884 Version 1.1.58
Add bufferSize to config
2026-06-14 09:48:11 +02:00
Morteza Bashsiz 4860804ef1 Version 1.1.58 (Dev)
Add bufferSize to config
Implement Buffer size configurable
2026-06-11 22:44:37 +02:00
Morteza Bashsiz d9c3a45074 Add bufferSize to config 2026-06-11 22:40:32 +02:00
lorem10 33adcf9541 chore(nix): bump version to 1.1.57 2026-06-10 17:30:29 +03:30
lorem10 02920acb49 docs: add Nix guide 2026-06-10 17:18:48 +03:30
lorem10 b250ec47a9 feat: add Nix Flake 2026-06-10 17:18:48 +03:30
Morteza Bashsiz 8e677a826d Merge pull request #220 from MortezaBashsiz/dev
Version 1.1.57
2026-06-09 16:07:09 +02:00
Morteza Bashsiz 2e2ef18529 Merge pull request #219 from MortezaBashsiz/mori
Mori
2026-06-09 16:03:12 +02:00
Morteza Bashsiz fdf03a7ec7 Fix windows version 2026-06-09 15:57:37 +02:00
Morteza Bashsiz 14f7f107b7 Version 1.1.57
* fix logging issue while INFO
* Version 1.1.57
2026-06-09 15:41:17 +02:00
Morteza Bashsiz 13aa2cd816 Version 1.1.57 (#216)
* fix logging issue while INFO
* Version 1.1.57
2026-06-09 15:38:22 +02:00
Morteza Bashsiz 042998095e fix logging issue while INFO (#215) 2026-06-09 15:13:40 +02:00
Morteza Bashsiz a006ba4e0c Merge pull request #212 from MortezaBashsiz/dev
Version 1.1.56
2026-06-07 20:36:51 +02:00
Morteza Bashsiz 413bffba44 Version 1.1.56
Version 1.1.56
2026-06-07 20:25:44 +02:00
Morteza Bashsiz 3b2c01b095 Merge branch 'dev' into mori 2026-06-07 20:25:20 +02:00
Morteza Bashsiz 4c6a00e801 Version 1.1.56 2026-06-07 20:23:26 +02:00
Morteza Bashsiz c2dc1487a2 Version 1.1.55
Version 1.1.55
2026-06-07 20:15:34 +02:00
Morteza Bashsiz 4df70ae101 Merge pull request #209 from MortezaBashsiz/mori
fix version
2026-06-07 20:14:06 +02:00
Morteza Bashsiz 49026a2f0d fix version 2026-06-07 20:13:15 +02:00
Morteza Bashsiz 7c82f7f3b5 Versin 1.1.55
Versin 1.1.55
2026-06-07 19:02:48 +02:00
Morteza Bashsiz 3a965c904f Merge branch 'main' into dev 2026-06-07 19:00:57 +02:00
Morteza Bashsiz 1f03931aa4 Merge pull request #207 from MortezaBashsiz/mori
fix ipv6 bug
2026-06-07 18:57:43 +02:00
Morteza Bashsiz aa36749c47 fix ipv6 bug 2026-06-07 18:56:45 +02:00
Morteza Bashsiz 6535cb51b7 Fix IPv6 bug 2026-06-07 13:34:14 +02:00
Morteza Bashsiz 212003760b fix server freezing bug 2026-06-07 11:36:12 +02:00
Morteza Bashsiz 698da19a8c Merge pull request #204 from MortezaBashsiz/revert-202-dev
Revert "Version 1.1.55"
2026-06-07 07:41:46 +02:00
Morteza Bashsiz 451a169756 Revert "Version 1.1.55" 2026-06-07 07:38:50 +02:00
Morteza Bashsiz 277321306b Version 1.1.55
Version 1.1.55
2026-06-06 14:04:46 +02:00
Morteza Bashsiz d6e0161aa5 Merge pull request #201 from MortezaBashsiz/mori
Version 1.1.55
2026-06-06 14:02:13 +02:00
Morteza Bashsiz 14b0947140 Version 1.1.55 2026-06-06 14:01:16 +02:00
Morteza Bashsiz 134251779c Merge pull request #200 from MortezaBashsiz/mori
change tcpconnection handle accept method
2026-06-06 08:32:05 +02:00
Morteza Bashsiz 92d877be31 change tcpconnection handle accept method 2026-06-06 08:17:14 +02:00
Morteza Bashsiz 7e6ae56753 Version 1.1.54
In this version

Socks5 protocol is now supported. So user can choose socks5|http protocol between client and agent

Refactor of code base is done
2026-06-05 17:45:46 +02:00
Morteza Bashsiz deae50f9d4 Merge pull request #197 from MortezaBashsiz/mori
Add socks5 support
2026-06-05 16:59:20 +02:00
Morteza Bashsiz daa21a57db fix main branch support 2026-06-05 16:38:20 +02:00
Morteza Bashsiz d8f09b9fe2 Add socks5 support 2026-06-05 16:21:05 +02:00
Morteza Bashsiz aeeea2a527 Merge pull request #196 from MortezaBashsiz/mori
Refactor code with better style
2026-06-05 10:33:08 +02:00
Morteza Bashsiz 55004368e4 Refactor code with better style 2026-06-05 10:30:06 +02:00
Morteza Bashsiz d0da1c55d8 Version 1.1.53
Fix handshake bug, close connection after handshake failed
2026-06-05 07:53:48 +02:00
Morteza Bashsiz 3363a7a5d2 Fix handshake bug, close connection after handshake failed
Fix handshake bug, close connection after handshake failed
2026-06-04 23:38:55 +02:00
Morteza Bashsiz 4cdc66bdf1 Fix handshake bug, close connection after handshake failed 2026-06-04 23:36:15 +02:00
Morteza Bashsiz 2540b3a504 Add windows build 2026-06-04 18:33:56 +02:00
Morteza Bashsiz cb87555503 Version 1.1.52
Version 1.1.52
2026-06-04 17:17:48 +02:00
Morteza Bashsiz 20bb0d2b9d Version 1.1.52
Version 1.1.52
2026-06-04 17:14:08 +02:00
Morteza Bashsiz 31b7bb96a8 Version 1.1.52 2026-06-04 17:12:52 +02:00
Morteza Bashsiz 9abc319202 Add workflows for all branches & support android in threading
Add workflows for all branches & support android in threading
2026-06-04 16:51:51 +02:00
Morteza Bashsiz 6c21edfc40 Add workflows for all branches & support android in threading 2026-06-04 16:38:43 +02:00
Morteza Bashsiz 6493d88258 create workflows for all branches 2026-06-04 16:37:01 +02:00
Morteza Bashsiz ed10d097f1 fix missing args 2026-06-03 14:52:26 +02:00
Morteza Bashsiz 14ead78ff8 add release step to android dev 2026-06-02 19:25:05 +02:00
Morteza Bashsiz b1a18e243c change jthread to thread for android 2026-06-02 18:43:46 +02:00
Morteza Bashsiz 24390b6562 fix android binary action 2026-06-02 18:26:57 +02:00
Morteza Bashsiz ec4a68fdb6 Merge pull request #187 from MortezaBashsiz/dev
Fix main verion
2026-06-02 16:37:21 +02:00
Morteza Bashsiz bae6afa35b Merge pull request #186 from MortezaBashsiz/mori
Mori
2026-06-02 16:35:16 +02:00
Morteza Bashsiz 36315032d9 fix main version 2026-06-02 16:33:49 +02:00
Morteza Bashsiz 96758b6322 add android 2026-06-02 16:18:21 +02:00
Morteza Bashsiz 9b5b275275 Merge pull request #185 from MortezaBashsiz/dev
add termux version #182
2026-06-02 16:14:35 +02:00
Morteza Bashsiz 76a9e4acb0 Merge pull request #184 from MortezaBashsiz/mori
add aarch64 termux
2026-06-02 15:57:43 +02:00
Morteza Bashsiz 3b3d2f4d88 add aarch64 to the build 2026-06-02 15:55:23 +02:00
Morteza Bashsiz 9af39a5715 Merge pull request #181 from MortezaBashsiz/dev
Release arm64 and amd64
2026-06-02 09:28:44 +02:00
Morteza Bashsiz 2f043a6f83 Merge pull request #180 from MortezaBashsiz/mori
Build debian package for arm64
2026-06-02 07:26:11 +02:00
Morteza Bashsiz d94075e5c3 fix workflow dev and main 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 9f1a7c8637 fix control 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 2add09ea33 fix control 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 8beee5d127 add arm to workflow 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 84bb675b9c add arm to workflow 2026-06-02 07:09:44 +02:00
46 changed files with 2930 additions and 792 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
.git
.github
build
cmake-build-*
*.deb
*.tar.gz
*.log
+157
View File
@@ -0,0 +1,157 @@
name: Build Android Binary - dev
on:
workflow_dispatch:
push:
branches:
- dev
paths:
- 'core/src/**'
- 'core/**'
- 'CMakeLists.txt'
- 'core/CMakeLists.txt'
- '.github/workflows/android-dev.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 0.1.${{ github.run_number }}
jobs:
build-android:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
cmake \
ninja-build \
git \
curl \
zip \
unzip \
tar \
pkg-config \
autoconf \
autoconf-archive \
automake \
libtool
- name: Setup Android NDK r29
uses: nttld/setup-ndk@v1
with:
ndk-version: r29
add-to-path: true
- name: Show Android NDK information
run: |
echo "ANDROID_NDK_HOME=$ANDROID_NDK_HOME"
echo "ANDROID_NDK_ROOT=$ANDROID_NDK_ROOT"
ls -lah "$ANDROID_NDK_HOME"
- name: Setup vcpkg
run: |
git clone https://github.com/microsoft/vcpkg.git "$HOME/vcpkg"
"$HOME/vcpkg/bootstrap-vcpkg.sh"
echo "VCPKG_ROOT=$HOME/vcpkg" >> "$GITHUB_ENV"
echo "$HOME/vcpkg" >> "$GITHUB_PATH"
- name: Build Android dependencies
run: |
"$VCPKG_ROOT/vcpkg" install \
boost:arm64-android \
openssl:arm64-android \
yaml-cpp:arm64-android
- name: Configure Android arm64-v8a build
run: |
rm -rf build-android-arm64
cmake -S . -B build-android-arm64 \
-G Ninja \
-DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \
-DVCPKG_TARGET_TRIPLET=arm64-android \
-DVCPKG_CHAINLOAD_TOOLCHAIN_FILE="$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake" \
-DANDROID_ABI=arm64-v8a \
-DANDROID_PLATFORM=android-23 \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_EXE_LINKER_FLAGS="-Wl,-z,max-page-size=16384" \
-DCMAKE_SHARED_LINKER_FLAGS="-Wl,-z,max-page-size=16384"
- name: Build Android arm64-v8a binary
run: |
cmake --build build-android-arm64 -j"$(nproc)"
- name: Collect Android binary and libraries
run: |
mkdir -p out/android/arm64-v8a
if [ ! -f build-android-arm64/core/nipovpn ]; then
echo "Android binary not found:"
find build-android-arm64 -type f || true
exit 1
fi
cp build-android-arm64/core/nipovpn out/android/arm64-v8a/libnipovpn_dev_"${{ env.PACKAGE_VERSION }}".so
chmod 755 out/android/arm64-v8a/libnipovpn_dev_"${{ env.PACKAGE_VERSION }}".so
find "$VCPKG_ROOT/installed/arm64-android" -type f -name "*.so*" -exec cp -v {} out/android/arm64-v8a/ \; || true
ls -lah out/android/arm64-v8a/
- name: Check 16 KB ELF alignment
run: |
READELF="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf"
for file in out/android/arm64-v8a/*.so*; do
echo "Checking $file"
"$READELF" -l "$file" | grep -A3 LOAD || true
if "$READELF" -l "$file" | awk '/LOAD/ && $NF != "0x4000" { bad=1 } END { exit bad }'; then
echo "OK: $file is 16 KB aligned"
else
echo "ERROR: $file is not 16 KB aligned"
exit 1
fi
done
- name: Upload Android artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-dev-android-arm64-v8a
path: out/android/arm64-v8a/
release-android:
needs:
- build-android
runs-on: ubuntu-24.04
steps:
- name: Download Android artifact
uses: actions/download-artifact@v4
with:
name: nipovpn-dev-android-arm64-v8a
path: ./android-artifact
- name: Show downloaded Android artifact
run: |
ls -lah android-artifact
- name: Create Android GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: dev-android-v${{ env.PACKAGE_VERSION }}
name: dev Android Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: |
android-artifact/*
env:
GITHUB_TOKEN: ${{ github.token }}
+157
View File
@@ -0,0 +1,157 @@
name: Build Android Binary - main
on:
workflow_dispatch:
push:
branches:
- main
paths:
- 'core/src/**'
- 'core/**'
- 'CMakeLists.txt'
- 'core/CMakeLists.txt'
- '.github/workflows/android-main.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 1.1.60
jobs:
build-android:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
cmake \
ninja-build \
git \
curl \
zip \
unzip \
tar \
pkg-config \
autoconf \
autoconf-archive \
automake \
libtool
- name: Setup Android NDK r29
uses: nttld/setup-ndk@v1
with:
ndk-version: r29
add-to-path: true
- name: Show Android NDK information
run: |
echo "ANDROID_NDK_HOME=$ANDROID_NDK_HOME"
echo "ANDROID_NDK_ROOT=$ANDROID_NDK_ROOT"
ls -lah "$ANDROID_NDK_HOME"
- name: Setup vcpkg
run: |
git clone https://github.com/microsoft/vcpkg.git "$HOME/vcpkg"
"$HOME/vcpkg/bootstrap-vcpkg.sh"
echo "VCPKG_ROOT=$HOME/vcpkg" >> "$GITHUB_ENV"
echo "$HOME/vcpkg" >> "$GITHUB_PATH"
- name: Build Android dependencies
run: |
"$VCPKG_ROOT/vcpkg" install \
boost:arm64-android \
openssl:arm64-android \
yaml-cpp:arm64-android
- name: Configure Android arm64-v8a build
run: |
rm -rf build-android-arm64
cmake -S . -B build-android-arm64 \
-G Ninja \
-DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \
-DVCPKG_TARGET_TRIPLET=arm64-android \
-DVCPKG_CHAINLOAD_TOOLCHAIN_FILE="$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake" \
-DANDROID_ABI=arm64-v8a \
-DANDROID_PLATFORM=android-23 \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_EXE_LINKER_FLAGS="-Wl,-z,max-page-size=16384" \
-DCMAKE_SHARED_LINKER_FLAGS="-Wl,-z,max-page-size=16384"
- name: Build Android arm64-v8a binary
run: |
cmake --build build-android-arm64 -j"$(nproc)"
- name: Collect Android binary and libraries
run: |
mkdir -p out/android/arm64-v8a
if [ ! -f build-android-arm64/core/nipovpn ]; then
echo "Android binary not found:"
find build-android-arm64 -type f || true
exit 1
fi
cp build-android-arm64/core/nipovpn out/android/arm64-v8a/libnipovpn_"${{ env.PACKAGE_VERSION }}".so
chmod 755 out/android/arm64-v8a/libnipovpn_"${{ env.PACKAGE_VERSION }}".so
find "$VCPKG_ROOT/installed/arm64-android" -type f -name "*.so*" -exec cp -v {} out/android/arm64-v8a/ \; || true
ls -lah out/android/arm64-v8a/
- name: Check 16 KB ELF alignment
run: |
READELF="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf"
for file in out/android/arm64-v8a/*.so*; do
echo "Checking $file"
"$READELF" -l "$file" | grep -A3 LOAD || true
if "$READELF" -l "$file" | awk '/LOAD/ && $NF != "0x4000" { bad=1 } END { exit bad }'; then
echo "OK: $file is 16 KB aligned"
else
echo "ERROR: $file is not 16 KB aligned"
exit 1
fi
done
- name: Upload Android artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-main-android-arm64-v8a
path: out/android/arm64-v8a/
release-android:
needs:
- build-android
runs-on: ubuntu-24.04
steps:
- name: Download Android artifact
uses: actions/download-artifact@v4
with:
name: nipovpn-main-android-arm64-v8a
path: ./android-artifact
- name: Show downloaded Android artifact
run: |
ls -lah android-artifact
- name: Create Android GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: android-v${{ env.PACKAGE_VERSION }}
name: Android Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: |
android-artifact/*
env:
GITHUB_TOKEN: ${{ github.token }}
+264 -24
View File
@@ -1,4 +1,4 @@
name: Build and Release Debian Package - DEV
name: Build and Release Package - dev
on:
push:
@@ -15,17 +15,29 @@ permissions:
env:
PACKAGE_VERSION: 0.1.${{ github.run_number }}
PACKAGE_FILE: nipovpn_dev_0.1.${{ github.run_number }}_amd64.deb
jobs:
build:
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
include:
- arch: amd64
package_arch: amd64
- arch: arm64
package_arch: arm64
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Set up dependencies
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
platforms: arm64
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
@@ -42,55 +54,283 @@ jobs:
- name: Build binary
run: |
rm -rf build
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
if [ "${{ matrix.arch }}" = "arm64" ]; then
docker run --rm --platform linux/arm64 \
-v "$PWD:/src" \
-w /src \
ubuntu:24.04 \
bash -c '
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y \
build-essential \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
'
sudo chown -R $USER:$USER build
else
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
fi
- name: Build Debian package
run: |
mkdir -p nipovpn/usr/bin
PACKAGE_FILE="nipovpn_dev_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
cp build/core/nipovpn nipovpn/usr/bin/nipovpn
chmod 755 nipovpn/usr/bin/nipovpn
rm -rf package-root
cp -a nipovpn package-root
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" nipovpn/DEBIAN/control
mkdir -p package-root/usr/bin
cp build/core/nipovpn package-root/usr/bin/nipovpn
chmod 755 package-root/usr/bin/nipovpn
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" package-root/DEBIAN/control
sed -i -E "s/^Architecture[[:space:]]*:.*/Architecture: ${{ matrix.package_arch }}/" package-root/DEBIAN/control
sed -i -e '$a\' package-root/DEBIAN/control
mkdir -p package-root/DEBIAN
cat > package-root/DEBIAN/conffiles <<'EOF'
/etc/nipovpn/config.yaml
EOF
rm -f package-root/var/log/nipovpn/nipovpn.log
mkdir -p package-root/var/log/nipovpn
cat > package-root/DEBIAN/postinst <<'EOF'
#!/bin/sh
set -e
mkdir -p /var/log/nipovpn
if [ ! -f /var/log/nipovpn/nipovpn.log ]; then
touch /var/log/nipovpn/nipovpn.log
chmod 0644 /var/log/nipovpn/nipovpn.log
fi
exit 0
EOF
chmod 755 package-root/DEBIAN/postinst
echo "Final control file:"
cat nipovpn/DEBIAN/control
cat package-root/DEBIAN/control
grep "^Version: ${PACKAGE_VERSION}$" nipovpn/DEBIAN/control
grep "^Version: ${PACKAGE_VERSION}$" package-root/DEBIAN/control
grep "^Architecture: ${{ matrix.package_arch }}$" package-root/DEBIAN/control
dpkg-deb --build nipovpn "build/${PACKAGE_FILE}"
mkdir -p build
dpkg-deb --build package-root "build/${PACKAGE_FILE}"
- name: Show package information
ls -lah build/
- name: Show Debian package information
run: |
PACKAGE_FILE="nipovpn_dev_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
dpkg -I "build/${PACKAGE_FILE}"
dpkg -c "build/${PACKAGE_FILE}"
- name: Upload Debian package as artifact
- name: Upload Debian package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-dev-deb
path: build/${{ env.PACKAGE_FILE }}
name: nipovpn-dev-deb-${{ matrix.arch }}
path: build/nipovpn_dev_${{ env.PACKAGE_VERSION }}_${{ matrix.arch }}.deb
build-termux:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
with:
path: nipovpn-src
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
git \
wget \
unzip \
curl \
python3 \
python3-pip \
build-essential \
cmake \
ninja-build \
pkg-config \
autoconf \
automake \
libtool \
autopoint \
bison \
flex \
gettext \
gperf \
help2man \
lzip \
libarchive-tools \
rsync \
texinfo \
jq
- name: Clone termux-packages
run: |
git clone --depth=1 https://github.com/termux/termux-packages.git
- name: Install Android NDK required by termux-packages
run: |
NDK_NUM="$(sed -n 's/^: "${TERMUX_NDK_VERSION_NUM:="\([0-9]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
NDK_REV="$(sed -n 's/^: "${TERMUX_NDK_REVISION:="\([a-z]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
if [ -z "$NDK_NUM" ]; then
echo "Could not read the NDK version from termux-packages/scripts/properties.sh"
grep -n NDK termux-packages/scripts/properties.sh || true
exit 1
fi
NDK_VERSION="r${NDK_NUM}${NDK_REV}"
echo "termux-packages requires Android NDK $NDK_VERSION"
mkdir -p "$HOME/lib"
cd "$HOME/lib"
wget -q "https://dl.google.com/android/repository/android-ndk-${NDK_VERSION}-linux.zip"
unzip -q "android-ndk-${NDK_VERSION}-linux.zip"
EXTRACTED_DIR="$(find "$HOME/lib" -maxdepth 1 -type d -name "android-ndk-${NDK_VERSION}*" | head -n 1)"
if [ -z "$EXTRACTED_DIR" ]; then
echo "Android NDK $NDK_VERSION directory not found"
ls -lah "$HOME/lib"
exit 1
fi
if [ "$EXTRACTED_DIR" != "$HOME/lib/android-ndk-${NDK_VERSION}" ]; then
ln -sfn "$EXTRACTED_DIR" "$HOME/lib/android-ndk-${NDK_VERSION}"
fi
echo "NDK=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
echo "ANDROID_NDK_ROOT=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
ls -ld "$HOME/lib/android-ndk-${NDK_VERSION}"
- name: Create Termux package recipe
run: |
mkdir -p termux-packages/packages/nipovpn
cat > termux-packages/packages/nipovpn/build.sh <<'EOF'
TERMUX_PKG_HOMEPAGE=https://github.com/MortezaBashsiz/nipovpn
TERMUX_PKG_DESCRIPTION="Powerful and secure HTTP/S proxy"
TERMUX_PKG_LICENSE="MIT"
TERMUX_PKG_MAINTAINER="Morteza Bashsiz"
TERMUX_PKG_VERSION=@PACKAGE_VERSION@
TERMUX_PKG_SRCURL=file://@GITHUB_WORKSPACE@/nipovpn-src
TERMUX_PKG_SHA256=SKIP_CHECKSUM
TERMUX_PKG_DEPENDS="openssl, boost, libyaml-cpp"
TERMUX_PKG_BUILD_IN_SRC=false
termux_step_configure() {
cmake -S "$TERMUX_PKG_SRCDIR" \
-B "$TERMUX_PKG_BUILDDIR" \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX="$TERMUX_PREFIX"
}
termux_step_make() {
cmake --build "$TERMUX_PKG_BUILDDIR" -j "$(nproc)"
}
termux_step_make_install() {
install -Dm755 \
"$TERMUX_PKG_BUILDDIR/core/nipovpn" \
"$TERMUX_PREFIX/bin/nipovpn"
if [ -d "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn" ]; then
mkdir -p "$TERMUX_PREFIX/etc/nipovpn"
cp -a "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn/." \
"$TERMUX_PREFIX/etc/nipovpn/"
fi
}
EOF
sed -i "s|@PACKAGE_VERSION@|${PACKAGE_VERSION}|g" termux-packages/packages/nipovpn/build.sh
sed -i "s|@GITHUB_WORKSPACE@|${GITHUB_WORKSPACE}|g" termux-packages/packages/nipovpn/build.sh
cat termux-packages/packages/nipovpn/build.sh
- name: Prepare Termux build data dir
run: |
sudo mkdir -p /data
sudo chown -R $USER:$USER /data
- name: Build Termux aarch64 package
working-directory: termux-packages
run: |
./build-package.sh -I -a aarch64 nipovpn
- name: Collect Termux package
run: |
mkdir -p out
TERMUX_DEB="$(find termux-packages/output -type f -name '*.deb' | head -n 1)"
if [ -z "$TERMUX_DEB" ]; then
echo "No Termux .deb package found"
find termux-packages/output -type f || true
exit 1
fi
cp "$TERMUX_DEB" "out/nipovpn_dev_${PACKAGE_VERSION}_termux_aarch64.deb"
ls -lah out/
- name: Upload Termux package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-dev-termux-aarch64
path: out/nipovpn_dev_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
release:
needs: build
needs:
- build
- build-termux
runs-on: ubuntu-latest
steps:
- name: Download Debian package artifact
- name: Download package artifacts
uses: actions/download-artifact@v4
with:
name: nipovpn-dev-deb
pattern: nipovpn-dev-*
merge-multiple: true
path: ./
- name: Create DEV GitHub Release
- name: Show downloaded files
run: |
ls -lah
- name: Create dev GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: dev-v${{ env.PACKAGE_VERSION }}
name: DEV Version v${{ env.PACKAGE_VERSION }}
name: dev Version v${{ env.PACKAGE_VERSION }}
prerelease: true
files: ${{ env.PACKAGE_FILE }}
files: |
nipovpn_dev_${{ env.PACKAGE_VERSION }}_amd64.deb
nipovpn_dev_${{ env.PACKAGE_VERSION }}_arm64.deb
nipovpn_dev_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
env:
GITHUB_TOKEN: ${{ github.token }}
+336
View File
@@ -0,0 +1,336 @@
name: Build and Release Package - main
on:
push:
branches:
- main
paths:
- 'core/src/**'
- 'core/**'
- 'nipovpn/**'
- '.github/workflows/debian-main.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 1.1.60
jobs:
build:
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
include:
- arch: amd64
package_arch: amd64
- arch: arm64
package_arch: arm64
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
platforms: arm64
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
dpkg-dev \
build-essential \
lintian \
fakeroot \
devscripts \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
- name: Build binary
run: |
rm -rf build
if [ "${{ matrix.arch }}" = "arm64" ]; then
docker run --rm --platform linux/arm64 \
-v "$PWD:/src" \
-w /src \
ubuntu:24.04 \
bash -c '
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y \
build-essential \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
'
sudo chown -R $USER:$USER build
else
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
fi
- name: Build Debian package
run: |
PACKAGE_FILE="nipovpn_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
rm -rf package-root
cp -a nipovpn package-root
mkdir -p package-root/usr/bin
cp build/core/nipovpn package-root/usr/bin/nipovpn
chmod 755 package-root/usr/bin/nipovpn
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" package-root/DEBIAN/control
sed -i -E "s/^Architecture[[:space:]]*:.*/Architecture: ${{ matrix.package_arch }}/" package-root/DEBIAN/control
sed -i -e '$a\' package-root/DEBIAN/control
mkdir -p package-root/DEBIAN
cat > package-root/DEBIAN/conffiles <<'EOF'
/etc/nipovpn/config.yaml
EOF
rm -f package-root/var/log/nipovpn/nipovpn.log
mkdir -p package-root/var/log/nipovpn
cat > package-root/DEBIAN/postinst <<'EOF'
#!/bin/sh
set -e
mkdir -p /var/log/nipovpn
if [ ! -f /var/log/nipovpn/nipovpn.log ]; then
touch /var/log/nipovpn/nipovpn.log
chmod 0644 /var/log/nipovpn/nipovpn.log
fi
exit 0
EOF
chmod 755 package-root/DEBIAN/postinst
echo "Final control file:"
cat package-root/DEBIAN/control
grep "^Version: ${PACKAGE_VERSION}$" package-root/DEBIAN/control
grep "^Architecture: ${{ matrix.package_arch }}$" package-root/DEBIAN/control
mkdir -p build
dpkg-deb --build package-root "build/${PACKAGE_FILE}"
ls -lah build/
- name: Show Debian package information
run: |
PACKAGE_FILE="nipovpn_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
dpkg -I "build/${PACKAGE_FILE}"
dpkg -c "build/${PACKAGE_FILE}"
- name: Upload Debian package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-deb-${{ matrix.arch }}
path: build/nipovpn_${{ env.PACKAGE_VERSION }}_${{ matrix.arch }}.deb
build-termux:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
with:
path: nipovpn-src
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
git \
wget \
unzip \
curl \
python3 \
python3-pip \
build-essential \
cmake \
ninja-build \
pkg-config \
autoconf \
automake \
libtool \
autopoint \
bison \
flex \
gettext \
gperf \
help2man \
lzip \
libarchive-tools \
rsync \
texinfo \
jq
- name: Clone termux-packages
run: |
git clone --depth=1 https://github.com/termux/termux-packages.git
- name: Install Android NDK required by termux-packages
run: |
NDK_NUM="$(sed -n 's/^: "${TERMUX_NDK_VERSION_NUM:="\([0-9]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
NDK_REV="$(sed -n 's/^: "${TERMUX_NDK_REVISION:="\([a-z]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
if [ -z "$NDK_NUM" ]; then
echo "Could not read the NDK version from termux-packages/scripts/properties.sh"
grep -n NDK termux-packages/scripts/properties.sh || true
exit 1
fi
NDK_VERSION="r${NDK_NUM}${NDK_REV}"
echo "termux-packages requires Android NDK $NDK_VERSION"
mkdir -p "$HOME/lib"
cd "$HOME/lib"
wget -q "https://dl.google.com/android/repository/android-ndk-${NDK_VERSION}-linux.zip"
unzip -q "android-ndk-${NDK_VERSION}-linux.zip"
EXTRACTED_DIR="$(find "$HOME/lib" -maxdepth 1 -type d -name "android-ndk-${NDK_VERSION}*" | head -n 1)"
if [ -z "$EXTRACTED_DIR" ]; then
echo "Android NDK $NDK_VERSION directory not found"
ls -lah "$HOME/lib"
exit 1
fi
if [ "$EXTRACTED_DIR" != "$HOME/lib/android-ndk-${NDK_VERSION}" ]; then
ln -sfn "$EXTRACTED_DIR" "$HOME/lib/android-ndk-${NDK_VERSION}"
fi
echo "NDK=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
echo "ANDROID_NDK_ROOT=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
ls -ld "$HOME/lib/android-ndk-${NDK_VERSION}"
- name: Create Termux package recipe
run: |
mkdir -p termux-packages/packages/nipovpn
cat > termux-packages/packages/nipovpn/build.sh <<'EOF'
TERMUX_PKG_HOMEPAGE=https://github.com/MortezaBashsiz/nipovpn
TERMUX_PKG_DESCRIPTION="Powerful and secure HTTP/S proxy"
TERMUX_PKG_LICENSE="MIT"
TERMUX_PKG_MAINTAINER="Morteza Bashsiz"
TERMUX_PKG_VERSION=@PACKAGE_VERSION@
TERMUX_PKG_SRCURL=file://@GITHUB_WORKSPACE@/nipovpn-src
TERMUX_PKG_SHA256=SKIP_CHECKSUM
TERMUX_PKG_DEPENDS="openssl, boost, libyaml-cpp"
TERMUX_PKG_BUILD_IN_SRC=false
termux_step_configure() {
cmake -S "$TERMUX_PKG_SRCDIR" \
-B "$TERMUX_PKG_BUILDDIR" \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX="$TERMUX_PREFIX"
}
termux_step_make() {
cmake --build "$TERMUX_PKG_BUILDDIR" -j "$(nproc)"
}
termux_step_make_install() {
install -Dm755 \
"$TERMUX_PKG_BUILDDIR/core/nipovpn" \
"$TERMUX_PREFIX/bin/nipovpn"
if [ -d "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn" ]; then
mkdir -p "$TERMUX_PREFIX/etc/nipovpn"
cp -a "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn/." \
"$TERMUX_PREFIX/etc/nipovpn/"
fi
}
EOF
sed -i "s|@PACKAGE_VERSION@|${PACKAGE_VERSION}|g" termux-packages/packages/nipovpn/build.sh
sed -i "s|@GITHUB_WORKSPACE@|${GITHUB_WORKSPACE}|g" termux-packages/packages/nipovpn/build.sh
cat termux-packages/packages/nipovpn/build.sh
- name: Prepare Termux build data dir
run: |
sudo mkdir -p /data
sudo chown -R $USER:$USER /data
- name: Build Termux aarch64 package
working-directory: termux-packages
run: |
./build-package.sh -I -a aarch64 nipovpn
- name: Collect Termux package
run: |
mkdir -p out
TERMUX_DEB="$(find termux-packages/output -type f -name '*.deb' | head -n 1)"
if [ -z "$TERMUX_DEB" ]; then
echo "No Termux .deb package found"
find termux-packages/output -type f || true
exit 1
fi
cp "$TERMUX_DEB" "out/nipovpn_${PACKAGE_VERSION}_termux_aarch64.deb"
ls -lah out/
- name: Upload Termux package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-termux-aarch64
path: out/nipovpn_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
release:
needs:
- build
- build-termux
runs-on: ubuntu-latest
steps:
- name: Download package artifacts
uses: actions/download-artifact@v4
with:
pattern: nipovpn-*
merge-multiple: true
path: ./
- name: Show downloaded files
run: |
ls -lah
- name: Create main GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: v${{ env.PACKAGE_VERSION }}
name: Version v${{ env.PACKAGE_VERSION }}
prerelease: true
files: |
nipovpn_${{ env.PACKAGE_VERSION }}_amd64.deb
nipovpn_${{ env.PACKAGE_VERSION }}_arm64.deb
nipovpn_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
env:
GITHUB_TOKEN: ${{ github.token }}
-96
View File
@@ -1,96 +0,0 @@
name: Build and Release Debian Package - MORI
on:
push:
branches:
- mori
paths:
- 'core/src/**'
- 'core/**'
- 'nipovpn/**'
- '.github/workflows/debian-mori.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 0.2.${{ github.run_number }}
PACKAGE_FILE: nipovpn_mori_0.2.${{ github.run_number }}_amd64.deb
jobs:
build:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Set up dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
dpkg-dev \
build-essential \
lintian \
fakeroot \
devscripts \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
- name: Build binary
run: |
rm -rf build
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
- name: Build Debian package
run: |
mkdir -p nipovpn/usr/bin
cp build/core/nipovpn nipovpn/usr/bin/nipovpn
chmod 755 nipovpn/usr/bin/nipovpn
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" nipovpn/DEBIAN/control
echo "Final control file:"
cat nipovpn/DEBIAN/control
grep "^Version: ${PACKAGE_VERSION}$" nipovpn/DEBIAN/control
dpkg-deb --build nipovpn "build/${PACKAGE_FILE}"
- name: Show package information
run: |
dpkg -I "build/${PACKAGE_FILE}"
dpkg -c "build/${PACKAGE_FILE}"
- name: Upload Debian package as artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-mori-deb
path: build/${{ env.PACKAGE_FILE }}
release:
needs: build
runs-on: ubuntu-latest
steps:
- name: Download Debian package artifact
uses: actions/download-artifact@v4
with:
name: nipovpn-mori-deb
path: ./
- name: Create MORI GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: mori-v${{ env.PACKAGE_VERSION }}
name: MORI Version v${{ env.PACKAGE_VERSION }}
prerelease: true
files: ${{ env.PACKAGE_FILE }}
env:
GITHUB_TOKEN: ${{ github.token }}
-100
View File
@@ -1,100 +0,0 @@
name: Build and Release Debian Package - MAIN
on:
push:
branches:
- main
paths:
- 'core/src/**'
- 'core/**'
- 'nipovpn/**'
- '.github/workflows/debian.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 1.1.${{ github.run_number }}
PACKAGE_FILE: nipovpn_1.1.${{ github.run_number }}_amd64.deb
jobs:
build:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Set up dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
dpkg-dev \
build-essential \
lintian \
fakeroot \
devscripts \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
- name: Build binary
run: |
rm -rf build
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
- name: Build Debian package
run: |
mkdir -p nipovpn/usr/bin
cp build/core/nipovpn nipovpn/usr/bin/nipovpn
chmod 755 nipovpn/usr/bin/nipovpn
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" nipovpn/DEBIAN/control
echo "Final control file:"
cat nipovpn/DEBIAN/control
grep "^Version: ${PACKAGE_VERSION}$" nipovpn/DEBIAN/control
dpkg-deb --build nipovpn "build/${PACKAGE_FILE}"
- name: Show package information
run: |
dpkg -I "build/${PACKAGE_FILE}"
dpkg -c "build/${PACKAGE_FILE}"
- name: Upload Debian package as artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-main-deb
path: build/${{ env.PACKAGE_FILE }}
release:
needs: build
runs-on: ubuntu-latest
steps:
- name: Download Debian package artifact
uses: actions/download-artifact@v4
with:
name: nipovpn-main-deb
path: ./
- name: Check downloaded files
run: |
ls -lah
- name: Create MAIN GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: v${{ env.PACKAGE_VERSION }}
name: Version v${{ env.PACKAGE_VERSION }}
prerelease: false
files: ${{ env.PACKAGE_FILE }}
env:
GITHUB_TOKEN: ${{ github.token }}
+98
View File
@@ -0,0 +1,98 @@
name: Build Windows Binary - dev
on:
push:
branches:
- dev
paths:
- 'core/**'
- 'server/**'
- 'agent/**'
- 'CMakeLists.txt'
- '.github/workflows/windows-dev.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 0.1.${{ github.run_number }}
jobs:
build-windows:
runs-on: windows-latest
defaults:
run:
shell: msys2 {0}
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: MINGW64
update: true
install: >-
git
zip
mingw-w64-x86_64-gcc
mingw-w64-x86_64-cmake
mingw-w64-x86_64-ninja
mingw-w64-x86_64-boost
mingw-w64-x86_64-openssl
mingw-w64-x86_64-yaml-cpp
- name: Build nipovpn.exe
run: |
rm -rf build dist
mkdir -p build dist
cmake -S . -B build \
-G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CXX_FLAGS="-DNOMINMAX -DWIN32_LEAN_AND_MEAN -DNOGDI -DOUT=NIPO_OUT"
cmake --build build -j$(nproc)
cp build/core/nipovpn.exe dist/
- name: Copy required DLL files
run: |
cd dist
for dll in $(ldd nipovpn.exe | grep 'mingw64' | awk '{print $3}'); do
cp "$dll" .
done
ls -lah
- name: Add config files
run: |
mkdir -p dist/etc/nipovpn
if [ -d nipovpn/etc/nipovpn ]; then
cp -a nipovpn/etc/nipovpn/. dist/etc/nipovpn/
fi
- name: Create ZIP package
run: |
cd dist
zip -r ../nipovpn_dev_${PACKAGE_VERSION}_windows_x86_64.zip .
- name: Upload Windows artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-dev-windows-x86_64
path: nipovpn_dev_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
- name: Create dev Windows Release
uses: softprops/action-gh-release@v2
with:
tag_name: dev-windows-v${{ env.PACKAGE_VERSION }}
name: dev Windows Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: nipovpn_dev_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
env:
GITHUB_TOKEN: ${{ github.token }}
+99
View File
@@ -0,0 +1,99 @@
name: Build Windows Binary - main
on:
push:
branches:
- main
paths:
- 'core/**'
- 'server/**'
- 'agent/**'
- 'CMakeLists.txt'
- '.github/workflows/windows-main.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 1.1.60
jobs:
build-windows:
runs-on: windows-latest
defaults:
run:
shell: msys2 {0}
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: MINGW64
update: true
install: >-
git
zip
mingw-w64-x86_64-gcc
mingw-w64-x86_64-cmake
mingw-w64-x86_64-ninja
mingw-w64-x86_64-boost
mingw-w64-x86_64-openssl
mingw-w64-x86_64-yaml-cpp
- name: Build nipovpn.exe
run: |
rm -rf build dist
mkdir -p build dist
cmake -S . -B build \
-G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CXX_FLAGS="-DNOMINMAX -DWIN32_LEAN_AND_MEAN -DNOGDI -DOUT=NIPO_OUT"
cmake --build build -j$(nproc)
cp build/core/nipovpn.exe dist/
- name: Copy required DLL files
run: |
cd dist
for dll in $(ldd nipovpn.exe | grep 'mingw64' | awk '{print $3}'); do
cp "$dll" .
done
ls -lah
- name: Add config files
run: |
mkdir -p dist/etc/nipovpn
if [ -d nipovpn/etc/nipovpn ]; then
cp -a nipovpn/etc/nipovpn/. dist/etc/nipovpn/
fi
- name: Create ZIP package
run: |
cd dist
zip -r ../nipovpn_${PACKAGE_VERSION}_windows_x86_64.zip .
- name: Upload Windows artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-windows-x86_64
path: nipovpn_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
- name: Create Windows Release
uses: softprops/action-gh-release@v2
with:
tag_name: windows-v${{ env.PACKAGE_VERSION }}
name: Windows Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: nipovpn_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
env:
GITHUB_TOKEN: ${{ github.token }}
+7
View File
@@ -37,3 +37,10 @@ build
.idea
/cmake-build-debug/
test
.git
.github
*.deb
*.tar.gz
*.log
+4
View File
@@ -10,6 +10,10 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -ggdb")
# Set the preprocessor flags
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -MMD -MP")
if(POLICY CMP0167)
cmake_policy(SET CMP0167 NEW)
endif()
# https://cmake.org/cmake/help/latest/module/FindBoost.html
find_package(Boost REQUIRED COMPONENTS regex OPTIONAL_COMPONENTS system)
+39
View File
@@ -10,61 +10,100 @@ NipoVPN is a powerful proxy tool designed to conceal your HTTP requests within f
- HTTP Request Obfuscation: Hide your legitimate HTTP requests inside decoy requests to avoid detection.
- Boost Library Integration: Utilizes Boost for robust and reliable networking operations.
- High Performance: Optimized for speed and efficiency, ensuring minimal impact on request latency.
- Support HTTP and SOCKS5 on agent side
- Ability to use multiple Agents for one Server
## Usecases
### Bypass filtering
This could help you to bypass the filtering in your country.
![Filtering](https://github.com/MortezaBashsiz/nipovpn/blob/main/files/pic/archFilternet.png)
### Hide your requests in the Internet
If you want to hide your HTTP requests in the Internet, this proxy could help you.
![Internet](https://github.com/MortezaBashsiz/nipovpn/blob/main/files/pic/archInternet.png)
## Flow
Here you can see the logical flow of a single request from first step to get the response
![Flow](https://github.com/MortezaBashsiz/nipovpn/blob/main/files/pic/flow.png)
## Contribution
To contribute take a look at [contribution page](https://github.com/MortezaBashsiz/nipovpn/blob/main/CONTRIBUTING.md).
## Build
Build from source for [Linux](guides/BuildLinux.md)
## Docker
For running it with docker [Docker Guide](guides/Docker.md).
## Termux
Build from source for [Termux](guides/InstallTermux.md)
## Android Application
Official Android application [Android](https://github.com/MortezaBashsiz/nipovpn-android)
## Nix
For development, building, installation, and NixOS integration, see the [Nix Guide](guides/Nix.md).
## Run
#### Create directories
Create the log directory and log file
```bash
[~/nipovpn]>$ sudo mkdir /var/log/nipovpn/
[~/nipovpn]>$ sudo touch /var/log/nipovpn/nipovpn.log
```
Run it
```bash
sudo build/core/nipovpn server nipovpn/etc/nipovpn/config.yaml
```
AES-256-GCM payload encryption is enabled by default. The key is derived from
`general.token`, which must be at least 32 bytes and identical on the agent and
server. Replace the sample token, e.g. with the output of `openssl rand -hex 16`.
To disable payload encryption, set `general.aesEnable: false` in both the agent
and server configuration. This setting is independent of `general.tlsEnable`;
without either, traffic is not encrypted.
> **Protocol change:** this version uses AES-256-GCM and carries the session and
> action inside the encrypted body instead of `X-Nipo-*` headers. It is not
> compatible with older agents, servers or the Android app; upgrade all of them
> together.
### Package
#### Install
Currently it is only available for debian-based Linuxes and fully tested on ubuntu 24.04
You can simply download and install the package. To download it please visit the [releases page](https://github.com/MortezaBashsiz/nipovpn/tags) and get the latest release.
```bash
[~]>$ sudo apt install ./nipovpn.deb
```
#### Run
There are systemd services to manage the nipovpn process.
`nipovpn-server.service` to manage as server.
`nipovpn-agent.service` to manage as agent.
```bash
[~]>$ sudo systemctl start nipovpn-server.service
[~]>$ cat /var/log/nipovpn/nipovpn.log
+4
View File
@@ -38,3 +38,7 @@ target_include_directories(${CORE_TARGET} PUBLIC ${OPENSSL_INCLUDE_DIR})
target_link_libraries(${CORE_TARGET} ${Boost_LIBRARIES})
target_link_libraries(${CORE_TARGET} ${YAML_CPP_LIBRARIES})
target_link_libraries(${CORE_TARGET} ${OPENSSL_LIBRARIES})
if(WIN32)
target_link_libraries(${CORE_TARGET} ws2_32 mswsock)
endif()
+25 -15
View File
@@ -1,21 +1,22 @@
#include "agenthandler.hpp"
#include <sstream>
#include <utility>
AgentHandler::AgentHandler(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid)
: config_(config),
log_(log),
client_(client),
client_(std::move(client)),
readBuffer_(readBuffer),
writeBuffer_(writeBuffer),
request_(HTTP::create(config, log, readBuffer, uuid)),
clientConnStr_(clientConnStr),
clientConnStr_(std::move(clientConnStr)),
uuid_(uuid) {
end_ = false;
connect_ = false;
@@ -37,7 +38,7 @@ void AgentHandler::handle() {
if (request_->parsedHttpRequest().target().length() > 0) {
log_->write("[" + to_string(uuid_) + "] [FORWARD] [SRC " + clientConnStr_ + "] [DST " +
std::string(request_->parsedHttpRequest().target()) + "]",
Log::Level::INFO);
Log::Level::TRACE);
}
if (config_->general().tlsEnable && !client_->tlsEnabled()) {
@@ -59,6 +60,10 @@ void AgentHandler::handle() {
Log::Level::INFO);
client_->socketShutdown();
return;
} else {
log_->write("[" + to_string(uuid_) + "] [CONNECT] [SRC " +
clientConnStr_ + "] [ORIGIN " + std::string(request_->parsedHttpRequest().target()) + "]",
Log::Level::INFO);
}
if (client_->tlsEnabled() && !client_->doHandshakeClient()) {
@@ -71,8 +76,15 @@ void AgentHandler::handle() {
}
}
const std::string action =
request_->httpType() == HTTP::HttpType::connect ? "open" : "request";
BoolStr encryption{false, std::string("FAILED")};
encryption = aes256Encrypt(hexStreambufToStr(readBuffer_), config_->general().token);
const std::string payload =
makeEnvelope(action, to_string(uuid_), hexStreambufToStr(readBuffer_));
encryption = config_->general().aesEnable
? aes256Encrypt(payload, config_->general().token)
: BoolStr{true, payload};
if (!encryption.ok) {
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Encryption Failed] : [ " +
encryption.message + "] ",
@@ -82,8 +94,6 @@ void AgentHandler::handle() {
}
const std::string innerRequest = encode64(encryption.message);
const std::string action =
request_->httpType() == HTTP::HttpType::connect ? "open" : "request";
std::ostringstream outer;
const bool directTunnelOpen =
@@ -94,9 +104,7 @@ void AgentHandler::handle() {
<< "Host: " << relayHostHeader(config_) << "\r\n"
<< "User-Agent: " << config_->agent().userAgent << "\r\n"
<< "Accept: */*\r\n"
<< "Content-Type: application/text\r\n"
<< "X-Nipo-Session: " << to_string(uuid_) << "\r\n"
<< "X-Nipo-Action: " << action << "\r\n"
<< "Content-Type: text/plain; charset=utf-8\r\n"
<< "Content-Length: " << innerRequest.size() << "\r\n"
<< "Connection: "
<< ((config_->general().connectionReuse || directTunnelOpen) ? "keep-alive" : "close")
@@ -124,14 +132,16 @@ void AgentHandler::handle() {
return;
}
const std::string encryptedBody = outerResponse.substr(bodyPos + 4);
if (encryptedBody.empty()) {
const std::string responseBody = outerResponse.substr(bodyPos + 4);
if (responseBody.empty()) {
client_->socketShutdown();
return;
}
BoolStr decryption{false, std::string("FAILED")};
decryption = aes256Decrypt(encryptedBody, config_->general().token);
decryption = config_->general().aesEnable
? aes256Decrypt(responseBody, config_->general().token)
: BoolStr{true, responseBody};
if (!decryption.ok) {
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Failed] : [ " +
decryption.message + "] ",
@@ -141,7 +151,7 @@ void AgentHandler::handle() {
}
copyStringToStreambuf(decryption.message, writeBuffer_);
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Done]",
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Payload Decoded]",
Log::Level::DEBUG);
connect_ = request_->httpType() == HTTP::HttpType::connect;
+9 -11
View File
@@ -18,8 +18,8 @@ public:
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid) {
return pointer(new AgentHandler(readBuffer, writeBuffer, config, log,
client, clientConnStr, uuid));
@@ -29,9 +29,7 @@ public:
void handle();
inline const HTTP::pointer &request() & { return request_; }
inline const HTTP::pointer &&request() && { return std::move(request_); }
inline const HTTP::pointer &request() const { return request_; }
bool end_;
bool connect_;
@@ -41,18 +39,18 @@ private:
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid);
std::string relayHostHeader(const std::shared_ptr<Config> &config);
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
const TCPClient::pointer &client_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
TCPClient::pointer client_;
boost::asio::streambuf &readBuffer_;
boost::asio::streambuf &writeBuffer_;
HTTP::pointer request_;
const std::string &clientConnStr_;
std::string clientConnStr_;
boost::uuids::uuid uuid_;
+24 -18
View File
@@ -1,7 +1,7 @@
#include "config.hpp"
Config::Config(const RunMode &mode, const std::string &filePath)
Config::Config(RunMode mode, const std::string &filePath)
: runMode_(mode),
filePath_(filePath),
configYaml_(YAML::LoadFile(filePath)),
@@ -9,30 +9,33 @@ Config::Config(const RunMode &mode, const std::string &filePath)
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>(),
configYaml_["general"]["pullTimeout"].as<unsigned short>(),
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>(),
log_({configYaml_["log"]["logLevel"].as<std::string>("INFO"),
configYaml_["log"]["logFile"].as<std::string>()}),
server_({configYaml_["server"]["threads"].as<unsigned short>(),
configYaml_["server"]["listenIp"].as<std::string>(),
configYaml_["server"]["listenPort"].as<unsigned short>()}),
agent_({configYaml_["agent"]["threads"].as<unsigned short>(),
configYaml_["agent"]["listenIp"].as<std::string>(),
configYaml_["agent"]["listenPort"].as<unsigned short>(),
configYaml_["agent"]["serverIp"].as<std::string>(),
configYaml_["agent"]["serverPort"].as<unsigned short>(),
configYaml_["agent"]["httpVersion"].as<std::string>(),
configYaml_["agent"]["userAgent"].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_);
@@ -72,7 +75,9 @@ std::string Config::toString() const {
ss << "\nConfig :\n"
<< " General :\n"
<< " token: " << general_.token << "\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) {
@@ -110,6 +115,7 @@ std::string Config::toString() const {
<< " 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"
@@ -157,7 +163,7 @@ const Config::Agent &Config::agent() const {
return agent_;
}
const unsigned short &Config::threads() const {
unsigned short Config::threads() const {
std::lock_guard<std::mutex> lock(configMutex_);
return threads_;
}
@@ -177,7 +183,7 @@ void Config::listenIp(const std::string &ip) {
listenIp_ = ip;
}
const unsigned short &Config::listenPort() const {
unsigned short Config::listenPort() const {
std::lock_guard<std::mutex> lock(configMutex_);
return listenPort_;
}
@@ -187,7 +193,7 @@ void Config::listenPort(unsigned short port) {
listenPort_ = port;
}
const RunMode &Config::runMode() const {
RunMode Config::runMode() const {
std::lock_guard<std::mutex> lock(configMutex_);
return runMode_;
}
+10 -7
View File
@@ -20,6 +20,8 @@ class Config : private Uncopyable {
private:
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;
@@ -27,6 +29,7 @@ private:
unsigned short pullTimeout;
bool tunnelEnable;
bool connectionReuse;
bool aesEnable;
bool tlsEnable;
bool tlsVerifyPeer;
std::string tlsCertFile;
@@ -55,9 +58,9 @@ private:
std::string userAgent;
};
const RunMode &runMode_;
RunMode runMode_;
std::string filePath_;
const YAML::Node configYaml_;
YAML::Node configYaml_;
unsigned short threads_;
std::string listenIp_;
@@ -65,12 +68,12 @@ private:
mutable std::mutex configMutex_;
explicit Config(const RunMode &mode, const std::string &filePath);
explicit Config(RunMode mode, const std::string &filePath);
public:
using pointer = std::shared_ptr<Config>;
static pointer create(const RunMode &mode, const std::string &filePath) {
static pointer create(RunMode mode, const std::string &filePath) {
return pointer(new Config(mode, filePath));
}
@@ -88,7 +91,7 @@ public:
const Server &server() const;
const Agent &agent() const;
const unsigned short &threads() const;
unsigned short threads() const;
void threads(unsigned short threads);
@@ -96,11 +99,11 @@ public:
void listenIp(const std::string &ip);
const unsigned short &listenPort() const;
unsigned short listenPort() const;
void listenPort(unsigned short port);
const RunMode &runMode() const;
RunMode runMode() const;
const std::string &filePath() const;
+117 -49
View File
@@ -19,10 +19,15 @@
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
static constexpr std::size_t BufferSize = 65536;
static constexpr std::size_t MinTokenLength = 32;
static constexpr const char *SampleToken = "af445adb-2434-4975-9445-2c1b2231";
class Uncopyable {
public:
Uncopyable() = default;
@@ -86,7 +91,7 @@ inline std::string hexArrToStr(const unsigned char *data, std::size_t size) {
}
inline unsigned int hexToInt(const std::string &hexString) {
unsigned short result;
unsigned int result{};
std::stringstream hexStr(hexString);
hexStr >> std::hex >> result;
return result;
@@ -181,111 +186,131 @@ inline std::string encode64(const std::string &inputStr) {
return encoded;
}
static constexpr std::size_t AesGcmNonceLength = 12;
static constexpr std::size_t AesGcmTagLength = 16;
inline std::string deriveAesKey(const std::string &token) {
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digestLen = 0;
EVP_Digest(token.data(), token.size(), digest, &digestLen, EVP_sha256(), NULL);
return std::string(reinterpret_cast<char *>(digest), digestLen);
}
inline BoolStr aes256Encrypt(const std::string &plaintext,
const std::string &key) {
const std::string &token) {
BoolStr result{false, "Encryption failed"};
unsigned char iv[EVP_MAX_IV_LENGTH];
if (!RAND_bytes(iv, sizeof(iv))) {
result.message = "IV generation failed";
const std::string key = deriveAesKey(token);
unsigned char nonce[AesGcmNonceLength];
if (!RAND_bytes(nonce, sizeof(nonce))) {
result.message = "Nonce generation failed";
return result;
}
int ciphertext_len =
plaintext.size() + EVP_CIPHER_block_size(EVP_aes_256_cbc());
std::vector<unsigned char> ciphertext(ciphertext_len);
std::vector<unsigned char> ciphertext(plaintext.size());
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
using EvpCipherCtxPtr = std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)>;
EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
if (!ctx) {
result.message = "Context initialization failed";
return result;
}
if (EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
reinterpret_cast<const unsigned char *>(key.c_str()),
iv) != 1) {
EVP_CIPHER_CTX_free(ctx);
if (EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL) != 1 ||
EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, AesGcmNonceLength, NULL) != 1 ||
EVP_EncryptInit_ex(ctx.get(), NULL, NULL,
reinterpret_cast<const unsigned char *>(key.data()),
nonce) != 1) {
result.message = "Encryption initialization failed";
return result;
}
int len;
int len = 0;
if (EVP_EncryptUpdate(
ctx, ciphertext.data(), &len,
reinterpret_cast<const unsigned char *>(plaintext.c_str()),
ctx.get(), ciphertext.data(), &len,
reinterpret_cast<const unsigned char *>(plaintext.data()),
plaintext.size()) != 1) {
EVP_CIPHER_CTX_free(ctx);
result.message = "Encryption update failed";
return result;
}
ciphertext_len = len;
int ciphertext_len = len;
if (EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len) != 1) {
EVP_CIPHER_CTX_free(ctx);
if (EVP_EncryptFinal_ex(ctx.get(), ciphertext.data() + len, &len) != 1) {
result.message = "Encryption finalization failed";
return result;
}
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
unsigned char tag[AesGcmTagLength];
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, AesGcmTagLength, tag) != 1) {
result.message = "Tag generation failed";
return result;
}
std::string final_result(reinterpret_cast<char *>(iv), sizeof(iv));
final_result.append(reinterpret_cast<char *>(ciphertext.data()),
ciphertext_len);
std::string final_result(reinterpret_cast<char *>(nonce), sizeof(nonce));
final_result.append(reinterpret_cast<char *>(ciphertext.data()), ciphertext_len);
final_result.append(reinterpret_cast<char *>(tag), sizeof(tag));
result.ok = true;
result.message = final_result;
return result;
}
inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
const std::string &key) {
inline BoolStr aes256Decrypt(const std::string &sealed,
const std::string &token) {
BoolStr result{false, "Decryption failed"};
unsigned char iv[EVP_MAX_IV_LENGTH];
std::memcpy(iv, ciphertext_with_iv.c_str(),
EVP_CIPHER_iv_length(EVP_aes_256_cbc()));
if (sealed.size() < AesGcmNonceLength + AesGcmTagLength) {
result.message = "Ciphertext too short";
return result;
}
std::string ciphertext =
ciphertext_with_iv.substr(EVP_CIPHER_iv_length(EVP_aes_256_cbc()));
const std::string key = deriveAesKey(token);
int max_plaintext_len = ciphertext.size();
std::vector<unsigned char> plaintext(max_plaintext_len);
const auto *nonce = reinterpret_cast<const unsigned char *>(sealed.data());
const auto *ciphertext = nonce + AesGcmNonceLength;
const std::size_t ciphertextLen = sealed.size() - AesGcmNonceLength - AesGcmTagLength;
std::string tag = sealed.substr(sealed.size() - AesGcmTagLength);
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
std::vector<unsigned char> plaintext(ciphertextLen);
using EvpCipherCtxPtr = std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)>;
EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
if (!ctx) {
result.message = "Context initialization failed";
return result;
}
if (EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
reinterpret_cast<const unsigned char *>(key.c_str()),
iv) != 1) {
EVP_CIPHER_CTX_free(ctx);
if (EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL) != 1 ||
EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, AesGcmNonceLength, NULL) != 1 ||
EVP_DecryptInit_ex(ctx.get(), NULL, NULL,
reinterpret_cast<const unsigned char *>(key.data()),
nonce) != 1) {
result.message = "Decryption initialization failed";
return result;
}
int len;
if (EVP_DecryptUpdate(
ctx, plaintext.data(), &len,
reinterpret_cast<const unsigned char *>(ciphertext.c_str()),
ciphertext.size()) != 1) {
EVP_CIPHER_CTX_free(ctx);
int len = 0;
if (EVP_DecryptUpdate(ctx.get(), plaintext.data(), &len, ciphertext,
ciphertextLen) != 1) {
result.message = "Decryption update failed";
return result;
}
int plaintext_len = len;
if (EVP_DecryptFinal_ex(ctx, plaintext.data() + len, &len) != 1) {
EVP_CIPHER_CTX_free(ctx);
result.message = "Decryption finalization failed";
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, AesGcmTagLength,
tag.data()) != 1) {
result.message = "Setting tag failed";
return result;
}
if (EVP_DecryptFinal_ex(ctx.get(), plaintext.data() + len, &len) != 1) {
result.message = "Authentication failed (wrong token or tampered payload)";
return result;
}
plaintext_len += len;
EVP_CIPHER_CTX_free(ctx);
result.ok = true;
result.message =
std::string(reinterpret_cast<char *>(plaintext.data()), plaintext_len);
@@ -293,6 +318,31 @@ inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
return result;
}
inline std::string makeEnvelope(const std::string &action,
const std::string &session,
const std::string &data) {
return action + "\n" + session + "\n" + data;
}
struct Envelope {
std::string action;
std::string session;
std::string data;
};
inline bool parseEnvelope(const std::string &raw, Envelope &out) {
const auto actionEnd = raw.find('\n');
if (actionEnd == std::string::npos) return false;
const auto sessionEnd = raw.find('\n', actionEnd + 1);
if (sessionEnd == std::string::npos) return false;
out.action = raw.substr(0, actionEnd);
out.session = raw.substr(actionEnd + 1, sessionEnd - actionEnd - 1);
out.data = raw.substr(sessionEnd + 1);
return true;
}
inline BoolStr validateConfig(int argc, const char *argv[]) {
BoolStr result{false, "Validation failed"};
@@ -325,6 +375,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>>();
@@ -364,6 +416,22 @@ 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";
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 (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";
return result;
}
result.ok = true;
result.message = "OK";
return result;
+81 -38
View File
@@ -155,7 +155,7 @@ bool HTTP::parseTls() {
return false;
}
const std::string HTTP::genHttpPostReqString(const std::string &body) const {
std::string HTTP::genHttpPostReqString(const std::string &body) const {
auto fakeUrl = config_->randomFakeUrl();
return std::string(config_->randomMethod() + " " +
fakeUrl + " HTTP/" +
@@ -167,7 +167,7 @@ const std::string HTTP::genHttpPostReqString(const std::string &body) const {
"Content-Type: application/x-www-form-urlencoded\r\n" + "\r\n" + body + "COMP\r\n\r\n";
}
const std::string HTTP::genHttpRestPostReqString() const {
std::string HTTP::genHttpRestPostReqString() const {
auto fakeUrl = config_->randomFakeUrl();
return std::string(config_->randomMethod() + " " +
fakeUrl + " HTTP/" +
@@ -178,7 +178,7 @@ const std::string HTTP::genHttpRestPostReqString() const {
"Rest: yes\r\n" + "COMP\r\n\r\n";
}
const std::string HTTP::genHttpOkResString(const std::string &body) const {
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" +
"Content-Length: " + std::to_string(body.length()) + "\r\n" +
@@ -186,26 +186,83 @@ const 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,
unsigned short defaultPort) {
host.clear();
port = defaultPort;
if (input.empty()) return false;
auto parsePort = [](const std::string &value,
unsigned short &out) -> bool {
try {
int p = std::stoi(value);
if (p < 1 || p > 65535) return false;
out = static_cast<unsigned short>(p);
return true;
} catch (...) {
return false;
}
};
if (input.front() == '[') {
auto close = input.find(']');
if (close == std::string::npos) return false;
host = input.substr(1, close - 1);
if (close + 1 < input.size()) {
if (input[close + 1] != ':') return false;
if (!parsePort(input.substr(close + 2), port)) return false;
}
return !host.empty();
}
auto firstColon = input.find(':');
auto lastColon = input.rfind(':');
if (firstColon != std::string::npos && firstColon != lastColon) {
const std::string maybePort = input.substr(lastColon + 1);
unsigned short parsedPort = defaultPort;
if (parsePort(maybePort, parsedPort)) {
host = input.substr(0, lastColon);
port = parsedPort;
return !host.empty();
}
host = input;
port = defaultPort;
return true;
}
if (lastColon != std::string::npos) {
host = input.substr(0, lastColon);
if (!parsePort(input.substr(lastColon + 1), port)) return false;
} else {
host = input;
port = defaultPort;
}
return !host.empty();
}
void HTTP::setIPPort() {
std::string target{};
std::vector<std::string> splitted;
switch (httpType()) {
case HTTP::HttpType::https: {
target = parsedTlsRequest_.sni;
splitted = splitString(target, ":");
if (!splitted.empty()) {
dstIP_ = splitted[0];
if (splitted.size() > 1 && !splitted[1].empty()) {
dstPort_ = std::stoi(splitted[1]);
} else {
dstPort_ = 443;
}
} else {
dstIP_.clear();
if (!parseHostPort(target, dstIp_, dstPort_, 443)) {
dstIp_.clear();
dstPort_ = 443;
}
break;
}
@@ -234,51 +291,37 @@ void HTTP::setIPPort() {
log_->write("[" + to_string(uuid_) +
"] [HTTP setIPPort] missing Host header",
Log::Level::DEBUG);
dstIP_.clear();
dstIp_.clear();
dstPort_ = 80;
break;
}
}
splitted = splitString(hostPort, ":");
if (!splitted.empty()) {
dstIP_ = splitted[0];
if (splitted.size() > 1 && !splitted[1].empty()) {
dstPort_ = std::stoi(splitted[1]);
} else {
dstPort_ = 80;
}
} else {
if (!parseHostPort(hostPort, dstIp_, dstPort_, 80)) {
log_->write("[" + to_string(uuid_) +
"] [HTTP setIPPort] wrong request",
Log::Level::DEBUG);
dstIP_.clear();
dstIp_.clear();
dstPort_ = 80;
}
break;
}
case HTTP::HttpType::connect: {
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
splitted = splitString(target, ":");
if (!splitted.empty()) {
dstIP_ = splitted[0];
if (splitted.size() > 1 && !splitted[1].empty()) {
dstPort_ = std::stoi(splitted[1]);
} else {
dstPort_ = 443;
}
} else {
dstIP_.clear();
if (!parseHostPort(target, dstIp_, dstPort_, 443)) {
dstIp_.clear();
dstPort_ = 443;
}
break;
}
}
}
const std::string HTTP::tlsTypeToString() const {
std::string HTTP::tlsTypeToString() const {
switch (parsedTlsRequest_.type) {
case TlsTypes::TLSHandshake:
return "TLSHandshake";
@@ -291,7 +334,7 @@ const std::string HTTP::tlsTypeToString() const {
}
}
const std::string HTTP::toString() const {
std::string HTTP::toString() const {
switch (httpType()) {
case HTTP::HttpType::https:
return std::string("\n") + "TLS Type : " + tlsTypeToString() + "\n" +
@@ -327,7 +370,7 @@ const std::string HTTP::toString() const {
}
}
const std::string HTTP::restoString() const {
std::string HTTP::restoString() const {
return std::string("\n") +
boost::lexical_cast<std::string>(parsedHttpResponse_.base()) + "\n" +
"Body Size : " +
+17 -12
View File
@@ -43,10 +43,15 @@ public:
~HTTP();
inline const HTTP::HttpType &httpType() const { return httpType_; }
inline HTTP::HttpType httpType() const { return httpType_; }
inline void httpType(const HTTP::HttpType &httpType) { httpType_ = httpType; }
static bool parseHostPort(const std::string &input,
std::string &host,
unsigned short &port,
unsigned short defaultPort);
bool detectType();
bool parseHttp();
@@ -55,11 +60,11 @@ public:
bool parseTls();
const std::string genHttpPostReqString(const std::string &body) const;
std::string genHttpPostReqString(const std::string &body) const;
const std::string genHttpRestPostReqString() const;
std::string genHttpRestPostReqString() const;
const std::string genHttpOkResString(const std::string &body) const;
std::string genHttpOkResString(const std::string &body) const;
inline const boost::beast::http::request<boost::beast::http::string_body> &
parsedHttpRequest() & {
@@ -73,15 +78,15 @@ public:
inline const TlsRequest &parsedTlsRequest() & { return parsedTlsRequest_; }
const std::string tlsTypeToString() const;
std::string tlsTypeToString() const;
inline const std::string &dstIP() { return dstIP_; }
inline const std::string &dstIp() const { return dstIp_; }
inline const unsigned short &dstPort() { return dstPort_; }
inline unsigned short dstPort() const { return dstPort_; }
const std::string toString() const;
std::string toString() const;
const std::string restoString() const;
std::string restoString() const;
private:
explicit HTTP(const std::shared_ptr<Config> &config,
@@ -91,8 +96,8 @@ private:
void setIPPort();
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::streambuf &buffer_;
boost::beast::http::parser<false, boost::beast::http::string_body> parser_;
@@ -100,7 +105,7 @@ private:
boost::beast::http::response<boost::beast::http::string_body> parsedHttpResponse_;
HttpType httpType_;
std::string dstIP_;
std::string dstIp_;
unsigned short dstPort_;
TlsRequest parsedTlsRequest_;
boost::uuids::uuid uuid_;
+126
View File
@@ -0,0 +1,126 @@
#pragma once
#include <algorithm>
#include <cctype>
#include <sstream>
#include <string>
namespace http_utils {
inline std::string makeHostPort(const std::string &host, uint16_t port) {
if (host.find(':') != std::string::npos &&
!(host.size() >= 2 && host.front() == '[' && host.back() == ']')) {
return "[" + host + "]:" + std::to_string(port);
}
return host + ":" + std::to_string(port);
}
inline std::string toLowerCopy(std::string value) {
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return value;
}
inline std::string trimCopy(std::string value) {
while (!value.empty() && (value.front() == ' ' || value.front() == '\t')) {
value.erase(value.begin());
}
while (!value.empty() &&
(value.back() == ' ' ||
value.back() == '\t' ||
value.back() == '\r' ||
value.back() == '\n')) {
value.pop_back();
}
return value;
}
inline std::string extractHeaders(const std::string &message) {
const auto pos = message.find("\r\n\r\n");
if (pos == std::string::npos) {
return {};
}
return message.substr(0, pos + 4);
}
inline std::string extractBody(const std::string &message) {
const auto pos = message.find("\r\n\r\n");
if (pos == std::string::npos) {
return {};
}
return message.substr(pos + 4);
}
inline bool parseContentLength(const std::string &headers, std::size_t &value) {
std::istringstream iss(headers);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
const auto lower = toLowerCopy(line);
if (lower.rfind("content-length:", 0) == 0) {
auto raw = line.substr(std::string("Content-Length:").size());
raw.erase(0, raw.find_first_not_of(" \t"));
try {
value = static_cast<std::size_t>(std::stoull(raw));
return true;
} catch (...) {
return false;
}
}
}
return false;
}
inline bool isChunked(const std::string &headers) {
std::istringstream iss(headers);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
const auto lower = toLowerCopy(line);
if (lower.rfind("transfer-encoding:", 0) == 0 &&
lower.find("chunked") != std::string::npos) {
return true;
}
}
return false;
}
inline std::string getRawHeader(const std::string &headers, const std::string &name) {
std::istringstream iss(headers);
std::string line;
const std::string prefix = toLowerCopy(name) + ":";
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
const std::string lower = toLowerCopy(line);
if (lower.rfind(prefix, 0) == 0) {
return trimCopy(line.substr(name.size() + 1));
}
}
return {};
}
}// namespace http_utils
+2 -4
View File
@@ -10,7 +10,6 @@
#include "config.hpp"
#include "general.hpp"
class Log : private Uncopyable {
public:
enum class Level {
@@ -28,10 +27,9 @@ public:
explicit Log(const std::shared_ptr<Log> &log);
~Log();
const std::shared_ptr<Config> &config() const { return config_; }
std::shared_ptr<Config> config() const { return config_; }
Level level() const { return level_; }
@@ -42,7 +40,7 @@ private:
static std::string levelToString(Level level);
const std::shared_ptr<Config> &config_;
std::shared_ptr<Config> config_;
Level level_;
std::string mode_;
+3 -3
View File
@@ -12,6 +12,9 @@ int main(int argc, char const *argv[]) {
return 1;
}
std::string mode(argv[1]);
RunMode runMode_ = (mode == "agent") ? RunMode::agent : RunMode::server;
BoolStr configValidation = validateConfig(argc, argv);
if (!configValidation.ok) {
std::cerr << "Configuration validation failed: " << configValidation.message
@@ -19,9 +22,6 @@ int main(int argc, char const *argv[]) {
return 1;
}
std::string mode(argv[1]);
RunMode runMode_ = (mode == "agent") ? RunMode::agent : RunMode::server;
Config::pointer config_ = Config::create(runMode_, std::string(argv[2]));
Log::pointer log_ = Log::create(config_);
+7
View File
@@ -25,6 +25,13 @@ 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);
}
auto tcpServer = TCPServer::create(io_context_, config_, log_);
for (auto i = 0; i < config_->threads(); ++i) {
+9 -3
View File
@@ -7,6 +7,12 @@
#include <thread>
#include <vector>
#if defined(__ANDROID__)
using runnerThread = std::thread;
#else
using runnerThread = std::jthread;
#endif
#include "config.hpp"
#include "log.hpp"
#include "tcpserver.hpp"
@@ -25,8 +31,8 @@ private:
void stop();
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context io_context_;
@@ -34,7 +40,7 @@ private:
std::atomic<bool> running_;
std::vector<std::jthread> threadPool_;
std::vector<runnerThread> threadPool_;
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
};
+64 -95
View File
@@ -1,83 +1,45 @@
#include "serverhandler.hpp"
#include <algorithm>
#include <cctype>
#include <sstream>
#include <utility>
#include <vector>
#include "http_utils.hpp"
std::mutex ServerHandler::sessionsMutex_;
std::unordered_map<std::string, TCPClient::pointer> ServerHandler::sessions_;
std::string ServerHandler::HttpUtils::lowerCopy(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return s;
return http_utils::toLowerCopy(std::move(s));
}
std::string ServerHandler::HttpUtils::trimCopy(std::string s) {
while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) {
s.erase(s.begin());
}
while (!s.empty() &&
(s.back() == ' ' ||
s.back() == '\t' ||
s.back() == '\r' ||
s.back() == '\n')) {
s.pop_back();
}
return s;
return http_utils::trimCopy(std::move(s));
}
std::string ServerHandler::HttpUtils::getRawHeader(const std::string &headers,
const std::string &name) {
std::istringstream iss(headers);
std::string line;
const std::string prefix = lowerCopy(name) + ":";
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
std::string lower = lowerCopy(line);
if (lower.rfind(prefix, 0) == 0) {
return trimCopy(line.substr(name.size() + 1));
}
}
return "";
return http_utils::getRawHeader(headers, name);
}
std::string ServerHandler::HttpUtils::extractHttpBody(const std::string &msg) {
const auto pos = msg.find("\r\n\r\n");
if (pos == std::string::npos) {
return "";
}
return msg.substr(pos + 4);
return http_utils::extractBody(msg);
}
ServerHandler::ServerHandler(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid)
: config_(config),
log_(log),
client_(client),
client_(std::move(client)),
readBuffer_(readBuffer),
writeBuffer_(writeBuffer),
request_(HTTP::create(config, log, readBuffer, uuid)),
clientConnStr_(clientConnStr),
clientConnStr_(std::move(clientConnStr)),
uuid_(uuid) {
end_ = false;
connect_ = false;
@@ -91,7 +53,7 @@ void ServerHandler::makePlainHttpResponse(const std::string &body,
std::ostringstream outer;
outer << "HTTP/1.1 " << status << "\r\n"
<< "Content-Type: application/text\r\n"
<< "Content-Type: application/octet-stream\r\n"
<< "Content-Length: " << body.size() << "\r\n"
<< "Connection: " << connection << "\r\n"
<< "\r\n"
@@ -103,10 +65,12 @@ void ServerHandler::makePlainHttpResponse(const std::string &body,
connect_ = false;
}
void ServerHandler::makeEncryptedHttpResponse(const std::string &plainBody,
const std::string &status,
const std::string &connection) {
BoolStr encryption = aes256Encrypt(plainBody, config_->general().token);
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};
if (!encryption.ok) {
log_->write("[" + to_string(uuid_) + "] [ServerHandler] [Encryption Failed] " + encryption.message,
@@ -136,17 +100,6 @@ void ServerHandler::handle() {
const auto &outerReq = request_->parsedHttpRequest();
const std::string outerRaw = streambufToString(readBuffer_);
const auto outerHeaderEnd = outerRaw.find("\r\n\r\n");
const std::string outerHeaders =
outerHeaderEnd == std::string::npos
? ""
: outerRaw.substr(0, outerHeaderEnd + 2);
const std::string session =
HttpUtils::getRawHeader(outerHeaders, "X-Nipo-Session");
const std::string action =
HttpUtils::getRawHeader(outerHeaders, "X-Nipo-Action");
std::string requestBody = std::string(outerReq.body());
@@ -157,9 +110,10 @@ void ServerHandler::handle() {
BoolStr decryption{false, std::string("FAILED")};
try {
decryption = aes256Decrypt(
decode64(requestBody),
config_->general().token);
const std::string payload = decode64(requestBody);
decryption = config_->general().aesEnable
? aes256Decrypt(payload, config_->general().token)
: BoolStr{true, payload};
} catch (const std::exception &e) {
log_->write(
"[" + to_string(uuid_) +
@@ -181,8 +135,23 @@ void ServerHandler::handle() {
return;
}
Envelope envelope;
if (!parseEnvelope(decryption.message, envelope)) {
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [Invalid Envelope] (agent and server versions or aesEnable may differ)",
Log::Level::DEBUG);
makePlainHttpResponse("", "400 Bad Request", "close");
return;
}
const std::string &action = envelope.action;
const std::string &session = envelope.session;
decryption.message = std::move(envelope.data);
log_->write(
"[" + to_string(uuid_) + "] [ServerHandler handle] [Decryption Done]",
"[" + to_string(uuid_) + "] [ServerHandler handle] [Payload Decoded]",
Log::Level::DEBUG);
if (action == "send") {
@@ -198,7 +167,7 @@ void ServerHandler::handle() {
}
if (!targetClient || !targetClient->isOpen()) {
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
@@ -206,7 +175,7 @@ void ServerHandler::handle() {
copyStringToStreambuf(hexToASCII(decryption.message), tunnelBuf);
targetClient->doWrite(tunnelBuf);
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
@@ -223,7 +192,7 @@ void ServerHandler::handle() {
}
if (!targetClient || !targetClient->isOpen()) {
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
@@ -231,21 +200,21 @@ void ServerHandler::handle() {
std::size_t available = targetClient->socket().available(ec);
if (ec || available == 0) {
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
std::vector<char> data(std::min<std::size_t>(available, 65536));
std::vector<char> data(std::min<std::size_t>(available, config_->general().bufferSize));
std::size_t n = targetClient->socket().read_some(
boost::asio::buffer(data),
ec);
if (ec || n == 0) {
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
makeEncryptedHttpResponse(
makePayloadHttpResponse(
std::string(data.data(), n),
"200 OK",
(config_->general().connectionReuse ? "keep-alive" : "close"));
@@ -262,7 +231,7 @@ void ServerHandler::handle() {
sessions_.erase(it);
}
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
@@ -276,7 +245,7 @@ void ServerHandler::handle() {
"] [ServerHandler handle] [INNER REQUEST MISSING HEADER END]",
Log::Level::DEBUG);
makeEncryptedHttpResponse("", "400 Bad Request", "close");
makePayloadHttpResponse("", "400 Bad Request", "close");
return;
}
@@ -294,22 +263,22 @@ void ServerHandler::handle() {
streambufToString(readBuffer_),
Log::Level::DEBUG);
makeEncryptedHttpResponse("", "400 Bad Request", "close");
makePayloadHttpResponse("", "400 Bad Request", "close");
return;
}
switch (inner->httpType()) {
case HTTP::HttpType::connect: {
if (config_->general().tunnelEnable) {
if (!client_->doConnect(inner->dstIP(), inner->dstPort())) {
if (!client_->doConnect(inner->dstIp(), inner->dstPort())) {
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [ERROR] [Resolving Host] [SRC " +
clientConnStr_ + "] [DST " +
inner->dstIP() + ":" + std::to_string(inner->dstPort()) + "]",
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
makeEncryptedHttpResponse(
makePayloadHttpResponse(
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
"502 Bad Gateway",
"close");
@@ -321,12 +290,12 @@ void ServerHandler::handle() {
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [TUNNEL] [SRC " +
"] [CONNECT] [SRC " +
clientConnStr_ + "] [DST " +
inner->dstIP() + ":" + std::to_string(inner->dstPort()) + "]",
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
makeEncryptedHttpResponse(
makePayloadHttpResponse(
"HTTP/1.1 200 Connection Established\r\n\r\n",
"200 OK",
"keep-alive");
@@ -344,15 +313,15 @@ void ServerHandler::handle() {
targetClient->uuid_ = uuid_;
if (!targetClient->doConnect(inner->dstIP(), inner->dstPort())) {
if (!targetClient->doConnect(inner->dstIp(), inner->dstPort())) {
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [ERROR] [Resolving Host] [SRC " +
clientConnStr_ + "] [DST " +
inner->dstIP() + ":" + std::to_string(inner->dstPort()) + "]",
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
makeEncryptedHttpResponse(
makePayloadHttpResponse(
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
"502 Bad Gateway",
"close");
@@ -365,8 +334,8 @@ void ServerHandler::handle() {
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [SRC " +
clientConnStr_ + "] [DST " +
inner->dstIP() + ":" + std::to_string(inner->dstPort()) + "]",
clientConnStr_ + "] [ORIGIN " +
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
if (!pendingTunnelData.empty()) {
@@ -380,7 +349,7 @@ void ServerHandler::handle() {
sessions_[session.empty() ? to_string(uuid_) : session] = targetClient;
}
makeEncryptedHttpResponse(
makePayloadHttpResponse(
"HTTP/1.1 200 Connection Established\r\n\r\n",
"200 OK",
"keep-alive");
@@ -395,9 +364,9 @@ void ServerHandler::handle() {
copyStringToStreambuf(innerRequest, readBuffer_);
if (!client_->socket().is_open()) {
if (!client_->doConnect(inner->dstIP(), inner->dstPort())) {
if (!client_->doConnect(inner->dstIp(), inner->dstPort())) {
client_->socket().close();
makeEncryptedHttpResponse("", "502 Bad Gateway", "close");
makePayloadHttpResponse("", "502 Bad Gateway", "close");
return;
}
}
@@ -407,11 +376,11 @@ void ServerHandler::handle() {
if (client_->readBuffer().size() == 0) {
client_->socket().close();
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
makeEncryptedHttpResponse(
makePayloadHttpResponse(
streambufToString(client_->readBuffer()),
"200 OK",
(config_->general().connectionReuse ? "keep-alive" : "close"));
+12 -13
View File
@@ -19,8 +19,8 @@ public:
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid) {
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log, client, clientConnStr, uuid));
}
@@ -29,8 +29,7 @@ public:
void handle();
inline const HTTP::pointer &request() & { return request_; }
inline const HTTP::pointer &&request() && { return std::move(request_); }
inline const HTTP::pointer &request() const { return request_; }
bool end_;
bool connect_;
@@ -47,13 +46,13 @@ private:
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid);
void makeEncryptedHttpResponse(const std::string &plainBody,
const std::string &status = "200 OK",
const std::string &connection = "close");
void makePayloadHttpResponse(const std::string &plainBody,
const std::string &status = "200 OK",
const std::string &connection = "close");
void makePlainHttpResponse(const std::string &body,
const std::string &status = "200 OK",
@@ -62,13 +61,13 @@ private:
static std::mutex sessionsMutex_;
static std::unordered_map<std::string, TCPClient::pointer> sessions_;
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
const TCPClient::pointer &client_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
TCPClient::pointer client_;
boost::asio::streambuf &readBuffer_;
boost::asio::streambuf &writeBuffer_;
HTTP::pointer request_;
const std::string &clientConnStr_;
std::string clientConnStr_;
boost::uuids::uuid uuid_;
std::mutex mutex_;
};
+262 -152
View File
@@ -4,9 +4,93 @@
#include <algorithm>
#include <cctype>
#include <chrono>
#include <memory>
#include <sstream>
#include <utility>
#include <vector>
#include "http_utils.hpp"
#ifndef _WIN32
#include <poll.h>
#endif
namespace {
template<typename Socket>
void connectWithTimeout(Socket &socket,
const boost::asio::ip::tcp::resolver::results_type &endpoints,
unsigned short timeoutSeconds,
boost::system::error_code &ec) {
ec = boost::asio::error::host_not_found;
for (const auto &entry: endpoints) {
boost::system::error_code ignored;
socket.close(ignored);
socket.open(entry.endpoint().protocol(), ec);
if (ec) continue;
if (timeoutSeconds == 0) {
socket.connect(entry.endpoint(), ec);
if (!ec) return;
continue;
}
socket.native_non_blocking(true, ec);
if (ec) continue;
const auto endpoint = entry.endpoint();
const bool started =
::connect(socket.native_handle(), endpoint.data(),
static_cast<int>(endpoint.size())) == 0;
#ifdef _WIN32
const int connectErr = started ? 0 : WSAGetLastError();
const bool pending = connectErr == WSAEWOULDBLOCK;
#else
const int connectErr = started ? 0 : errno;
const bool pending = connectErr == EINPROGRESS;
#endif
ec = boost::system::error_code(connectErr, boost::system::system_category());
if (pending) {
#ifdef _WIN32
WSAPOLLFD pfd{socket.native_handle(), POLLWRNORM, 0};
const int ready = WSAPoll(&pfd, 1, timeoutSeconds * 1000);
#else
pollfd pfd{socket.native_handle(), POLLOUT, 0};
const int ready = ::poll(&pfd, 1, timeoutSeconds * 1000);
#endif
if (ready == 0) {
ec = boost::asio::error::timed_out;
} else if (ready < 0) {
#ifdef _WIN32
ec = boost::system::error_code(WSAGetLastError(), boost::system::system_category());
#else
ec = boost::system::error_code(errno, boost::system::system_category());
#endif
} else {
boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_ERROR> soError;
socket.get_option(soError, ec);
if (!ec && soError.value() != 0) {
ec = boost::system::error_code(soError.value(), boost::system::system_category());
}
}
}
if (!ec) {
socket.native_non_blocking(false, ec);
if (!ec) return;
}
}
boost::system::error_code ignored;
socket.close(ignored);
}
}
TCPClient::TCPClient(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log)
@@ -90,8 +174,7 @@ bool TCPClient::enableTlsClient() {
}
}
bool TCPClient::doConnect(const std::string &dstIP, const unsigned short &dstPort) {
bool TCPClient::doConnect(const std::string &dstIp, unsigned short dstPort) {
try {
if (tlsEnabled_ && sslSocket_ && sslSocket_->lowest_layer().is_open()) {
return true;
@@ -101,15 +184,16 @@ bool TCPClient::doConnect(const std::string &dstIP, const unsigned short &dstPor
return true;
}
log_->write("[" + to_string(uuid_) + "] [TCPClient doConnect] [DST " + dstIP +
":" + std::to_string(dstPort) + "]",
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] [DST " + dstIp + ":" +
std::to_string(dstPort) + "]",
Log::Level::DEBUG);
boost::system::error_code error_code;
auto endpoint = resolver_.resolve(
dstIP.c_str(),
std::to_string(dstPort).c_str(),
auto endpoints = resolver_.resolve(
dstIp,
std::to_string(dstPort),
error_code);
if (error_code) {
@@ -120,104 +204,151 @@ bool TCPClient::doConnect(const std::string &dstIP, const unsigned short &dstPor
return false;
}
resetTimeout();
if (tlsEnabled_) {
if (!sslSocket_ || closed_ || !sslSocket_->lowest_layer().is_open()) {
sslSocket_ = std::make_unique<ssl_stream>(io_context_, sslContext_);
closed_ = false;
}
sslSocket_ = std::make_unique<ssl_stream>(io_context_, sslContext_);
closed_ = false;
boost::asio::connect(sslSocket_->lowest_layer(), endpoint, error_code);
connectWithTimeout(sslSocket_->lowest_layer(), endpoints,
config_->general().timeout, error_code);
} else {
if (!socket_.is_open()) {
socket_ = tcp::socket(io_context_);
closed_ = false;
}
socket_ = tcp::socket(io_context_);
closed_ = false;
boost::asio::connect(socket_, endpoint, error_code);
connectWithTimeout(socket_, endpoints,
config_->general().timeout, error_code);
}
cancelTimeout();
if (error_code) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] connect error: " +
error_code.message(),
Log::Level::ERROR);
socketShutdown();
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] connected",
Log::Level::DEBUG);
return true;
} catch (std::exception &error) {
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] " +
error.what(),
"] [TCPClient doConnect] exception: " + ex.what(),
Log::Level::ERROR);
socketShutdown();
return false;
}
}
bool TCPClient::doHandshakeClient() {
try {
if (!tlsEnabled_ || !sslSocket_) return true;
if (!tlsEnabled_ || !sslSocket_) {
return true;
}
if (!sslSocket_->lowest_layer().is_open()) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doHandshakeClient] socket is not open",
Log::Level::ERROR);
socketShutdown();
return false;
}
std::string sniHost = config_->randomFakeUrl();
if (!sniHost.empty()) {
auto pos = sniHost.find("://");
if (pos != std::string::npos) sniHost = sniHost.substr(pos + 3);
pos = sniHost.find('/');
if (pos != std::string::npos) sniHost = sniHost.substr(0, pos);
pos = sniHost.find(':');
if (pos != std::string::npos) sniHost = sniHost.substr(0, pos);
if (!sniHost.empty()) {
if (!SSL_set_tlsext_host_name(sslSocket_->native_handle(), sniHost.c_str())) {
log_->write("[" + to_string(uuid_) +
"] [TLS] Failed to set SNI: " + sniHost,
Log::Level::ERROR);
return false;
}
static const unsigned char alpn[] = {
0x08, 'h', 't', 't', 'p', '/', '1', '.', '1'};
if (SSL_set_alpn_protos(sslSocket_->native_handle(),
alpn, sizeof(alpn)) != 0) {
log_->write("[" + to_string(uuid_) +
"] [TLS] Failed to set ALPN http/1.1",
Log::Level::ERROR);
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TLS] Using SNI/ALPN host: " + sniHost +
" [ALPN http/1.1]",
Log::Level::DEBUG);
}
auto pos = sniHost.find("://");
if (pos != std::string::npos) {
sniHost = sniHost.substr(pos + 3);
}
pos = sniHost.find('/');
if (pos != std::string::npos) {
sniHost = sniHost.substr(0, pos);
}
pos = sniHost.find(':');
if (pos != std::string::npos) {
sniHost = sniHost.substr(0, pos);
}
if (!sniHost.empty()) {
if (!SSL_set_tlsext_host_name(
sslSocket_->native_handle(),
sniHost.c_str())) {
log_->write("[" + to_string(uuid_) +
"] [TLS] Failed to set SNI: " + sniHost,
Log::Level::ERROR);
socketShutdown();
return false;
}
static const unsigned char alpn[] = {
0x08, 'h', 't', 't', 'p', '/', '1', '.', '1'};
if (SSL_set_alpn_protos(
sslSocket_->native_handle(),
alpn,
sizeof(alpn)) != 0) {
log_->write("[" + to_string(uuid_) +
"] [TLS] Failed to set ALPN http/1.1",
Log::Level::ERROR);
socketShutdown();
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TLS] Starting client handshake with SNI: " +
sniHost,
Log::Level::DEBUG);
}
boost::system::error_code error;
resetTimeout();
sslSocket_->handshake(boost::asio::ssl::stream_base::client);
sslSocket_->handshake(
boost::asio::ssl::stream_base::client,
error);
cancelTimeout();
if (error) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doHandshakeClient] handshake error: " +
error.message(),
Log::Level::ERROR);
socketShutdown();
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TLS] Client handshake completed",
Log::Level::DEBUG);
const unsigned char *selected = nullptr;
unsigned int selectedLen = 0;
SSL_get0_alpn_selected(sslSocket_->native_handle(), &selected, &selectedLen);
SSL_get0_alpn_selected(
sslSocket_->native_handle(),
&selected,
&selectedLen);
if (selected != nullptr && selectedLen > 0) {
std::string negotiated(reinterpret_cast<const char *>(selected), selectedLen);
std::string negotiated(
reinterpret_cast<const char *>(selected),
selectedLen);
log_->write("[" + to_string(uuid_) +
"] [TLS] Negotiated ALPN: " + negotiated,
Log::Level::DEBUG);
if (negotiated != "http/1.1") {
log_->write("[" + to_string(uuid_) +
"] [TLS] Unsupported negotiated ALPN: " + negotiated,
Log::Level::ERROR);
return false;
}
} else {
log_->write("[" + to_string(uuid_) +
"] [TLS] No ALPN negotiated",
@@ -226,11 +357,15 @@ bool TCPClient::doHandshakeClient() {
return true;
} catch (std::exception &error) {
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doHandshakeClient] " + error.what(),
"] [TCPClient doHandshakeClient] exception: " +
ex.what(),
Log::Level::ERROR);
socketShutdown();
return false;
}
}
@@ -240,9 +375,9 @@ void TCPClient::writeBuffer(boost::asio::streambuf &buffer) {
}
void TCPClient::doWrite(boost::asio::streambuf &buffer) {
bool TCPClient::doWrite(boost::asio::streambuf &buffer) {
try {
writeBuffer_.consume(writeBuffer_.size());
moveStreambuf(buffer, writeBuffer_);
if (!isOpen()) {
@@ -250,31 +385,33 @@ void TCPClient::doWrite(boost::asio::streambuf &buffer) {
"] [TCPClient doWrite] socket is not open",
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
if (writeBuffer_.size() == 0) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] empty write buffer",
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
boost::system::error_code error;
resetTimeout();
if (tlsEnabled_ && sslSocket_) {
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [SSL] [DST " +
sslSocket_->lowest_layer().remote_endpoint().address().to_string() +
":" +
std::to_string(sslSocket_->lowest_layer().remote_endpoint().port()) +
"] [Bytes " + std::to_string(writeBuffer_.size()) + "] ",
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] [SSL] [Bytes " +
std::to_string(writeBuffer_.size()) + "]",
Log::Level::DEBUG);
boost::asio::write(*sslSocket_, writeBuffer_, error);
} else {
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [TCP] [DST " +
socket_.remote_endpoint().address().to_string() + ":" +
std::to_string(socket_.remote_endpoint().port()) +
"] [Bytes " + std::to_string(writeBuffer_.size()) + "] ",
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] [TCP] [Bytes " +
std::to_string(writeBuffer_.size()) + "]",
Log::Level::DEBUG);
boost::asio::write(socket_, writeBuffer_, error);
}
@@ -285,18 +422,24 @@ void TCPClient::doWrite(boost::asio::streambuf &buffer) {
"] [TCPClient doWrite] [error] " + error.message(),
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
} catch (std::exception &error) {
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [catch] " +
error.what(),
return true;
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] [catch] " + ex.what(),
Log::Level::DEBUG);
socketShutdown();
return false;
}
}
void TCPClient::doReadAgent() {
bool TCPClient::doReadAgent() {
boost::system::error_code error;
try {
@@ -304,16 +447,18 @@ void TCPClient::doReadAgent() {
std::lock_guard<std::mutex> lock(mutex_);
readBuffer_.consume(readBuffer_.size());
buffer_.consume(buffer_.size());
if (!isOpen()) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] Socket is not OPEN",
Log::Level::DEBUG);
return;
return false;
}
}
resetTimeout();
bool ok = false;
if (tlsEnabled_) {
if (!sslSocket_) {
@@ -322,14 +467,16 @@ void TCPClient::doReadAgent() {
"] [TCPClient doReadAgent] SSL socket is null",
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
ok = HttpUtils::readHttpMessage(*sslSocket_, readBuffer_, error);
} else {
ok = HttpUtils::readHttpMessage(socket_, readBuffer_, error);
}
cancelTimeout();
if (!ok) {
if (error == boost::asio::error::operation_aborted) {
log_->write("[" + to_string(uuid_) +
@@ -341,29 +488,34 @@ void TCPClient::doReadAgent() {
Log::Level::TRACE);
} else {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [error] " +
error.message(),
"] [TCPClient doReadAgent] [error] " + error.message(),
Log::Level::ERROR);
}
socketShutdown();
return;
return false;
}
if (readBuffer_.size() > 0) {
copyStreambuf(readBuffer_, buffer_);
return;
if (readBuffer_.size() == 0) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] empty read buffer",
Log::Level::DEBUG);
socketShutdown();
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] empty read buffer",
Log::Level::DEBUG);
socketShutdown();
copyStreambuf(readBuffer_, buffer_);
return true;
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [catch read] " +
ex.what(),
"] [TCPClient doReadAgent] [catch read] " + ex.what(),
Log::Level::DEBUG);
socketShutdown();
return false;
}
}
@@ -453,13 +605,14 @@ void TCPClient::cancelTimeout() {
}
void TCPClient::onTimeout(const boost::system::error_code &error) {
if (error || error == boost::asio::error::operation_aborted) return;
if (error == boost::asio::error::operation_aborted) {
return;
}
log_->write("[" + to_string(uuid_) +
"] [TCPClient onTimeout] [expiration] " +
std::to_string(+config_->general().timeout) +
" seconds has passed, and the timeout has expired",
"] [TCPClient onTimeout] timeout expired",
Log::Level::TRACE);
socketShutdown();
}
@@ -507,66 +660,23 @@ void TCPClient::socketShutdown() {
}
std::string TCPClient::HttpUtils::toLowerCopy(std::string s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return s;
return http_utils::toLowerCopy(std::move(s));
}
std::string TCPClient::HttpUtils::extractHeaders(const std::string &msg) {
auto pos = msg.find("\r\n\r\n");
if (pos == std::string::npos) return {};
return msg.substr(0, pos + 4);
return http_utils::extractHeaders(msg);
}
std::string TCPClient::HttpUtils::extractBody(const std::string &msg) {
auto pos = msg.find("\r\n\r\n");
if (pos == std::string::npos) return {};
return msg.substr(pos + 4);
return http_utils::extractBody(msg);
}
bool TCPClient::HttpUtils::parseContentLength(const std::string &headers, std::size_t &value) {
std::istringstream iss(headers);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
auto lower = toLowerCopy(line);
if (lower.rfind("content-length:", 0) == 0) {
auto raw = line.substr(std::string("Content-Length:").size());
raw.erase(0, raw.find_first_not_of(" \t"));
try {
value = static_cast<std::size_t>(std::stoull(raw));
return true;
} catch (...) {
return false;
}
}
}
return false;
return http_utils::parseContentLength(headers, value);
}
bool TCPClient::HttpUtils::isChunked(const std::string &headers) {
std::istringstream iss(headers);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
auto lower = toLowerCopy(line);
if (lower.rfind("transfer-encoding:", 0) == 0 &&
lower.find("chunked") != std::string::npos) {
return true;
}
}
return false;
return http_utils::isChunked(headers);
}
bool TCPClient::HttpUtils::readHttpMessage(
+10 -11
View File
@@ -2,8 +2,6 @@
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/uuid/uuid.hpp>
#include <functional>
#include <memory>
@@ -15,9 +13,9 @@
#include "http.hpp"
#include "log.hpp"
class TCPClient : public boost::enable_shared_from_this<TCPClient> {
class TCPClient : public std::enable_shared_from_this<TCPClient> {
public:
using pointer = boost::shared_ptr<TCPClient>;
using pointer = std::shared_ptr<TCPClient>;
using tcp = boost::asio::ip::tcp;
using ssl_stream = boost::asio::ssl::stream<tcp::socket>;
@@ -35,22 +33,23 @@ public:
bool enableTlsClient();
bool doHandshakeClient();
bool doConnect(const std::string &dstIP, const unsigned short &dstPort);
bool doConnect(const std::string &dstIp, unsigned short dstPort);
void writeBuffer(boost::asio::streambuf &buffer);
inline boost::asio::streambuf &writeBuffer() & { return writeBuffer_; }
inline boost::asio::streambuf &&writeBuffer() && { return std::move(writeBuffer_); }
inline boost::asio::streambuf &readBuffer() & { return readBuffer_; }
inline boost::asio::streambuf &&readBuffer() && { return std::move(readBuffer_); }
void doWrite(boost::asio::streambuf &buffer);
void doReadAgent();
bool doReadAgent();
bool doWrite(boost::asio::streambuf &buffer);
void doReadServer();
void socketShutdown();
boost::uuids::uuid uuid() const { return uuid_; }
bool ended() const { return end_; }
boost::uuids::uuid uuid_;
bool end_;
@@ -87,8 +86,8 @@ private:
void cancelTimeout();
void onTimeout(const boost::system::error_code &error);
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context &io_context_;
tcp::socket socket_;
+245 -73
View File
@@ -5,8 +5,11 @@
#include <algorithm>
#include <cctype>
#include <sstream>
#include <utility>
#include <vector>
#include "http_utils.hpp"
TCPConnection::TCPConnection(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
@@ -26,6 +29,11 @@ TCPConnection::TCPConnection(boost::asio::io_context &io_context,
connect_ = false;
tunnelClosed_ = false;
pollInProgress_ = false;
pollDelayMs_ = 0;
}
namespace {
constexpr unsigned int MaxPollDelayMs = 50;
}
boost::asio::ip::tcp::socket &TCPConnection::socket() { return socket_; }
@@ -102,6 +110,7 @@ bool TCPConnection::doHandshakeServer() {
cancelTimeout();
log_->write("[" + to_string(uuid_) + "] [TCPConnection doHandshakeServer] " + error.what(),
Log::Level::ERROR);
socketShutdown();
return false;
}
}
@@ -122,20 +131,30 @@ void TCPConnection::doReadAgent() {
try {
readBuffer_.consume(readBuffer_.size());
writeBuffer_.consume(writeBuffer_.size());
resetTimeout();
boost::asio::async_read(socket_,
readBuffer_,
boost::asio::transfer_at_least(1),
boost::asio::bind_executor(
strand_,
boost::bind(&TCPConnection::handleReadAgent,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)));
socket_.async_read_some(
readBuffer_.prepare(BufferSize),
boost::asio::bind_executor(
strand_,
[self = shared_from_this()](
const boost::system::error_code &ec,
std::size_t bytes) {
if (!ec) {
self->readBuffer_.commit(bytes);
}
self->handleReadAgent(ec, bytes);
}));
} catch (std::exception &error) {
log_->write("[" + to_string(uuid_) + "] [TCPConnection doReadAgent] [catch] " + error.what(),
Log::Level::ERROR);
log_->write(
"[" + to_string(uuid_) +
"] [TCPConnection doReadAgent] [catch] " +
error.what(),
Log::Level::ERROR);
socketShutdown();
}
}
@@ -176,7 +195,15 @@ void TCPConnection::handleReadAgent(const boost::system::error_code &error, size
boost::system::error_code errorIn;
if (config_->general().protocol == "socks5") {
if (!handleSocks5Handshake()) {
socketShutdown();
return;
}
}
std::string current = streambufToString(readBuffer_);
if (current.find("\r\n\r\n") == std::string::npos) {
boost::asio::read_until(socket_, readBuffer_, "\r\n\r\n", errorIn);
}
@@ -233,6 +260,18 @@ void TCPConnection::handleReadAgent(const boost::system::error_code &error, size
end_ = agentHandler_->end_;
connect_ = agentHandler_->connect_;
if (config_->general().protocol == "socks5" && connect_) {
writeBuffer_.consume(writeBuffer_.size());
const unsigned char ok[10] = {
0x05, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00};
std::ostream os(&writeBuffer_);
os.write(reinterpret_cast<const char *>(ok), sizeof(ok));
}
if (writeBuffer_.size() == 0) {
socketShutdown();
return;
@@ -264,12 +303,15 @@ void TCPConnection::handleReadAgent(const boost::system::error_code &error, size
if (!self->config_->general().connectionReuse) {
self->client_->socketShutdown();
}
self->pollDelayMs_ = self->config_->general().pullTimeout;
self->startTunnelReadFromClient();
self->startTunnelPollServer();
}
return;
}
self->doReadAgent();
}));
} catch (std::exception &error) {
@@ -403,6 +445,8 @@ std::string TCPConnection::makeRelayHostHeader() const {
std::string TCPConnection::postTunnelAction(const std::string &action,
const std::string &rawBody) {
std::lock_guard<std::mutex> relayLock(relayMutex_);
client_->uuid_ = uuid_;
auto sendOnce = [&]() -> std::string {
@@ -423,11 +467,13 @@ std::string TCPConnection::postTunnelAction(const std::string &action,
}
}
BoolStr enc = aes256Encrypt(
hexArrToStr(
reinterpret_cast<const unsigned char *>(rawBody.data()),
rawBody.size()),
config_->general().token);
const std::string payload = makeEnvelope(
action, to_string(uuid_),
hexArrToStr(reinterpret_cast<const unsigned char *>(rawBody.data()),
rawBody.size()));
BoolStr enc = config_->general().aesEnable
? aes256Encrypt(payload, config_->general().token)
: BoolStr{true, payload};
if (!enc.ok) return "";
@@ -442,9 +488,7 @@ std::string TCPConnection::postTunnelAction(const std::string &action,
<< "Host: " << makeRelayHostHeader() << "\r\n"
<< "User-Agent: " << config_->agent().userAgent << "\r\n"
<< "Accept: */*\r\n"
<< "Content-Type: application/text\r\n"
<< "X-Nipo-Session: " << to_string(uuid_) << "\r\n"
<< "X-Nipo-Action: " << action << "\r\n"
<< "Content-Type: text/plain; charset=utf-8\r\n"
<< "Content-Length: " << encodedBody.size() << "\r\n"
<< "Connection: " << (keepAlive ? "keep-alive" : "close") << "\r\n"
<< "\r\n"
@@ -453,11 +497,32 @@ std::string TCPConnection::postTunnelAction(const std::string &action,
boost::asio::streambuf out;
copyStringToStreambuf(req.str(), out);
client_->doWrite(out);
client_->doReadAgent();
if (!client_->doWrite(out)) {
log_->write("[" + to_string(uuid_) +
"] [TCPConnection postTunnelAction] doWrite failed",
Log::Level::DEBUG);
client_->socketShutdown();
return "";
}
if (!client_->doReadAgent()) {
log_->write("[" + to_string(uuid_) +
"] [TCPConnection postTunnelAction] doReadAgent failed",
Log::Level::DEBUG);
client_->socketShutdown();
return "";
}
const std::string response = streambufToString(client_->readBuffer());
if (response.empty()) {
log_->write("[" + to_string(uuid_) +
"] [TCPConnection postTunnelAction] empty response",
Log::Level::DEBUG);
client_->socketShutdown();
return "";
}
if (!keepAlive) {
client_->socketShutdown();
}
@@ -477,15 +542,145 @@ std::string TCPConnection::postTunnelAction(const std::string &action,
const auto pos = response.find("\r\n\r\n");
if (pos == std::string::npos) return "";
const std::string encryptedBody = response.substr(pos + 4);
if (encryptedBody.empty()) return "";
const std::string responseBody = response.substr(pos + 4);
if (responseBody.empty()) return "";
BoolStr dec = aes256Decrypt(encryptedBody, config_->general().token);
BoolStr dec = config_->general().aesEnable
? aes256Decrypt(responseBody, config_->general().token)
: BoolStr{true, responseBody};
if (!dec.ok) return "";
return dec.message;
}
bool TCPConnection::readExactFromClient(void *data, std::size_t size) {
auto *out = static_cast<char *>(data);
std::size_t copied = 0;
while (copied < size && readBuffer_.size() > 0) {
std::size_t n = std::min(size - copied, readBuffer_.size());
auto buffers = readBuffer_.data();
std::size_t copiedNow = boost::asio::buffer_copy(
boost::asio::buffer(out + copied, n),
buffers);
readBuffer_.consume(copiedNow);
copied += copiedNow;
}
if (copied == size) {
return true;
}
boost::system::error_code ec;
boost::asio::read(
socket_,
boost::asio::buffer(out + copied, size - copied),
ec);
return !ec;
}
bool TCPConnection::handleSocks5Handshake() {
log_->write(
"[" + to_string(uuid_) + "] [TCPConnection handleSocks5Handshake] handshake start",
Log::Level::DEBUG);
unsigned char header[2];
if (!readExactFromClient(header, 2)) {
log_->write(
"[" + to_string(uuid_) + "] [TCPConnection handleSocks5Handshake] [SOCKS5] version=" +
std::to_string(header[0]),
Log::Level::DEBUG);
return false;
}
if (header[0] != 0x05) {
log_->write("[" + to_string(uuid_) + "] [SOCKS5] invalid version", Log::Level::DEBUG);
return false;
}
std::vector<unsigned char> methods(header[1]);
if (!readExactFromClient(methods.data(), methods.size())) return false;
const unsigned char authReply[2] = {0x05, 0x00};
boost::asio::write(socket_, boost::asio::buffer(authReply, 2));
log_->write(
"[" + to_string(uuid_) + "] [TCPConnection handleSocks5Handshake] auth reply sent" +
std::to_string(header[0]),
Log::Level::DEBUG);
unsigned char req[4];
if (!readExactFromClient(req, 4)) return false;
if (req[0] != 0x05 || req[1] != 0x01) {
const unsigned char fail[10] = {0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0};
boost::asio::write(socket_, boost::asio::buffer(fail, 10));
return false;
}
std::string host;
if (req[3] == 0x01) {
unsigned char ip[4];
if (!readExactFromClient(ip, 4)) return false;
host =
std::to_string(ip[0]) + "." +
std::to_string(ip[1]) + "." +
std::to_string(ip[2]) + "." +
std::to_string(ip[3]);
} else if (req[3] == 0x03) {
unsigned char len;
if (!readExactFromClient(&len, 1)) return false;
std::vector<char> domain(len);
if (!readExactFromClient(domain.data(), domain.size())) return false;
host.assign(domain.begin(), domain.end());
} else if (req[3] == 0x04) {
unsigned char ip[16];
if (!readExactFromClient(ip, 16)) return false;
boost::asio::ip::address_v6::bytes_type bytes;
std::copy(ip, ip + 16, bytes.begin());
host = boost::asio::ip::address_v6(bytes).to_string();
} else {
return false;
}
unsigned char portBytes[2];
if (!readExactFromClient(portBytes, 2)) return false;
unsigned short port =
static_cast<unsigned short>((portBytes[0] << 8) | portBytes[1]);
std::string target;
if (host.find(':') != std::string::npos) {
target = "[" + host + "]:" + std::to_string(port);
} else {
target = host + ":" + std::to_string(port);
}
std::string connectRequest =
"CONNECT " + target +
" HTTP/1.1\r\n"
"Host: " +
target +
"\r\n"
"\r\n";
copyStringToStreambuf(connectRequest, readBuffer_);
return true;
}
void TCPConnection::startTunnelReadFromClient() {
if (tunnelClosed_ || !socket_.is_open()) return;
@@ -503,6 +698,10 @@ void TCPConnection::startTunnelReadFromClient() {
std::string raw(self->downstreamBuf_.data(), bytes);
self->postTunnelAction("send", raw);
self->pollDelayMs_ = self->config_->general().pullTimeout;
if (self->pollInProgress_) self->pollTimer_.cancel();
self->startTunnelReadFromClient();
}));
}
@@ -512,17 +711,30 @@ void TCPConnection::startTunnelPollServer() {
pollInProgress_ = true;
pollTimer_.expires_after(std::chrono::milliseconds(config_->general().pullTimeout));
pollTimer_.expires_after(std::chrono::milliseconds(pollDelayMs_));
pollTimer_.async_wait(
boost::asio::bind_executor(
strand_,
[self = shared_from_this()](const boost::system::error_code &ec) {
self->pollInProgress_ = false;
if (ec || self->tunnelClosed_ || !self->socket_.is_open()) return;
if (self->tunnelClosed_ || !self->socket_.is_open()) return;
if (ec == boost::asio::error::operation_aborted) {
self->startTunnelPollServer();
return;
}
if (ec) return;
std::string data = self->postTunnelAction("recv", "");
const unsigned int baseDelay = self->config_->general().pullTimeout;
self->pollDelayMs_ =
data.empty()
? std::min(std::max(self->pollDelayMs_ * 2, 1u), std::max(MaxPollDelayMs, baseDelay))
: baseDelay;
if (!data.empty()) {
boost::asio::async_write(
self->socket_,
@@ -682,7 +894,7 @@ void TCPConnection::asyncWriteToAgentConnection(
}
void TCPConnection::asyncReadFromAgentConnection(
std::array<char, 8192> &buffer,
std::array<char, BufferSize> &buffer,
std::function<void(const boost::system::error_code &, std::size_t)> done) {
if (config_->general().tlsEnable && tlsSocket_) {
tlsSocket_->async_read_some(
@@ -723,7 +935,7 @@ void TCPConnection::asyncWriteToAgentServerConnection(
}
void TCPConnection::asyncReadFromAgentServerConnection(
std::array<char, 8192> &buffer,
std::array<char, BufferSize> &buffer,
std::function<void(const boost::system::error_code &, std::size_t)> done) {
if (client_->tlsEnabled()) {
client_->sslSocket().async_read_some(
@@ -866,63 +1078,23 @@ void TCPConnection::relayTargetToAgent() {
}
std::string TCPConnection::HttpUtils::toLowerCopy(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return s;
return http_utils::toLowerCopy(std::move(s));
}
std::string TCPConnection::HttpUtils::extractHeaders(const std::string &msg) {
auto pos = msg.find("\r\n\r\n");
if (pos == std::string::npos) return {};
return msg.substr(0, pos + 4);
return http_utils::extractHeaders(msg);
}
std::string TCPConnection::HttpUtils::extractBody(const std::string &msg) {
auto pos = msg.find("\r\n\r\n");
if (pos == std::string::npos) return {};
return msg.substr(pos + 4);
return http_utils::extractBody(msg);
}
bool TCPConnection::HttpUtils::parseContentLength(const std::string &headers, std::size_t &value) {
std::istringstream iss(headers);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
auto lower = toLowerCopy(line);
if (lower.rfind("content-length:", 0) == 0) {
auto raw = line.substr(std::string("Content-Length:").size());
raw.erase(0, raw.find_first_not_of(" \t"));
try {
value = static_cast<std::size_t>(std::stoull(raw));
return true;
} catch (...) {
return false;
}
}
}
return false;
return http_utils::parseContentLength(headers, value);
}
bool TCPConnection::HttpUtils::isChunked(const std::string &headers) {
std::istringstream iss(headers);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
auto lower = toLowerCopy(line);
if (lower.rfind("transfer-encoding:", 0) == 0 &&
lower.find("chunked") != std::string::npos) {
return true;
}
}
return false;
return http_utils::isChunked(headers);
}
bool TCPConnection::HttpUtils::readRemainingHttpBody(
+17 -13
View File
@@ -5,8 +5,6 @@
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
@@ -20,9 +18,9 @@
#include "general.hpp"
#include "serverhandler.hpp"
class TCPConnection : public boost::enable_shared_from_this<TCPConnection> {
class TCPConnection : public std::enable_shared_from_this<TCPConnection> {
public:
using pointer = boost::shared_ptr<TCPConnection>;
using pointer = std::shared_ptr<TCPConnection>;
using ssl_stream = boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
static pointer create(boost::asio::io_context &io_context,
@@ -33,7 +31,7 @@ public:
}
boost::asio::ip::tcp::socket &socket();
inline TCPClient::pointer client() { return client_; }
inline TCPClient::pointer client() const { return client_; }
ssl_stream &tlsSocket();
bool initTlsServerContext();
@@ -44,8 +42,8 @@ public:
}
inline const boost::asio::streambuf &readBuffer() & { return readBuffer_; }
inline const boost::asio::streambuf &&readBuffer() && { return std::move(readBuffer_); }
inline boost::uuids::uuid uuid() { return uuid_; }
inline boost::uuids::uuid uuid() const { return uuid_; }
void startAgent();
void startServer();
@@ -65,13 +63,15 @@ public:
void relayAgentToTarget();
void relayTargetToAgent();
std::mutex relayMutex_;
inline void asyncWriteToAgentConnection(
const char *data,
std::size_t bytes,
std::function<void(const boost::system::error_code &)> done);
inline void asyncReadFromAgentConnection(
std::array<char, 8192> &buffer,
std::array<char, BufferSize> &buffer,
std::function<void(const boost::system::error_code &, std::size_t)> done);
inline void asyncWriteToAgentServerConnection(
@@ -80,7 +80,7 @@ public:
std::function<void(const boost::system::error_code &)> done);
inline void asyncReadFromAgentServerConnection(
std::array<char, 8192> &buffer,
std::array<char, BufferSize> &buffer,
std::function<void(const boost::system::error_code &, std::size_t)> done);
private:
@@ -111,6 +111,9 @@ private:
const std::shared_ptr<Log> &log,
TCPClient::pointer client);
bool handleSocks5Handshake();
bool readExactFromClient(void *data, std::size_t size);
void resetTimeout();
void cancelTimeout();
void onTimeout(const boost::system::error_code &error);
@@ -125,8 +128,8 @@ private:
boost::asio::ssl::context sslContext_;
std::unique_ptr<ssl_stream> tlsSocket_;
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context &io_context_;
TCPClient::pointer client_;
@@ -145,8 +148,9 @@ private:
bool tunnelMode_;
bool tunnelClosed_;
bool pollInProgress_;
unsigned int pollDelayMs_;
std::atomic_bool closed_{false};
std::array<char, 8192> downstreamBuf_;
std::array<char, 8192> upstreamBuf_;
std::array<char, BufferSize> downstreamBuf_;
std::array<char, BufferSize> upstreamBuf_;
};
+32 -34
View File
@@ -1,5 +1,8 @@
#include "tcpserver.hpp"
#include <atomic>
#include <chrono>
TCPServer::TCPServer(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log)
@@ -11,7 +14,6 @@ TCPServer::TCPServer(boost::asio::io_context &io_context,
boost::asio::ip::make_address(config->listenIp()),
config->listenPort())) {
acceptor_.set_option(boost::asio::socket_base::reuse_address(true));
startAccept();
}
@@ -26,47 +28,43 @@ void TCPServer::startAccept() {
});
}
void TCPServer::handleAccept(TCPConnection::pointer connection,
const boost::system::error_code &error) {
void TCPServer::handleAccept(
TCPConnection::pointer connection,
const boost::system::error_code &error) {
startAccept();
try {
if (!error) {
if (config_->runMode() == RunMode::server) {
if (config_->general().tlsEnable) {
if (!connection->initTlsServerContext()) {
log_->write("[TCPServer handleAccept] TLS server context init failed",
Log::Level::ERROR);
connection->socketShutdown();
startAccept();
return;
}
if (error) {
log_->write("[TCPServer handleAccept] Error: " + error.message(), Log::Level::ERROR);
return;
}
connection->tlsSocket().lowest_layer() =
std::move(connection->socket());
if (!connection->doHandshakeServer()) {
log_->write("[TCPServer handleAccept] TLS server handshake failed",
Log::Level::ERROR);
connection->socketShutdown();
startAccept();
return;
}
if (config_->runMode() == RunMode::server) {
if (config_->general().tlsEnable) {
if (!connection->initTlsServerContext()) {
log_->write("[TCPServer handleAccept] TLS server context init failed", Log::Level::ERROR);
connection->socketShutdown();
return;
}
connection->startServer();
} else {
connection->startAgent();
connection->tlsSocket().lowest_layer() = std::move(connection->socket());
if (!connection->doHandshakeServer()) {
log_->write("[TCPServer handleAccept] TLS server handshake failed", Log::Level::ERROR);
connection->socketShutdown();
return;
}
}
connection->startServer();
} else {
log_->write("[TCPServer handleAccept] Error: " + error.message(),
Log::Level::ERROR);
connection->startAgent();
}
} catch (const std::exception &ex) {
log_->write("[TCPServer handleAccept] Exception: " + std::string(ex.what()),
Log::Level::ERROR);
log_->write("[TCPServer handleAccept] Exception: " + std::string(ex.what()), Log::Level::ERROR);
connection->socketShutdown();
} catch (...) {
log_->write("[TCPServer handleAccept] Unknown exception",
Log::Level::ERROR);
log_->write("[TCPServer handleAccept] Unknown exception", Log::Level::ERROR);
connection->socketShutdown();
}
startAccept();
}
+5 -5
View File
@@ -1,13 +1,13 @@
#pragma once
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <memory>
#include "tcpconnection.hpp"
class TCPServer {
public:
using pointer = boost::shared_ptr<TCPServer>;
using pointer = std::shared_ptr<TCPServer>;
static pointer create(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
@@ -25,8 +25,8 @@ private:
void handleAccept(TCPConnection::pointer connection,
const boost::system::error_code &error);
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context &io_context_;
boost::asio::ip::tcp::acceptor acceptor_;
};
};
+40
View File
@@ -0,0 +1,40 @@
FROM ubuntu:24.04 AS builder
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
build-essential \
cmake \
git \
libboost-all-dev \
libssl-dev \
libyaml-cpp-dev \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /src
COPY . .
RUN cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \
&& cmake --build build --target nipovpn -j$(nproc)
FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
libboost-regex1.83.0 \
libssl3t64 \
libyaml-cpp0.8 \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN mkdir -p /etc/nipovpn /var/log/nipovpn
COPY --from=builder /src/build/core/nipovpn /usr/local/bin/nipovpn
COPY nipovpn/etc/nipovpn/config.yaml /etc/nipovpn/config.yaml
ENTRYPOINT ["nipovpn"]
CMD ["server", "/etc/nipovpn/config.yaml"]
+26
View File
@@ -0,0 +1,26 @@
services:
nipovpn:
container_name: nipovpn
build:
context: ..
dockerfile: docker/Dockerfile
image: nipovpn:latest
restart: unless-stopped
ports:
- "443:443"
- "8080:8080"
volumes:
- ../nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro
- nipovpn_logs:/var/log/nipovpn
command:
- ${NIPOVPN_MODE:-server}
- /etc/nipovpn/config.yaml
volumes:
nipovpn_logs:
Generated
+61
View File
@@ -0,0 +1,61 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1780243769,
"narHash": "sha256-x5UQuRsH3MqI0U9afaXSNqzTPSeZlRLvFAav2Ux1pNw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "331800de5053fcebacf6813adb5db9c9dca22a0c",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}
+72
View File
@@ -0,0 +1,72 @@
{
description = "NipoVPN - Powerful HTTP proxy";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
};
outputs = {
self,
nixpkgs,
flake-utils,
}:
flake-utils.lib.eachSystem ["x86_64-linux" "aarch64-linux"] (system: let
pkgs = nixpkgs.legacyPackages.${system};
nipovpn = pkgs.stdenv.mkDerivation {
pname = "nipovpn";
version = "1.1.57";
src = self;
nativeBuildInputs = with pkgs; [cmake];
buildInputs = with pkgs; [boost yaml-cpp openssl];
cmakeFlags = ["-DCMAKE_BUILD_TYPE=Release"];
installPhase = ''
runHook preInstall
mkdir -p $out/bin $out/etc/nipovpn
cp core/nipovpn $out/bin/nipovpn
cp -r $src/nipovpn/etc/nipovpn/. $out/etc/nipovpn/
runHook postInstall
'';
meta = with pkgs.lib; {
description = "Powerful HTTP proxy with traffic obfuscation";
homepage = "https://github.com/MortezaBashsiz/nipovpn";
license = licenses.gpl3Plus;
platforms = platforms.linux;
mainProgram = "nipovpn";
};
};
in {
packages.default = nipovpn;
packages.nipovpn = nipovpn;
devShells.default = pkgs.mkShell {
buildInputs = with pkgs; [
cmake
ninja
boost
yaml-cpp
openssl
clang-tools
gdb
valgrind
];
shellHook = ''
echo "NipoVPN dev environment ready"
echo ""
echo "You can build using either Make or Ninja:"
echo " Standard (Make):"
echo " cmake -B build -DCMAKE_BUILD_TYPE=Debug"
echo " cmake --build build -j\$(nproc)"
echo ""
echo " Fast (Ninja):"
echo " cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug"
echo " cmake --build build -j\$(nproc)"
'';
};
});
}
+348
View File
@@ -0,0 +1,348 @@
# NipoVPN Docker
This directory contains Docker files for building and running **NipoVPN** in either `server` or `agent` mode.
## Directory Structure
```text
nipovpn/
├── docker/
│ ├── Dockerfile
│ ├── docker-compose.yml
│ └── README.md
├── nipovpn/
│ └── etc/nipovpn/config.yaml
├── core/
├── CMakeLists.txt
└── .dockerignore
```
## Requirements
Install Docker and Docker Compose:
```bash
docker --version
docker compose version
```
For older systems:
```bash
docker-compose --version
```
## Important: `.dockerignore`
Create `.dockerignore` in the repository root:
```text
.git
.github
build
cmake-build-*
*.deb
*.tar.gz
*.log
```
This prevents local build files from being copied into the Docker image.
## Docker Compose File
The compose file is located at:
```bash
docker/docker-compose.yml
```
Example:
```yaml
services:
nipovpn:
container_name: nipovpn
build:
context: ..
dockerfile: docker/Dockerfile
image: nipovpn:latest
restart: unless-stopped
ports:
- "443:443"
- "8080:8080"
volumes:
- ../nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro
- nipovpn_logs:/var/log/nipovpn
command:
- ${NIPOVPN_MODE:-server}
- /etc/nipovpn/config.yaml
volumes:
nipovpn_logs:
```
## Build Image
From the `docker` directory:
```bash
cd docker
docker compose build
```
Or with old Docker Compose:
```bash
cd docker
docker-compose build
```
To rebuild without cache:
```bash
docker compose build --no-cache
```
## Run in Server Mode
Using environment variable:
```bash
cd docker
NIPOVPN_MODE=server docker compose up -d
```
Or create `docker/.env`:
```env
NIPOVPN_MODE=server
```
Then run:
```bash
docker compose up -d
```
The container will run:
```bash
nipovpn server /etc/nipovpn/config.yaml
```
## Run in Agent Mode
Using environment variable:
```bash
cd docker
NIPOVPN_MODE=agent docker compose up -d
```
Or create `docker/.env`:
```env
NIPOVPN_MODE=agent
```
Then run:
```bash
docker compose up -d
```
The container will run:
```bash
nipovpn agent /etc/nipovpn/config.yaml
```
## Specify Config File
By default, this file is mounted into the container:
```bash
../nipovpn/etc/nipovpn/config.yaml
```
Inside the container it becomes:
```bash
/etc/nipovpn/config.yaml
```
To use another config file, change this line in `docker-compose.yml`:
```yaml
volumes:
- ../nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro
```
Example:
```yaml
volumes:
- ./server-config.yaml:/etc/nipovpn/config.yaml:ro
```
Then run:
```bash
docker compose up -d
```
## View Logs
Show live container logs:
```bash
docker compose logs -f
```
Show logs only for NipoVPN service:
```bash
docker compose logs -f nipovpn
```
Read the log file inside the container volume:
```bash
docker exec -it nipovpn cat /var/log/nipovpn/nipovpn.log
```
Follow the log file:
```bash
docker exec -it nipovpn tail -f /var/log/nipovpn/nipovpn.log
```
## Stop Container
```bash
docker compose down
```
## Restart Container
```bash
docker compose restart
```
## Rebuild and Restart
```bash
docker compose down
docker compose build --no-cache
docker compose up -d
```
## Check Container Status
```bash
docker ps
```
Or:
```bash
docker compose ps
```
## Execute Shell Inside Container
```bash
docker exec -it nipovpn bash
```
## Run Manually Without Compose
Build image from repository root:
```bash
docker build -f docker/Dockerfile -t nipovpn:latest .
```
Run server mode:
```bash
docker run --rm \
--name nipovpn \
-p 443:443 \
-p 8080:8080 \
-v ./nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro \
nipovpn:latest server /etc/nipovpn/config.yaml
```
Run agent mode:
```bash
docker run --rm \
--name nipovpn \
-p 8080:8080 \
-v ./nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro \
nipovpn:latest agent /etc/nipovpn/config.yaml
```
## Common Problems
### CMakeCache path error
If you see an error like:
```text
CMakeCache.txt directory is different
```
your local `build/` directory was copied into Docker.
Fix:
```bash
rm -rf build
docker compose build --no-cache
```
Also make sure `.dockerignore` exists in the repository root.
### Port already in use
If port `443` or `8080` is already used, change the port mapping:
```yaml
ports:
- "8443:443"
- "8081:8080"
```
### Config changes are not applied
Restart the container:
```bash
docker compose restart
```
## Recommended Commands
Server:
```bash
cd docker
NIPOVPN_MODE=server docker compose up -d --build
docker compose logs -f
```
Agent:
```bash
cd docker
NIPOVPN_MODE=agent docker compose up -d --build
docker compose logs -f
```
+18
View File
@@ -0,0 +1,18 @@
## Install on Termux
### Requirements
libyaml-cpp >= 0.8
boost >= 1.88.0
### Dependencies
Install the dependencies
```bash
pkg install boost libyaml-cpp
```
### Install
Download the nipovpn_VERSION_termux_aarch64 version from releases pages
```bash
pkg install ./nipovpn_VERSION_termux_aarch64.deb
```
+84
View File
@@ -0,0 +1,84 @@
## Nix Guide
**Note:** Nix Flakes are an experimental feature and must be enabled before using any of the commands in this guide.
### Enable Flakes
* **NixOS:** Follow the instructions in the NixOS & Flakes Book:
[Enabling NixOS with Flakes](https://nixos-and-flakes.thiscute.world/nixos-with-flakes/nixos-with-flakes-enabled?utm_source=chatgpt.com#enable-nix-flakes)
* **Non-NixOS systems:** Add the following to `~/.config/nix/nix.conf` (or `/etc/nix/nix.conf`):
```bash
experimental-features = nix-command flakes
```
## Installation
### Install into your Nix profile
```bash
nix profile install github:MortezaBashsiz/nipovpn
```
### NixOS (system-wide installation)
Add the flake as an input in your system `flake.nix`:
```nix
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
nipovpn.url = "github:MortezaBashsiz/nipovpn";
};
outputs = { self, nixpkgs, nipovpn, ... }: {
nixosConfigurations.yourhostname = nixpkgs.lib.nixosSystem {
system = "x86_64-linux"; # or "aarch64-linux"
modules = [
./configuration.nix
{
environment.systemPackages = [
nipovpn.packages.${pkgs.system}.default
];
}
];
};
};
}
```
## Building
### Manual Build (without Nix)
For traditional builds on Linux, please refer to [`BuildLinux.md`](./BuildLinux.md).
### Build with Nix
From the repository root:
```bash
nix build
```
Or directly from GitHub without cloning:
```bash
nix build github:MortezaBashsiz/nipovpn
```
## Development
Enter the development shell with all dependencies pre-configured:
```bash
git clone https://github.com/MortezaBashsiz/nipovpn.git
cd nipovpn
nix develop
```
If the command completes successfully, the development environment is ready to use.
+1
View File
@@ -0,0 +1 @@
/etc/nipovpn/config.yaml
+7 -7
View File
@@ -1,7 +1,7 @@
Package : nipovpn
Version : 0.1
Maintainer : Morteza Bashsiz
Architecture : amd64
Description : Powerfull and Secure http/s Proxy
Depends : libyaml-cpp0.8
Homepage : https://github.com/MortezaBashsiz/nipovpn
Package: nipovpn
Version: 0.0.0
Maintainer: Morteza Bashsiz
Architecture: amd64
Depends: libyaml-cpp0.8
Homepage: https://github.com/MortezaBashsiz/nipovpn
Description: Powerful and secure proxy
+22 -9
View File
@@ -1,8 +1,21 @@
---
# This block contains general and global configuration which is in both modes
general:
# token: 32 bytes of string. this will be used on agent and server side to encryption
# 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.
# 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:
@@ -36,18 +49,18 @@ general:
# pullTimeout: unsigned short
# Defines the timeout for I/O Operation in milliseconds.
# Useful to expire serverside read timer.
pullTimeout: 50
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 false then it will use same connection between agent and server to handle client request
# If true then it will create new connection for each request between agent and server
# 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: false
tlsEnable: true
# tlsVerifyPeer: bool
# Use it to controll if the certificate should be validated or not
tlsVerifyPeer: false
@@ -60,7 +73,7 @@ general:
# This block is to define log directives
log:
# logLevel: "INFO|TRACE|DEBUG"
logLevel: "DEBUG"
logLevel: "INFO"
# logFile: "/var/log/nipo/nipo.log"
# Path of log file
logFile: "/var/log/nipovpn/nipovpn.log"
@@ -68,11 +81,11 @@ log:
# This block is to define server directives
server:
# threads: number of threads in server
threads: 8
threads: 2
# listenIp: which must be IPv4 which is used on server
listenIp: "0.0.0.0"
# listenPort: the port number which will be used on server
listenPort: 80
listenPort: 443
# This block is to define agent directives
@@ -86,7 +99,7 @@ agent:
# serverIp: IPv4 of the nipoServer
serverIp: "127.0.0.10"
# serverPort: port number of the nipoServer
serverPort: 80
serverPort: 443
# httpVersion: This version will be used between agent and server
httpVersion: "1.1"
# userAgent: This is the http user agent which will be used between agent and server
@@ -8,6 +8,7 @@ ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
Type=simple
LimitNOFILE=1048576
[Install]
WantedBy=multi-user.target
@@ -8,6 +8,7 @@ ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
Type=simple
LimitNOFILE=1048576
[Install]
WantedBy=multi-user.target
View File
Whitespace-only changes.