mirror of
https://github.com/WGDashboard/WGDashboard.git
synced 2026-08-04 23:13:02 +00:00
Compare commits
61 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 891990b2f1 | |||
| e9ab7029c9 | |||
| 6f681dba09 | |||
| b3edff947d | |||
| d35bd6e75b | |||
| f3a2f98864 | |||
| e21853286e | |||
| c012b8c4a5 | |||
| 48f6c28556 | |||
| 0c1502f801 | |||
| fec20ed381 | |||
| 252c147dcf | |||
| 453d474104 | |||
| 84cf4a9b66 | |||
| fb016bebde | |||
| 8f6a738481 | |||
| b07f958577 | |||
| 8da0fde52a | |||
| 39be16cb63 | |||
| 59d0c0def4 | |||
| 79c03db9a0 | |||
| 0c77823020 | |||
| deed7e0022 | |||
| 99db8c7335 | |||
| 9fe2aa9ed5 | |||
| 4c80dc256b | |||
| cafe9e9c11 | |||
| 27ff4e63b6 | |||
| 8020714e07 | |||
| dbd825ba4b | |||
| fee6cf29eb | |||
| 56287d8e7a | |||
| 45504eaf95 | |||
| b8a9b1150a | |||
| 8bd0e43f58 | |||
| 2c83e9e83c | |||
| 53c9ca10a7 | |||
| 75fbdac42e | |||
| 09d54546ca | |||
| b62fece3d0 | |||
| 284a2b7f64 | |||
| 9c873ccbbd | |||
| 5f72f90031 | |||
| 93cf3c69b8 | |||
| 88f856cbc7 | |||
| 2d5796d161 | |||
| acf4f3fbf0 | |||
| 8378030c70 | |||
| dc7140d486 | |||
| 3c50e4768a | |||
| 63dc9834be | |||
| f042e42633 | |||
| 39b80a2e7e | |||
| fb6e948358 | |||
| 181b0845bf | |||
| b2a82dcfe5 | |||
| ed1c05dec9 | |||
| cd73aef0c9 | |||
| ed522ec024 | |||
| a4151800f1 | |||
| 932f24c966 |
@@ -0,0 +1,56 @@
|
||||
name: Docker Image Build and Analysis
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * *" # Schedule the workflow to run daily at midnight (UTC time). Adjust the time if needed.
|
||||
workflow_dispatch: # Manual run trigger
|
||||
inputs:
|
||||
trigger-build:
|
||||
description: 'Trigger a manual build and push'
|
||||
default: 'true'
|
||||
|
||||
jobs:
|
||||
build-and-analyze:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Build Docker image
|
||||
id: build-image
|
||||
run: |
|
||||
echo "Building Docker image..."
|
||||
docker build -t my-app-image:latest .
|
||||
echo "Docker image built successfully."
|
||||
|
||||
- name: Install Docker Scout
|
||||
run: |
|
||||
echo "Installing Docker Scout..."
|
||||
curl -sSfL https://raw.githubusercontent.com/docker/scout-cli/main/install.sh | sh -s --
|
||||
echo "Docker Scout installed successfully."
|
||||
|
||||
- name: Analyze Docker image with Docker Scout
|
||||
id: analyze-image
|
||||
run: |
|
||||
echo "Analyzing Docker image with Docker Scout..."
|
||||
docker scout cves my-app-image:latest > scout-results.txt
|
||||
cat scout-results.txt # Print the report to the workflow logs for easy viewing
|
||||
echo "Docker Scout analysis completed."
|
||||
|
||||
- name: Post Comment on Issue or PR
|
||||
run: |
|
||||
COMMENT="**Docker Image Build and Analysis Report**\n\nThe Docker image was built and analyzed successfully.\n\n**Build Summary:**\n- Image Tag: my-app-image:latest\n\n**Analysis Report:**\n\`\`\`\n$(cat scout-results.txt)\n\`\`\`"
|
||||
|
||||
# Post comment using GitHub API
|
||||
curl -X POST \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
-d "{\"body\": \"$COMMENT\"}" \
|
||||
"https://api.github.com/repos/NOXCIS/WGDashboard/issues/1/comments" # Replace '1' with the issue or PR number
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
# Pull from small Debian stable image.
|
||||
FROM alpine:latest AS builder
|
||||
|
||||
LABEL maintainer="dselen@nerthus.nl"
|
||||
|
||||
WORKDIR /opt/wireguarddashboard/src
|
||||
|
||||
RUN apk update && \
|
||||
apk add --no-cache sudo gcc musl-dev rust cargo linux-headers
|
||||
|
||||
COPY ./docker/alpine/builder.sh /opt/wireguarddashboard/src/
|
||||
COPY ./docker/alpine/requirements.txt /opt/wireguarddashboard/src/
|
||||
RUN chmod u+x /opt/wireguarddashboard/src/builder.sh
|
||||
RUN /opt/wireguarddashboard/src/builder.sh
|
||||
|
||||
|
||||
FROM alpine:latest
|
||||
WORKDIR /opt/wireguarddashboard/src
|
||||
|
||||
COPY ./src /opt/wireguarddashboard/src/
|
||||
COPY --from=builder /opt/wireguarddashboard/src/venv /opt/wireguarddashboard/src/venv
|
||||
COPY --from=builder /opt/wireguarddashboard/src/log /opt/wireguarddashboard/src/log/
|
||||
|
||||
RUN apk update && \
|
||||
apk add --no-cache wireguard-tools sudo && \
|
||||
apk add --no-cache iptables ip6tables && \
|
||||
chmod u+x /opt/wireguarddashboard/src/entrypoint.sh
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD curl -f http://localhost:10086/signin || exit 1
|
||||
|
||||
ENTRYPOINT ["/opt/wireguarddashboard/src/entrypoint.sh"]
|
||||
@@ -24,6 +24,9 @@
|
||||
|
||||
## 📣 What's New: v4.0
|
||||
|
||||
> [!TIP]
|
||||
> [📹 Demo video on YouTube](https://www.youtube.com/watch?v=0mwzd5Gr2eU)
|
||||
|
||||
### 🎉 New Features
|
||||
|
||||
- **Updated dashboard design**: Re-designed some of the section with more modern style and layout, the UI is faster and more responsive, it also uses less memory. But overall is still the same dashboard you're familiarized.
|
||||
@@ -55,6 +58,8 @@
|
||||
> Also, huge thanks to who contributed to this major release:
|
||||
> @bolgovrussia, @eduardorosabales, @Profik, @airgapper, @tokon2000, @bkeenke, @kontorskiy777, @bugsse, @Johnnykson, @DaanSelen, @shuricksumy and many others!
|
||||
|
||||
|
||||
|
||||
<hr>
|
||||
|
||||
## 📋 Table of Content
|
||||
@@ -77,6 +82,7 @@
|
||||
* [Debian 11.10](#debian-1110)
|
||||
* [Red Hat Enterprise Linux 9.4 & CentOS 9-Stream](#red-hat-enterprise-linux-94--centos-9-stream)
|
||||
* [Fedora 40 & Fedora 39 & Fedora 38](#fedora-40--fedora-39--fedora-38)
|
||||
* [Alpine Linux 3.20.2](#alpine-linux-3202)
|
||||
* [Manual Installation](#manual-installation)
|
||||
* [🪜 Usage](#-usage)
|
||||
* [Start/Stop/Restart WGDashboard](#startstoprestart-wgdashboard)
|
||||
@@ -124,11 +130,11 @@
|
||||
> [!NOTE]
|
||||
> All operating systems below are tested by myself. All are ARM64 ran in UTM Virtual Machine.
|
||||
|
||||
| Ubuntu | Debian | Red Hat Enterprise Linux | CentOS | Fedora |
|
||||
|-----------|--------|--------------------------|----------|--------|
|
||||
| 20.04 LTS | 12.6 | 9.4 | 9-Stream | 40 |
|
||||
| 22.04 LTS | 11.10 | | | 39 |
|
||||
| 24.02 LTS | | | | 38 |
|
||||
| Ubuntu | Debian | Red Hat Enterprise Linux | CentOS | Fedora | Alpine Linux |
|
||||
|-----------|--------|--------------------------|----------|--------|------------------------|
|
||||
| 20.04 LTS | 12.6 | 9.4 | 9-Stream | 40 | 3.20.2 (Under Testing) |
|
||||
| 22.04 LTS | 11.10 | | | 39 | |
|
||||
| 24.02 LTS | | | | 38 | |
|
||||
|
||||
> [!TIP]
|
||||
> If you installed WGDashboard on other systems without any issues, please let me know. Thank you!
|
||||
@@ -256,6 +262,20 @@ firewall-cmd --add-port=51820/udp --permanent && \
|
||||
firewall-cmd --reload
|
||||
```
|
||||
|
||||
#### Alpine Linux 3.20.2
|
||||
|
||||
```shell
|
||||
setup-interfaces -a ; \
|
||||
rc-service networking --quiet start ; \
|
||||
printf "https://mirrors.aliyun.com/alpine/latest-stable/main\nhttps://mirrors.aliyun.com/alpine/latest-stable/community" > /etc/apk/repositories ; \
|
||||
apk update ; \
|
||||
apk add wireguard-tools python3 python3-dev git iptables net-tools gcc musl-dev linux-headers sudo ; \
|
||||
git clone -b v4.0-alpine-linux https://github.com/donaldzou/WGDashboard.git ; \
|
||||
cd ./WGDashboard/src ; \
|
||||
chmod +x ./wgd.sh ; \
|
||||
./wgd.sh install
|
||||
```
|
||||
|
||||
### Manual Installation
|
||||
|
||||
> [!NOTE]
|
||||
@@ -502,7 +522,7 @@ Endpoint = 0.0.0.0:51820
|
||||
|
||||
2. Update the dashboard
|
||||
```shell
|
||||
git pull https://github.com/donaldzou/WGDashboard.git v4.0 --force
|
||||
git pull https://github.com/donaldzou/WGDashboard.git --force
|
||||
```
|
||||
|
||||
3. Install
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
services:
|
||||
|
||||
wireguard-dashboard:
|
||||
build: ./
|
||||
container_name: wiregate
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
- SYS_MODULE
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- wg_net=10.0.0.1/24
|
||||
- wg_port=51820
|
||||
volumes:
|
||||
- wgd_configs:/etc/wireguard
|
||||
- wgd_app:/opt/wireguarddashboard/src
|
||||
ports:
|
||||
- 10086:10086/tcp
|
||||
- 51820:51820/udp
|
||||
sysctls:
|
||||
- net.ipv4.ip_forward=1
|
||||
- net.ipv4.conf.all.src_valid_mark=1
|
||||
|
||||
|
||||
volumes:
|
||||
wgd_configs:
|
||||
wgd_app:
|
||||
@@ -1,77 +0,0 @@
|
||||
# Pull from small Debian stable image.
|
||||
FROM debian:stable-slim
|
||||
LABEL maintainer="dselen@nerthus.nl"
|
||||
|
||||
# Declaring environment variables, change Peernet to an address you like, standard is a 24 bit subnet.
|
||||
ENV wg_net="10.0.0.1"
|
||||
# wg_net is used functionally as an ARG for its environment variable nature, do not change unless you know what you are doing.
|
||||
|
||||
# Following ENV variables are changable on container runtime because /entrypoint.sh handles that. See compose.yaml for more info.
|
||||
ENV tz="Europe/Amsterdam"
|
||||
ENV global_dns="1.1.1.1"
|
||||
ENV enable_wg0="false"
|
||||
ENV isolated_peers="true"
|
||||
ENV public_ip="0.0.0.0"
|
||||
|
||||
# Doing basic system maintenance. Change the timezone to the desired timezone.
|
||||
RUN ln -sf /usr/share/zoneinfo/${tz} /etc/localtime
|
||||
|
||||
# Doing package management operations, such as upgrading
|
||||
RUN apt-get update && apt-get upgrade -y \
|
||||
&& apt-get install -y --no-install-recommends curl \
|
||||
git \
|
||||
iproute2 \
|
||||
iptables \
|
||||
iputils-ping \
|
||||
openresolv \
|
||||
procps \
|
||||
python3 \
|
||||
python3-pip \
|
||||
python3-venv \
|
||||
traceroute \
|
||||
wireguard \
|
||||
wireguard-tools \
|
||||
&& apt-get remove linux-image-* --autoremove -y \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# Removing the Linux Image package to preserve space on the image, for this reason also deleting apt lists, to be able to install packages: run apt update.
|
||||
|
||||
# Using WGDASH -- like wg_net functionally as a ARG command. But it is needed in entrypoint.sh so it needs to be exported as environment variable.
|
||||
ENV WGDASH=/opt/wireguarddashboard
|
||||
RUN python3 -m venv ${WGDASH}/venv
|
||||
|
||||
# Doing WireGuard Dashboard installation measures. Modify the git clone command to get the preferred version, with a specific branch for example.
|
||||
RUN . ${WGDASH}/venv/bin/activate \
|
||||
&& git clone https://github.com/donaldzou/WGDashboard.git ${WGDASH}/app \
|
||||
&& pip3 install -r ${WGDASH}/app/src/requirements.txt \
|
||||
&& chmod +x ${WGDASH}/app/src/wgd.sh \
|
||||
&& .${WGDASH}/app/src/wgd.sh install
|
||||
|
||||
# Set the volume to be used for persistency.
|
||||
VOLUME /etc/wireguard
|
||||
|
||||
# Generate basic WireGuard interface. Echoing the WireGuard interface config for readability, adjust if you want it for efficiency.
|
||||
# Also setting the pipefail option, verbose: https://github.com/hadolint/hadolint/wiki/DL4006.
|
||||
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
|
||||
RUN wg genkey | tee /etc/wireguard/wg0_privatekey \
|
||||
&& echo "[Interface]" > /wg0.conf \
|
||||
&& echo "SaveConfig = true" >> /wg0.conf \
|
||||
&& echo "Address = ${wg_net}/24" >> /wg0.conf \
|
||||
&& echo "PrivateKey = $(cat /etc/wireguard/wg0_privatekey)" >> /wg0.conf \
|
||||
&& echo "PostUp = iptables -t nat -I POSTROUTING 1 -s ${wg_net}/24 -o $(ip -o -4 route show to default | awk '{print $NF}') -j MASQUERADE" >> /wg0.conf \
|
||||
&& echo "PostUp = iptables -I FORWARD -i wg0 -o wg0 -j DROP" >> /wg0.conf \
|
||||
&& echo "PreDown = iptables -t nat -D POSTROUTING 1" >> /wg0.conf \
|
||||
&& echo "PreDown = iptables -D FORWARD -i wg0 -o wg0 -j DROP" >> /wg0.conf \
|
||||
&& echo "ListenPort = 51820" >> /wg0.conf \
|
||||
#&& echo "DNS = ${global_dns}" >> /wg0.conf \
|
||||
&& rm /etc/wireguard/wg0_privatekey
|
||||
|
||||
# Defining a way for Docker to check the health of the container. In this case: checking the login URL.
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD curl -f http://localhost:10086/signin || exit 1
|
||||
|
||||
# Copy the basic entrypoint.sh script.
|
||||
COPY entrypoint.sh /entrypoint.sh
|
||||
|
||||
# Exposing the default WireGuard Dashboard port for web access.
|
||||
EXPOSE 10086
|
||||
ENTRYPOINT ["/bin/bash", "/entrypoint.sh"]
|
||||
@@ -0,0 +1,43 @@
|
||||
venv_python="./venv/bin/python3"
|
||||
venv_gunicorn="./venv/bin/gunicorn"
|
||||
pythonExecutable="python3"
|
||||
|
||||
|
||||
_check_and_set_venv(){
|
||||
VIRTUAL_ENV="./venv"
|
||||
if [ ! -d $VIRTUAL_ENV ]; then
|
||||
printf "[WGDashboard] Creating Python Virtual Environment under ./venv\n"
|
||||
{ $pythonExecutable -m venv $VIRTUAL_ENV; } >> ./log/install.txt
|
||||
fi
|
||||
|
||||
if ! $venv_python --version > /dev/null 2>&1
|
||||
then
|
||||
printf "[WGDashboard] %s Python Virtual Environment under ./venv failed to create. Halting now.\n" "$heavy_crossmark"
|
||||
kill $TOP_PID
|
||||
fi
|
||||
|
||||
source ${VIRTUAL_ENV}/bin/activate
|
||||
|
||||
}
|
||||
|
||||
build_core () {
|
||||
if [ ! -d "log" ]
|
||||
then
|
||||
printf "[WGDashboard] Creating ./log folder\n"
|
||||
mkdir "log"
|
||||
fi
|
||||
|
||||
|
||||
apk add --no-cache python3 net-tools python3-dev py3-virtualenv
|
||||
_check_and_set_venv
|
||||
printf "[WGDashboard] Upgrading Python Package Manage (PIP)\n"
|
||||
{ date; python3 -m pip install --upgrade pip; printf "\n\n"; } >> ./log/install.txt
|
||||
printf "[WGDashboard] Building Bcrypt & Psutil\n"
|
||||
{ date; python3 -m pip install -r requirements.txt ; printf "\n\n"; } >> ./log/install.txt
|
||||
printf "[WGDashboard] Build Successfull!\n"
|
||||
printf "[WGDashboard] Clean Up Pip!\n"
|
||||
{ date; rm -rf /opt/wireguarddashboard/src/venv/lib/python3.12/site-packages/pip* ; printf "\n\n"; } >> ./log/install.txt
|
||||
|
||||
}
|
||||
|
||||
build_core
|
||||
@@ -0,0 +1,2 @@
|
||||
bcrypt
|
||||
psutil
|
||||
@@ -1,23 +0,0 @@
|
||||
services:
|
||||
wireguard-dashboard:
|
||||
image: repo.nerthus.nl/app/wireguard-dashboard:latest
|
||||
restart: unless-stopped
|
||||
container_name: wire-dash
|
||||
environment:
|
||||
#- tz= # <--- Set container timezone, default: Europe/Amsterdam.
|
||||
#- global_dns= # <--- Set global DNS address, default: 1.1.1.1.
|
||||
- enable_wg0=true # <--- If true, wg0 will be started on container startup. default: false.
|
||||
- isolated_peers=false # <--- When set to true, it disallows peers to talk to eachother, setting to false, allows it, default: true.
|
||||
#- public_ip= # <--- Set public IP to ensure the correct one is chosen, defaulting to the IP give by ifconfig.me.
|
||||
ports:
|
||||
- 10086:10086/tcp
|
||||
- 51820:51820/udp
|
||||
volumes:
|
||||
- conf:/etc/wireguard
|
||||
- app:/opt/wireguarddashboard/app
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
|
||||
volumes:
|
||||
conf:
|
||||
app:
|
||||
@@ -1,109 +0,0 @@
|
||||
#!/bin/bash
|
||||
echo "Starting the WireGuard Dashboard Docker container."
|
||||
|
||||
clean_up() {
|
||||
# Cleaning out previous data such as the .pid file and starting the WireGuard Dashboard. Making sure to use the python venv.
|
||||
echo "Looking for remains of previous instances..."
|
||||
if [ -f "/opt/wireguarddashboard/app/src/gunicorn.pid" ]; then
|
||||
echo "Found old .pid file, removing."
|
||||
rm /opt/wireguarddashboard/app/src/gunicorn.pid
|
||||
else
|
||||
echo "No remains found, continuing."
|
||||
fi
|
||||
}
|
||||
|
||||
start_core() {
|
||||
# This first step is to ensure the wg0.conf file exists, and if not, then its copied over from the ephemeral container storage.
|
||||
if [ ! -f "/etc/wireguard/wg0.conf" ]; then
|
||||
cp "/wg0.conf" "/etc/wireguard/wg0.conf"
|
||||
echo "WireGuard interface file copied over."
|
||||
else
|
||||
echo "WireGuard interface file looks to already be existing."
|
||||
fi
|
||||
|
||||
echo "Activating Python venv and executing the WireGuard Dashboard service."
|
||||
|
||||
. "${WGDASH}"/venv/bin/activate
|
||||
cd "${WGDASH}"/app/src || return # If changing the directory fails (permission or presence error), then bash will exist this function, causing the WireGuard Dashboard to not be succesfully launched.
|
||||
bash wgd.sh start
|
||||
|
||||
# The following section takes care of the firewall rules regarding the 'isolated_peers' feature, which allows or drops packets destined from the wg0 to the wg0 interface.
|
||||
if [ "${isolated_peers,,}" = "false" ]; then
|
||||
echo "Isolated peers disabled, adjusting."
|
||||
|
||||
sed -i '/PostUp = iptables -I FORWARD -i wg0 -o wg0 -j DROP/d' /etc/wireguard/wg0.conf
|
||||
sed -i '/PreDown = iptables -D FORWARD -i wg0 -o wg0 -j DROP/d' /etc/wireguard/wg0.conf
|
||||
elif [ "${isolated_peers,,}" = "true" ]; then
|
||||
upblocking=$(grep -c "PostUp = iptables -I FORWARD -i wg0 -o wg0 -j DROP" /etc/wireguard/wg0.conf)
|
||||
downblocking=$(grep -c "PreDown = iptables -D FORWARD -i wg0 -o wg0 -j DROP" /etc/wireguard/wg0.conf)
|
||||
if [ "$upblocking" -lt 1 ] && [ "$downblocking" -lt 1 ]; then
|
||||
echo "Isolated peers enabled, adjusting."
|
||||
|
||||
sed -i '/PostUp = iptables -t nat -I POSTROUTING 1 -s/a PostUp = iptables -I FORWARD -i wg0 -o wg0 -j DROP' /etc/wireguard/wg0.conf
|
||||
sed -i '/PreDown = iptables -t nat -D POSTROUTING 1 -s/a PreDown = iptables -D FORWARD -i wg0 -o wg0 -j DROP' /etc/wireguard/wg0.conf
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# The following section takes care of
|
||||
if [ "${enable_wg0,,}" = "true" ]; then
|
||||
echo "Preference for wg0 to be turned on found."
|
||||
|
||||
wg-quick up wg0
|
||||
else
|
||||
echo "Preference for wg0 to be turned off found."
|
||||
fi
|
||||
}
|
||||
|
||||
set_envvars() {
|
||||
echo "Setting relevant variables for operation."
|
||||
|
||||
# If the timezone is different, for example in North-America or Asia.
|
||||
if [ "${tz}" != "$(cat /etc/timezone)" ]; then
|
||||
echo "Changing timezone."
|
||||
|
||||
ln -sf /usr/share/zoneinfo/"${tz}" /etc/localtime
|
||||
echo "${tz}" > /etc/timezone
|
||||
fi
|
||||
|
||||
# Changing the DNS used for clients and the dashboard itself.
|
||||
if [ "${global_dns}" != "$(grep "peer_global_dns = " /opt/wireguarddashboard/app/src/wg-dashboard.ini | awk '{print $NF}')" ]; then
|
||||
echo "Changing default dns."
|
||||
|
||||
#sed -i "s/^DNS = .*/DNS = ${global_dns}/" /etc/wireguard/wg0.conf # Uncomment if you want to have DNS on server-level.
|
||||
sed -i "s/^peer_global_dns = .*/peer_global_dns = ${global_dns}/" /opt/wireguarddashboard/app/src/wg-dashboard.ini
|
||||
fi
|
||||
|
||||
# Setting the public IP of the WireGuard Dashboard container host. If not defined, it will trying fetching it using a curl to ifconfig.me.
|
||||
if [ "${public_ip}" = "0.0.0.0" ]; then
|
||||
default_ip=$(curl -s ifconfig.me)
|
||||
echo "Trying to fetch the Public-IP using ifconfig.me: ${default_ip}"
|
||||
|
||||
sed -i "s/^remote_endpoint = .*/remote_endpoint = ${default_ip}/" /opt/wireguarddashboard/app/src/wg-dashboard.ini
|
||||
elif [ "${public_ip}" != "$(grep "remote_endpoint = " /opt/wireguarddashboard/app/src/wg-dashboard.ini | awk '{print $NF}')" ]; then
|
||||
echo "Setting the Public-IP using given variable: ${public_ip}"
|
||||
|
||||
sed -i "s/^remote_endpoint = .*/remote_endpoint = ${public_ip}/" /opt/wireguarddashboard/app/src/wg-dashboard.ini
|
||||
fi
|
||||
}
|
||||
|
||||
ensure_blocking() {
|
||||
sleep 1s
|
||||
echo "Ensuring container continuation."
|
||||
|
||||
# This function checks if the latest error log is created and tails it for docker logs uses.
|
||||
if find "/opt/wireguarddashboard/app/src/log" -mindepth 1 -maxdepth 1 -type f | read -r; then
|
||||
latestErrLog=$(find /opt/wireguarddashboard/app/src/log -name "error_*.log" | head -n 1)
|
||||
latestAccLog=$(find /opt/wireguarddashboard/app/src/log -name "access_*.log" | head -n 1)
|
||||
tail -f "${latestErrLog}" "${latestAccLog}"
|
||||
fi
|
||||
|
||||
# Blocking command in case of erroring. So the container does not quit.
|
||||
sleep infinity
|
||||
}
|
||||
|
||||
# Execute functions for the WireGuard Dashboard services, then set the environment variables
|
||||
clean_up
|
||||
start_core
|
||||
set_envvars
|
||||
ensure_blocking
|
||||
+164
-102
@@ -33,7 +33,7 @@ import threading
|
||||
|
||||
from flask.json.provider import DefaultJSONProvider
|
||||
|
||||
DASHBOARD_VERSION = 'v4.0'
|
||||
DASHBOARD_VERSION = 'v4.0.3'
|
||||
CONFIGURATION_PATH = os.getenv('CONFIGURATION_PATH', '.')
|
||||
DB_PATH = os.path.join(CONFIGURATION_PATH, 'db')
|
||||
if not os.path.isdir(DB_PATH):
|
||||
@@ -119,26 +119,30 @@ class DashboardLogger:
|
||||
self.loggerdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_log.db'),
|
||||
check_same_thread=False)
|
||||
self.loggerdb.row_factory = sqlite3.Row
|
||||
self.loggerdbCursor = self.loggerdb.cursor()
|
||||
self.__createLogDatabase()
|
||||
self.log(Message="WGDashboard started")
|
||||
def __createLogDatabase(self):
|
||||
existingTable = self.loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
|
||||
with self.loggerdb:
|
||||
loggerdbCursor = self.loggerdb.cursor()
|
||||
existingTable = loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
|
||||
existingTable = [t['name'] for t in existingTable]
|
||||
|
||||
if "DashboardLog" not in existingTable:
|
||||
self.loggerdbCursor.execute(
|
||||
loggerdbCursor.execute(
|
||||
"CREATE TABLE DashboardLog (LogID VARCHAR NOT NULL, LogDate DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now', 'localtime')), URL VARCHAR, IP VARCHAR, Status VARCHAR, Message VARCHAR, PRIMARY KEY (LogID))")
|
||||
if self.loggerdb.in_transaction:
|
||||
self.loggerdb.commit()
|
||||
|
||||
def log(self, URL: str = "", IP: str = "", Status: str = "true", Message: str = "") -> bool:
|
||||
try:
|
||||
self.loggerdbCursor.execute(
|
||||
with self.loggerdb:
|
||||
loggerdbCursor = self.loggerdb.cursor()
|
||||
loggerdbCursor.execute(
|
||||
"INSERT INTO DashboardLog (LogID, URL, IP, Status, Message) VALUES (?, ?, ?, ?, ?)", (str(uuid.uuid4()), URL, IP, Status, Message,))
|
||||
if self.loggerdb.in_transaction:
|
||||
self.loggerdb.commit()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(e)
|
||||
print(f"[WGDashboard] Access Log Error: {str(e)}")
|
||||
return False
|
||||
|
||||
class PeerJobLogger:
|
||||
@@ -147,23 +151,29 @@ class PeerJobLogger:
|
||||
check_same_thread=False)
|
||||
self.loggerdb.row_factory = sqlite3.Row
|
||||
self.logs:list(Log) = []
|
||||
self.loggerdbCursor = self.loggerdb.cursor()
|
||||
self.__createLogDatabase()
|
||||
|
||||
def __createLogDatabase(self):
|
||||
existingTable = self.loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
|
||||
with self.loggerdb:
|
||||
loggerdbCursor = self.loggerdb.cursor()
|
||||
|
||||
existingTable = loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
|
||||
existingTable = [t['name'] for t in existingTable]
|
||||
|
||||
if "JobLog" not in existingTable:
|
||||
self.loggerdbCursor.execute("CREATE TABLE JobLog (LogID VARCHAR NOT NULL, JobID NOT NULL, LogDate DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now', 'localtime')), Status VARCHAR NOT NULL, Message VARCHAR, PRIMARY KEY (LogID))")
|
||||
loggerdbCursor.execute("CREATE TABLE JobLog (LogID VARCHAR NOT NULL, JobID NOT NULL, LogDate DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now', 'localtime')), Status VARCHAR NOT NULL, Message VARCHAR, PRIMARY KEY (LogID))")
|
||||
if self.loggerdb.in_transaction:
|
||||
self.loggerdb.commit()
|
||||
def log(self, JobID: str, Status: bool = True, Message: str = "") -> bool:
|
||||
try:
|
||||
self.loggerdbCursor.execute(f"INSERT INTO JobLog (LogID, JobID, Status, Message) VALUES (?, ?, ?, ?)",
|
||||
with self.loggerdb:
|
||||
loggerdbCursor = self.loggerdb.cursor()
|
||||
loggerdbCursor.execute(f"INSERT INTO JobLog (LogID, JobID, Status, Message) VALUES (?, ?, ?, ?)",
|
||||
(str(uuid.uuid4()), JobID, Status, Message,))
|
||||
if self.loggerdb.in_transaction:
|
||||
self.loggerdb.commit()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
print(f"[WGDashboard] Peer Job Log Error: {str(e)}")
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -172,7 +182,9 @@ class PeerJobLogger:
|
||||
try:
|
||||
allJobs = AllPeerJobs.getAllJobs(configName)
|
||||
allJobsID = ", ".join([f"'{x.JobID}'" for x in allJobs])
|
||||
table = self.loggerdb.execute(f"SELECT * FROM JobLog WHERE JobID IN ({allJobsID}) ORDER BY LogDate DESC").fetchall()
|
||||
with self.loggerdb:
|
||||
loggerdbCursor = self.loggerdb.cursor()
|
||||
table = loggerdbCursor.execute(f"SELECT * FROM JobLog WHERE JobID IN ({allJobsID}) ORDER BY LogDate DESC").fetchall()
|
||||
self.logs.clear()
|
||||
for l in table:
|
||||
logs.append(
|
||||
@@ -217,13 +229,14 @@ class PeerJobs:
|
||||
self.jobdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_job.db'),
|
||||
check_same_thread=False)
|
||||
self.jobdb.row_factory = sqlite3.Row
|
||||
self.jobdbCursor = self.jobdb.cursor()
|
||||
self.__createPeerJobsDatabase()
|
||||
self.__getJobs()
|
||||
|
||||
def __getJobs(self):
|
||||
self.Jobs.clear()
|
||||
jobs = self.jobdbCursor.execute("SELECT * FROM PeerJobs WHERE ExpireDate IS NULL").fetchall()
|
||||
with self.jobdb:
|
||||
jobdbCursor = self.jobdb.cursor()
|
||||
jobs = jobdbCursor.execute("SELECT * FROM PeerJobs WHERE ExpireDate IS NULL").fetchall()
|
||||
for job in jobs:
|
||||
self.Jobs.append(PeerJob(
|
||||
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'],
|
||||
@@ -231,7 +244,9 @@ class PeerJobs:
|
||||
|
||||
def getAllJobs(self, configuration: str = None):
|
||||
if configuration is not None:
|
||||
jobs = self.jobdbCursor.execute(
|
||||
with self.jobdb:
|
||||
jobdbCursor = self.jobdb.cursor()
|
||||
jobs = jobdbCursor.execute(
|
||||
f"SELECT * FROM PeerJobs WHERE Configuration = ?", (configuration, )).fetchall()
|
||||
j = []
|
||||
for job in jobs:
|
||||
@@ -242,11 +257,14 @@ class PeerJobs:
|
||||
return []
|
||||
|
||||
def __createPeerJobsDatabase(self):
|
||||
existingTable = self.jobdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
|
||||
with self.jobdb:
|
||||
jobdbCursor = self.jobdb.cursor()
|
||||
|
||||
existingTable = jobdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
|
||||
existingTable = [t['name'] for t in existingTable]
|
||||
|
||||
if "PeerJobs" not in existingTable:
|
||||
self.jobdbCursor.execute('''
|
||||
jobdbCursor.execute('''
|
||||
CREATE TABLE PeerJobs (JobID VARCHAR NOT NULL, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL,
|
||||
Field VARCHAR NOT NULL, Operator VARCHAR NOT NULL, Value VARCHAR NOT NULL, CreationDate DATETIME,
|
||||
ExpireDate DATETIME, Action VARCHAR NOT NULL, PRIMARY KEY (JobID))
|
||||
@@ -261,16 +279,19 @@ class PeerJobs:
|
||||
|
||||
def saveJob(self, Job: PeerJob) -> tuple[bool, list] | tuple[bool, str]:
|
||||
try:
|
||||
with self.jobdb:
|
||||
jobdbCursor = self.jobdb.cursor()
|
||||
|
||||
if (len(str(Job.CreationDate))) == 0:
|
||||
self.jobdbCursor.execute('''
|
||||
jobdbCursor.execute('''
|
||||
INSERT INTO PeerJobs VALUES (?, ?, ?, ?, ?, ?, strftime('%Y-%m-%d %H:%M:%S','now'), NULL, ?)
|
||||
''', (Job.JobID, Job.Configuration, Job.Peer, Job.Field, Job.Operator, Job.Value, Job.Action,))
|
||||
JobLogger.log(Job.JobID, Message=f"Job is created if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}")
|
||||
|
||||
else:
|
||||
currentJob = self.jobdbCursor.execute('SELECT * FROM PeerJobs WHERE JobID = ?', (Job.JobID, )).fetchone()
|
||||
currentJob = jobdbCursor.execute('SELECT * FROM PeerJobs WHERE JobID = ?', (Job.JobID, )).fetchone()
|
||||
if currentJob is not None:
|
||||
self.jobdbCursor.execute('''
|
||||
jobdbCursor.execute('''
|
||||
UPDATE PeerJobs SET Field = ?, Operator = ?, Value = ?, Action = ? WHERE JobID = ?
|
||||
''', (Job.Field, Job.Operator, Job.Value, Job.Action, Job.JobID))
|
||||
JobLogger.log(Job.JobID,
|
||||
@@ -288,7 +309,9 @@ class PeerJobs:
|
||||
try:
|
||||
if (len(str(Job.CreationDate))) == 0:
|
||||
return False, "Job does not exist"
|
||||
self.jobdbCursor.execute('''
|
||||
with self.jobdb:
|
||||
jobdbCursor = self.jobdb.cursor()
|
||||
jobdbCursor.execute('''
|
||||
UPDATE PeerJobs SET ExpireDate = strftime('%Y-%m-%d %H:%M:%S','now') WHERE JobID = ?
|
||||
''', (Job.JobID,))
|
||||
self.jobdb.commit()
|
||||
@@ -364,10 +387,9 @@ class PeerShareLink:
|
||||
class PeerShareLinks:
|
||||
def __init__(self):
|
||||
self.Links: list[PeerShareLink] = []
|
||||
self.PeerShareLinkCursor = sqldb.cursor()
|
||||
existingTables = self.PeerShareLinkCursor.execute("SELECT name FROM sqlite_master WHERE type='table' and name = 'PeerShareLinks'").fetchall()
|
||||
existingTables = sqlSelect("SELECT name FROM sqlite_master WHERE type='table' and name = 'PeerShareLinks'").fetchall()
|
||||
if len(existingTables) == 0:
|
||||
self.PeerShareLinkCursor.execute(
|
||||
sqlUpdate(
|
||||
"""
|
||||
CREATE TABLE PeerShareLinks (
|
||||
ShareID VARCHAR NOT NULL PRIMARY KEY, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL,
|
||||
@@ -376,12 +398,12 @@ class PeerShareLinks:
|
||||
)
|
||||
"""
|
||||
)
|
||||
sqldb.commit()
|
||||
# sqldb.commit()
|
||||
self.__getSharedLinks()
|
||||
# print(self.Links)
|
||||
def __getSharedLinks(self):
|
||||
self.Links.clear()
|
||||
allLinks = self.PeerShareLinkCursor.execute("SELECT * FROM PeerShareLinks WHERE ExpireDate IS NULL OR ExpireDate > datetime('now', 'localtime')").fetchall()
|
||||
allLinks = sqlSelect("SELECT * FROM PeerShareLinks WHERE ExpireDate IS NULL OR ExpireDate > datetime('now', 'localtime')").fetchall()
|
||||
for link in allLinks:
|
||||
self.Links.append(PeerShareLink(*link))
|
||||
|
||||
@@ -397,18 +419,17 @@ class PeerShareLinks:
|
||||
try:
|
||||
newShareID = str(uuid.uuid4())
|
||||
if len(self.getLink(Configuration, Peer)) > 0:
|
||||
self.PeerShareLinkCursor.execute("UPDATE PeerShareLinks SET ExpireDate = datetime('now', 'localtime') WHERE Configuration = ? AND Peer = ?", (Configuration, Peer, ))
|
||||
self.PeerShareLinkCursor.execute("INSERT INTO PeerShareLinks (ShareID, Configuration, Peer, ExpireDate) VALUES (?, ?, ?, ?)", (newShareID, Configuration, Peer, ExpireDate, ))
|
||||
sqldb.commit()
|
||||
sqlUpdate("UPDATE PeerShareLinks SET ExpireDate = datetime('now', 'localtime') WHERE Configuration = ? AND Peer = ?", (Configuration, Peer, ))
|
||||
sqlUpdate("INSERT INTO PeerShareLinks (ShareID, Configuration, Peer, ExpireDate) VALUES (?, ?, ?, ?)", (newShareID, Configuration, Peer, ExpireDate, ))
|
||||
# sqldb.commit()
|
||||
self.__getSharedLinks()
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
return True, newShareID
|
||||
|
||||
def updateLinkExpireDate(self, ShareID, ExpireDate: datetime = None) -> tuple[bool, str]:
|
||||
|
||||
self.PeerShareLinkCursor.execute("UPDATE PeerShareLinks SET ExpireDate = ? WHERE ShareID = ?;", (ExpireDate, ShareID, ))
|
||||
sqldb.commit()
|
||||
sqlUpdate("UPDATE PeerShareLinks SET ExpireDate = ? WHERE ShareID = ?;", (ExpireDate, ShareID, ))
|
||||
# sqldb.commit()
|
||||
self.__getSharedLinks()
|
||||
return True, ""
|
||||
|
||||
@@ -421,6 +442,8 @@ class WireguardConfiguration:
|
||||
return self.message
|
||||
|
||||
def __init__(self, name: str = None, data: dict = None):
|
||||
print(f"[WGDashboard] Initialized Configuration: {name}")
|
||||
|
||||
self.__parser: configparser.ConfigParser = configparser.ConfigParser(strict=False)
|
||||
self.__parser.optionxform = str
|
||||
self.__configFileModifiedTime = None
|
||||
@@ -490,12 +513,13 @@ class WireguardConfiguration:
|
||||
# Create tables in database
|
||||
self.__createDatabase()
|
||||
self.getPeersList()
|
||||
self.getRestrictedPeersList()
|
||||
|
||||
def __createDatabase(self):
|
||||
existingTables = sqldb.cursor().execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
|
||||
existingTables = sqlSelect("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
|
||||
existingTables = [t['name'] for t in existingTables]
|
||||
if self.Name not in existingTables:
|
||||
sqldb.cursor().execute(
|
||||
sqlUpdate(
|
||||
"""
|
||||
CREATE TABLE '%s'(
|
||||
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
|
||||
@@ -508,10 +532,10 @@ class WireguardConfiguration:
|
||||
)
|
||||
""" % self.Name
|
||||
)
|
||||
sqldb.commit()
|
||||
# sqldb.commit()
|
||||
|
||||
if f'{self.Name}_restrict_access' not in existingTables:
|
||||
sqldb.cursor().execute(
|
||||
sqlUpdate(
|
||||
"""
|
||||
CREATE TABLE '%s_restrict_access' (
|
||||
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
|
||||
@@ -524,9 +548,9 @@ class WireguardConfiguration:
|
||||
)
|
||||
""" % self.Name
|
||||
)
|
||||
sqldb.commit()
|
||||
# sqldb.commit()
|
||||
if f'{self.Name}_transfer' not in existingTables:
|
||||
sqldb.cursor().execute(
|
||||
sqlUpdate(
|
||||
"""
|
||||
CREATE TABLE '%s_transfer' (
|
||||
id VARCHAR NOT NULL, total_receive FLOAT NULL,
|
||||
@@ -535,9 +559,9 @@ class WireguardConfiguration:
|
||||
)
|
||||
""" % self.Name
|
||||
)
|
||||
sqldb.commit()
|
||||
# sqldb.commit()
|
||||
if f'{self.Name}_deleted' not in existingTables:
|
||||
sqldb.cursor().execute(
|
||||
sqlUpdate(
|
||||
"""
|
||||
CREATE TABLE '%s_deleted' (
|
||||
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
|
||||
@@ -550,7 +574,7 @@ class WireguardConfiguration:
|
||||
)
|
||||
""" % self.Name
|
||||
)
|
||||
sqldb.commit()
|
||||
# sqldb.commit()
|
||||
|
||||
|
||||
|
||||
@@ -563,14 +587,19 @@ class WireguardConfiguration:
|
||||
|
||||
def __getRestrictedPeers(self):
|
||||
self.RestrictedPeers = []
|
||||
restricted = sqldb.cursor().execute("SELECT * FROM '%s_restrict_access'" % self.Name).fetchall()
|
||||
restricted = sqlSelect("SELECT * FROM '%s_restrict_access'" % self.Name).fetchall()
|
||||
for i in restricted:
|
||||
self.RestrictedPeers.append(Peer(i, self))
|
||||
|
||||
def configurationFileChanged(self) :
|
||||
mt = os.path.getmtime(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'))
|
||||
changed = self.__configFileModifiedTime is None or self.__configFileModifiedTime != mt
|
||||
self.__configFileModifiedTime = mt
|
||||
return changed
|
||||
|
||||
def __getPeers(self):
|
||||
|
||||
mt = os.path.getmtime(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'))
|
||||
# if self.__configFileModifiedTime is None or self.__configFileModifiedTime != mt:
|
||||
if self.configurationFileChanged():
|
||||
self.Peers = []
|
||||
with open(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'), 'r') as configFile:
|
||||
p = []
|
||||
@@ -599,7 +628,7 @@ class WireguardConfiguration:
|
||||
|
||||
for i in p:
|
||||
if "PublicKey" in i.keys():
|
||||
checkIfExist = sqldb.cursor().execute("SELECT * FROM '%s' WHERE id = ?" % self.Name,
|
||||
checkIfExist = sqlSelect("SELECT * FROM '%s' WHERE id = ?" % self.Name,
|
||||
((i['PublicKey']),)).fetchone()
|
||||
if checkIfExist is None:
|
||||
newPeer = {
|
||||
@@ -625,7 +654,7 @@ class WireguardConfiguration:
|
||||
"remote_endpoint": DashboardConfig.GetConfig("Peers", "remote_endpoint")[1],
|
||||
"preshared_key": i["PresharedKey"] if "PresharedKey" in i.keys() else ""
|
||||
}
|
||||
sqldb.cursor().execute(
|
||||
sqlUpdate(
|
||||
"""
|
||||
INSERT INTO '%s'
|
||||
VALUES (:id, :private_key, :DNS, :endpoint_allowed_ip, :name, :total_receive, :total_sent,
|
||||
@@ -633,16 +662,21 @@ class WireguardConfiguration:
|
||||
:cumu_data, :mtu, :keepalive, :remote_endpoint, :preshared_key);
|
||||
""" % self.Name
|
||||
, newPeer)
|
||||
sqldb.commit()
|
||||
# sqldb.commit()
|
||||
self.Peers.append(Peer(newPeer, self))
|
||||
else:
|
||||
sqldb.cursor().execute("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self.Name,
|
||||
sqlUpdate("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self.Name,
|
||||
(i.get("AllowedIPs", "N/A"), i['PublicKey'],))
|
||||
sqldb.commit()
|
||||
# sqldb.commit()
|
||||
self.Peers.append(Peer(checkIfExist, self))
|
||||
except Exception as e:
|
||||
print(f"[WGDashboard] {self.Name} Error: {str(e)}")
|
||||
self.__configFileModifiedTime = mt
|
||||
else:
|
||||
self.Peers.clear()
|
||||
checkIfExist = sqlSelect("SELECT * FROM '%s'" % self.Name).fetchall()
|
||||
for i in checkIfExist:
|
||||
self.Peers.append(Peer(i, self))
|
||||
|
||||
|
||||
def addPeers(self, peers: list):
|
||||
for p in peers:
|
||||
@@ -665,11 +699,11 @@ class WireguardConfiguration:
|
||||
self.toggleConfiguration()
|
||||
|
||||
for i in listOfPublicKeys:
|
||||
p = sqldb.cursor().execute("SELECT * FROM '%s_restrict_access' WHERE id = ?" % self.Name, (i,)).fetchone()
|
||||
p = sqlSelect("SELECT * FROM '%s_restrict_access' WHERE id = ?" % self.Name, (i,)).fetchone()
|
||||
if p is not None:
|
||||
sqldb.cursor().execute("INSERT INTO '%s' SELECT * FROM %s_restrict_access WHERE id = ?"
|
||||
sqlUpdate("INSERT INTO '%s' SELECT * FROM %s_restrict_access WHERE id = ?"
|
||||
% (self.Name, self.Name,), (p['id'],))
|
||||
sqldb.cursor().execute("DELETE FROM '%s_restrict_access' WHERE id = ?"
|
||||
sqlUpdate("DELETE FROM '%s_restrict_access' WHERE id = ?"
|
||||
% self.Name, (p['id'],))
|
||||
subprocess.check_output(f"wg set {self.Name} peer {p['id']} allowed-ips {p['allowed_ip']}",
|
||||
shell=True, stderr=subprocess.STDOUT)
|
||||
@@ -692,11 +726,12 @@ class WireguardConfiguration:
|
||||
try:
|
||||
subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove",
|
||||
shell=True, stderr=subprocess.STDOUT)
|
||||
sqldb.cursor().execute("INSERT INTO '%s_restrict_access' SELECT * FROM %s WHERE id = ?" %
|
||||
sqlUpdate("INSERT INTO '%s_restrict_access' SELECT * FROM %s WHERE id = ?" %
|
||||
(self.Name, self.Name,), (pf.id,))
|
||||
sqldb.cursor().execute("UPDATE '%s_restrict_access' SET status = 'stopped' WHERE id = ?" %
|
||||
sqlUpdate("UPDATE '%s_restrict_access' SET status = 'stopped' WHERE id = ?" %
|
||||
(self.Name,), (pf.id,))
|
||||
sqldb.cursor().execute("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,))
|
||||
sqlUpdate("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,))
|
||||
# sqldb.commit()
|
||||
numOfRestrictedPeers += 1
|
||||
except Exception as e:
|
||||
numOfFailedToRestrictPeers += 1
|
||||
@@ -723,7 +758,7 @@ class WireguardConfiguration:
|
||||
try:
|
||||
subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove",
|
||||
shell=True, stderr=subprocess.STDOUT)
|
||||
sqldb.cursor().execute("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,))
|
||||
sqlUpdate("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,))
|
||||
numOfDeletedPeers += 1
|
||||
except Exception as e:
|
||||
numOfFailedToDeletePeers += 1
|
||||
@@ -780,12 +815,11 @@ class WireguardConfiguration:
|
||||
else:
|
||||
status = "stopped"
|
||||
if int(latestHandshake[count + 1]) > 0:
|
||||
sqldb.execute("UPDATE '%s' SET latest_handshake = ?, status = ? WHERE id= ?" % self.Name
|
||||
sqlUpdate("UPDATE '%s' SET latest_handshake = ?, status = ? WHERE id= ?" % self.Name
|
||||
, (str(minus).split(".", maxsplit=1)[0], status, latestHandshake[count],))
|
||||
else:
|
||||
sqldb.execute("UPDATE '%s' SET latest_handshake = 'No Handshake', status = ? WHERE id= ?" % self.Name
|
||||
sqlUpdate("UPDATE '%s' SET latest_handshake = 'No Handshake', status = ? WHERE id= ?" % self.Name
|
||||
, (status, latestHandshake[count],))
|
||||
sqldb.commit()
|
||||
count += 2
|
||||
|
||||
|
||||
@@ -799,7 +833,7 @@ class WireguardConfiguration:
|
||||
data_usage = [p.split("\t") for p in data_usage]
|
||||
for i in range(len(data_usage)):
|
||||
if len(data_usage[i]) == 3:
|
||||
cur_i = sqldb.cursor().execute(
|
||||
cur_i = sqlSelect(
|
||||
"SELECT total_receive, total_sent, cumu_receive, cumu_sent, status FROM '%s' WHERE id= ? "
|
||||
% self.Name, (data_usage[i][0],)).fetchone()
|
||||
if cur_i is not None:
|
||||
@@ -814,7 +848,7 @@ class WireguardConfiguration:
|
||||
total_sent = cur_total_sent
|
||||
total_receive = cur_total_receive
|
||||
else:
|
||||
sqldb.cursor().execute(
|
||||
sqlUpdate(
|
||||
"UPDATE '%s' SET cumu_receive = ?, cumu_sent = ?, cumu_data = ? WHERE id = ?" %
|
||||
self.Name, (cumulative_receive, cumulative_sent,
|
||||
cumulative_sent + cumulative_receive,
|
||||
@@ -824,7 +858,7 @@ class WireguardConfiguration:
|
||||
total_receive = 0
|
||||
_, p = self.searchPeer(data_usage[i][0])
|
||||
if p.total_receive != total_receive or p.total_sent != total_sent:
|
||||
sqldb.cursor().execute(
|
||||
sqlUpdate(
|
||||
"UPDATE '%s' SET total_receive = ?, total_sent = ?, total_data = ? WHERE id = ?"
|
||||
% self.Name, (total_receive, total_sent,
|
||||
total_receive + total_sent, data_usage[i][0],))
|
||||
@@ -845,7 +879,7 @@ class WireguardConfiguration:
|
||||
for _ in range(int(len(data_usage) / 2)):
|
||||
sqldb.execute("UPDATE '%s' SET endpoint = ? WHERE id = ?" % self.Name
|
||||
, (data_usage[count + 1], data_usage[count],))
|
||||
sqldb.commit()
|
||||
# sqldb.commit()
|
||||
count += 2
|
||||
|
||||
def toggleConfiguration(self) -> [bool, str]:
|
||||
@@ -980,7 +1014,7 @@ class Peer:
|
||||
if f"wg showconf {self.configuration.Name}" not in saveConfig.decode().strip('\n'):
|
||||
return ResponseObject(False,
|
||||
"Update peer failed when saving the configuration.")
|
||||
sqldb.cursor().execute(
|
||||
sqlUpdate(
|
||||
'''UPDATE '%s' SET name = ?, private_key = ?, DNS = ?, endpoint_allowed_ip = ?, mtu = ?,
|
||||
keepalive = ?, preshared_key = ? WHERE id = ?''' % self.configuration.Name,
|
||||
(name, private_key, dns_addresses, endpoint_allowed_ip, mtu,
|
||||
@@ -1033,11 +1067,11 @@ PersistentKeepalive = {str(self.keepalive)}
|
||||
def resetDataUsage(self, type):
|
||||
try:
|
||||
if type == "total":
|
||||
sqldb.cursor().execute("UPDATE '%s' SET total_data = 0, cumu_data = 0, total_receive = 0, cumu_receive = 0, total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
|
||||
sqlUpdate("UPDATE '%s' SET total_data = 0, cumu_data = 0, total_receive = 0, cumu_receive = 0, total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
|
||||
elif type == "receive":
|
||||
sqldb.cursor().execute("UPDATE '%s' SET total_receive = 0, cumu_receive = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
|
||||
sqlUpdate("UPDATE '%s' SET total_receive = 0, cumu_receive = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
|
||||
elif type == "sent":
|
||||
sqldb.cursor().execute("UPDATE '%s' SET total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
|
||||
sqlUpdate("UPDATE '%s' SET total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
|
||||
else:
|
||||
return False
|
||||
except Exception as e:
|
||||
@@ -1051,7 +1085,7 @@ def regex_match(regex, text):
|
||||
|
||||
def iPv46RegexCheck(ip):
|
||||
return re.match(
|
||||
'((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))',
|
||||
r'((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))',
|
||||
ip)
|
||||
|
||||
class DashboardAPIKey:
|
||||
@@ -1115,15 +1149,17 @@ class DashboardConfig:
|
||||
self.__createAPIKeyTable()
|
||||
self.DashboardAPIKeys = self.__getAPIKeys()
|
||||
self.APIAccessed = False
|
||||
self.SetConfig("Server", "version", DASHBOARD_VERSION)
|
||||
|
||||
|
||||
def __createAPIKeyTable(self):
|
||||
existingTable = sqldb.cursor().execute("SELECT name FROM sqlite_master WHERE type='table' AND name = 'DashboardAPIKeys'").fetchall()
|
||||
existingTable = sqlSelect("SELECT name FROM sqlite_master WHERE type='table' AND name = 'DashboardAPIKeys'").fetchall()
|
||||
if len(existingTable) == 0:
|
||||
sqldb.cursor().execute("CREATE TABLE DashboardAPIKeys (Key VARCHAR NOT NULL PRIMARY KEY, CreatedAt DATETIME NOT NULL DEFAULT (datetime('now', 'localtime')), ExpiredAt VARCHAR)")
|
||||
sqldb.commit()
|
||||
sqlUpdate("CREATE TABLE DashboardAPIKeys (Key VARCHAR NOT NULL PRIMARY KEY, CreatedAt DATETIME NOT NULL DEFAULT (datetime('now', 'localtime')), ExpiredAt VARCHAR)")
|
||||
# sqldb.commit()
|
||||
|
||||
def __getAPIKeys(self) -> list[DashboardAPIKey]:
|
||||
keys = sqldb.cursor().execute("SELECT * FROM DashboardAPIKeys WHERE ExpiredAt IS NULL OR ExpiredAt > datetime('now', 'localtime') ORDER BY CreatedAt DESC").fetchall()
|
||||
keys = sqlSelect("SELECT * FROM DashboardAPIKeys WHERE ExpiredAt IS NULL OR ExpiredAt > datetime('now', 'localtime') ORDER BY CreatedAt DESC").fetchall()
|
||||
fKeys = []
|
||||
for k in keys:
|
||||
fKeys.append(DashboardAPIKey(*k))
|
||||
@@ -1131,13 +1167,13 @@ class DashboardConfig:
|
||||
|
||||
def createAPIKeys(self, ExpiredAt = None):
|
||||
newKey = secrets.token_urlsafe(32)
|
||||
sqldb.cursor().execute('INSERT INTO DashboardAPIKeys (Key, ExpiredAt) VALUES (?, ?)', (newKey, ExpiredAt,))
|
||||
sqldb.commit()
|
||||
sqlUpdate('INSERT INTO DashboardAPIKeys (Key, ExpiredAt) VALUES (?, ?)', (newKey, ExpiredAt,))
|
||||
# sqldb.commit()
|
||||
self.DashboardAPIKeys = self.__getAPIKeys()
|
||||
|
||||
def deleteAPIKey(self, key):
|
||||
sqldb.cursor().execute("UPDATE DashboardAPIKeys SET ExpiredAt = datetime('now', 'localtime') WHERE Key = ?", (key, ))
|
||||
sqldb.commit()
|
||||
sqlUpdate("UPDATE DashboardAPIKeys SET ExpiredAt = datetime('now', 'localtime') WHERE Key = ?", (key, ))
|
||||
# sqldb.commit()
|
||||
self.DashboardAPIKeys = self.__getAPIKeys()
|
||||
|
||||
|
||||
@@ -1259,16 +1295,20 @@ def _regexMatch(regex, text):
|
||||
return pattern.search(text) is not None
|
||||
|
||||
|
||||
def _getConfigurationList() -> [WireguardConfiguration]:
|
||||
configurations = {}
|
||||
def _getConfigurationList():
|
||||
# configurations = {}
|
||||
for i in os.listdir(WG_CONF_PATH):
|
||||
if _regexMatch("^(.{1,}).(conf)$", i):
|
||||
i = i.replace('.conf', '')
|
||||
try:
|
||||
configurations[i] = WireguardConfiguration(i)
|
||||
if i in WireguardConfigurations.keys():
|
||||
if WireguardConfigurations[i].configurationFileChanged():
|
||||
WireguardConfigurations[i] = WireguardConfiguration(i)
|
||||
else:
|
||||
WireguardConfigurations[i] = WireguardConfiguration(i)
|
||||
except WireguardConfiguration.InvalidConfigurationFileException as e:
|
||||
print(f"{i} have an invalid configuration file.")
|
||||
return configurations
|
||||
|
||||
|
||||
|
||||
def _checkIPWithRange(ip):
|
||||
@@ -1329,8 +1369,7 @@ def _generatePrivateKey() -> [bool, str]:
|
||||
except subprocess.CalledProcessError:
|
||||
return False, None
|
||||
|
||||
|
||||
def _getWireguardConfigurationAvailableIP(configName: str) -> tuple[bool, list[str]] | tuple[bool, None]:
|
||||
def _getWireguardConfigurationAvailableIP(configName: str, all: bool = False) -> tuple[bool, list[str]] | tuple[bool, None]:
|
||||
if configName not in WireguardConfigurations.keys():
|
||||
return False, None
|
||||
configuration = WireguardConfigurations[configName]
|
||||
@@ -1344,6 +1383,14 @@ def _getWireguardConfigurationAvailableIP(configName: str) -> tuple[bool, list[s
|
||||
for i in add:
|
||||
a, c = i.split('/')
|
||||
existedAddress.append(ipaddress.ip_address(a.replace(" ", "")))
|
||||
|
||||
for p in configuration.getRestrictedPeersList():
|
||||
if len(p.allowed_ip) > 0:
|
||||
add = p.allowed_ip.split(',')
|
||||
for i in add:
|
||||
a, c = i.split('/')
|
||||
existedAddress.append(ipaddress.ip_address(a.replace(" ", "")))
|
||||
|
||||
for i in address:
|
||||
addressSplit, cidr = i.split('/')
|
||||
existedAddress.append(ipaddress.ip_address(addressSplit.replace(" ", "")))
|
||||
@@ -1354,6 +1401,7 @@ def _getWireguardConfigurationAvailableIP(configName: str) -> tuple[bool, list[s
|
||||
if h not in existedAddress:
|
||||
availableAddress.append(ipaddress.ip_network(h).compressed)
|
||||
count += 1
|
||||
if not all:
|
||||
if network.version == 6 and count > 255:
|
||||
break
|
||||
return True, availableAddress
|
||||
@@ -1365,6 +1413,17 @@ sqldb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard.db')
|
||||
sqldb.row_factory = sqlite3.Row
|
||||
cursor = sqldb.cursor()
|
||||
|
||||
def sqlSelect(statement: str, paramters: tuple = ()) -> sqlite3.Cursor:
|
||||
with sqldb:
|
||||
cursor = sqldb.cursor()
|
||||
return cursor.execute(statement, paramters)
|
||||
|
||||
def sqlUpdate(statement: str, paramters: tuple = ()) -> sqlite3.Cursor:
|
||||
with sqldb:
|
||||
cursor = sqldb.cursor()
|
||||
cursor.execute(statement, paramters)
|
||||
sqldb.commit()
|
||||
|
||||
DashboardConfig = DashboardConfig()
|
||||
_, APP_PREFIX = DashboardConfig.GetConfig("Server", "app_prefix")
|
||||
cors = CORS(app, resources={rf"{APP_PREFIX}/api/*": {
|
||||
@@ -1419,6 +1478,7 @@ def auth_req():
|
||||
and f"{(APP_PREFIX if len(APP_PREFIX) > 0 else '')}" != request.path)
|
||||
and "validateAuthentication" not in request.path and "authenticate" not in request.path
|
||||
and "getDashboardConfiguration" not in request.path and "getDashboardTheme" not in request.path
|
||||
and "getDashboardVersion" not in request.path
|
||||
and "sharePeer/get" not in request.path
|
||||
and "isTotpEnabled" not in request.path
|
||||
):
|
||||
@@ -1489,7 +1549,7 @@ def API_SignOut():
|
||||
|
||||
@app.route(f'{APP_PREFIX}/api/getWireguardConfigurations', methods=["GET"])
|
||||
def API_getWireguardConfigurations():
|
||||
# WireguardConfigurations = _getConfigurationList()
|
||||
_getConfigurationList()
|
||||
return ResponseObject(data=[wc for wc in WireguardConfigurations.values()])
|
||||
|
||||
|
||||
@@ -1751,10 +1811,13 @@ def API_addPeers(configName):
|
||||
return ResponseObject(False, "Please fill in all required box.")
|
||||
if not config.getStatus():
|
||||
config.toggleConfiguration()
|
||||
|
||||
availableIps = _getWireguardConfigurationAvailableIP(configName)
|
||||
|
||||
if bulkAdd:
|
||||
if bulkAddAmount < 1:
|
||||
return ResponseObject(False, "Please specify amount of peers you want to add")
|
||||
availableIps = _getWireguardConfigurationAvailableIP(configName)
|
||||
|
||||
if not availableIps[0]:
|
||||
return ResponseObject(False, "No more available IP can assign")
|
||||
if bulkAddAmount > len(availableIps[1]):
|
||||
@@ -1788,17 +1851,12 @@ def API_addPeers(configName):
|
||||
return ResponseObject(False, f"This peer already exist.")
|
||||
name = data['name']
|
||||
private_key = data['private_key']
|
||||
config.addPeers([{"id": public_key, "allowed_ip": ''.join(allowed_ips)}])
|
||||
# subprocess.check_output(
|
||||
# f"wg set {config.Name} peer {public_key} allowed-ips {''.join(allowed_ips)}",
|
||||
# shell=True, stderr=subprocess.STDOUT)
|
||||
# if len(preshared_key) > 0:
|
||||
# subprocess.check_output(
|
||||
# f"wg set {config.Name} peer {public_key} preshared-key {preshared_key}",
|
||||
# shell=True, stderr=subprocess.STDOUT)
|
||||
# subprocess.check_output(
|
||||
# f"wg-quick save {config.Name}", shell=True, stderr=subprocess.STDOUT)
|
||||
# config.getPeersList()
|
||||
|
||||
for i in allowed_ips:
|
||||
if i not in availableIps[1]:
|
||||
return ResponseObject(False, f"This IP is not available: {i}")
|
||||
|
||||
config.addPeers([{"id": public_key, "allowed_ip": ','.join(allowed_ips)}])
|
||||
found, peer = config.searchPeer(public_key)
|
||||
if found:
|
||||
return peer.updatePeer(name, private_key, preshared_key, dns_addresses, ",".join(allowed_ips),
|
||||
@@ -1857,6 +1915,10 @@ def API_getConfigurationInfo():
|
||||
def API_getDashboardTheme():
|
||||
return ResponseObject(data=DashboardConfig.GetConfig("Server", "dashboard_theme")[1])
|
||||
|
||||
@app.route(f'{APP_PREFIX}/api/getDashboardVersion')
|
||||
def API_getDashboardVersion():
|
||||
return ResponseObject(data=DashboardConfig.GetConfig("Server", "version")[1])
|
||||
|
||||
|
||||
@app.route(f'{APP_PREFIX}/api/savePeerScheduleJob/', methods=["POST"])
|
||||
def API_savePeerScheduleJob():
|
||||
@@ -2006,8 +2068,7 @@ def API_traceroute_execute():
|
||||
|
||||
@app.route(f'{APP_PREFIX}/api/getDashboardUpdate')
|
||||
def API_getDashboardUpdate():
|
||||
import urllib.request as req;
|
||||
|
||||
import urllib.request as req
|
||||
try:
|
||||
r = req.urlopen("https://api.github.com/repos/donaldzou/WGDashboard/releases/latest", timeout=5).read()
|
||||
data = dict(json.loads(r))
|
||||
@@ -2020,8 +2081,8 @@ def API_getDashboardUpdate():
|
||||
return ResponseObject(message="You're on the latest version")
|
||||
return ResponseObject(False)
|
||||
|
||||
except urllib.error.HTTPError as e:
|
||||
return ResponseObject(False, f"Request to GitHub API failed. Returned a {e.code} status.")
|
||||
except urllib.error.HTTPError and urllib.error.URLError as e:
|
||||
return ResponseObject(False, f"Request to GitHub API failed.")
|
||||
|
||||
'''
|
||||
Sign Up
|
||||
@@ -2102,6 +2163,7 @@ def backGroundThread():
|
||||
c.getPeersLatestHandshake()
|
||||
c.getPeersEndpoint()
|
||||
c.getPeersList()
|
||||
c.getRestrictedPeersList()
|
||||
except Exception as e:
|
||||
print(f"[WGDashboard] Background Thread #1 Error: {str(e)}", flush=True)
|
||||
time.sleep(10)
|
||||
@@ -2131,7 +2193,7 @@ _, WG_CONF_PATH = DashboardConfig.GetConfig("Server", "wg_conf_path")
|
||||
|
||||
|
||||
WireguardConfigurations: dict[str, WireguardConfiguration] = {}
|
||||
WireguardConfigurations = _getConfigurationList()
|
||||
_getConfigurationList()
|
||||
|
||||
def startThreads():
|
||||
bgThread = threading.Thread(target=backGroundThread)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/bin/bash
|
||||
echo "Starting the WireGuard Dashboard Docker container."
|
||||
|
||||
clean_up() {
|
||||
# Cleaning out previous data such as the .pid file and starting the WireGuard Dashboard. Making sure to use the python venv.
|
||||
echo "Looking for remains of previous instances..."
|
||||
if [ -f "/opt/wireguarddashboard/app/src/gunicorn.pid" ]; then
|
||||
echo "Found old .pid file, removing."
|
||||
rm /opt/wireguarddashboard/app/src/gunicorn.pid
|
||||
else
|
||||
echo "No remains found, continuing."
|
||||
fi
|
||||
}
|
||||
ensure_blocking() {
|
||||
sleep 1s
|
||||
echo "Ensuring container continuation."
|
||||
|
||||
# This function checks if the latest error log is created and tails it for docker logs uses.
|
||||
if find "/opt/wireguarddashboard/src/log" -mindepth 1 -maxdepth 1 -type f | read -r; then
|
||||
latestErrLog=$(find /opt/wireguarddashboard/src/log -name "error_*.log" | head -n 1)
|
||||
latestAccLog=$(find /opt/wireguarddashboard/src/log -name "access_*.log" | head -n 1)
|
||||
tail -f "${latestErrLog}" "${latestAccLog}"
|
||||
fi
|
||||
|
||||
# Blocking command in case of erroring. So the container does not quit.
|
||||
sleep infinity
|
||||
}
|
||||
|
||||
{ date; clean_up; printf "\n\n"; } >> ./log/install.txt
|
||||
|
||||
chmod u+x /opt/wireguarddashboard/src/wgd.sh
|
||||
/opt/wireguarddashboard/src/wgd.sh install
|
||||
/opt/wireguarddashboard/src/wgd.sh docker_start
|
||||
ensure_blocking
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
WIREGUARD_INTERFACE=ADMINS
|
||||
WIREGUARD_LAN=10.0.0.1/24
|
||||
MASQUERADE_INTERFACE=eth0
|
||||
|
||||
CHAIN_NAME="WIREGUARD_$WIREGUARD_INTERFACE"
|
||||
|
||||
iptables -t nat -D POSTROUTING -o $MASQUERADE_INTERFACE -j MASQUERADE -s $WIREGUARD_LAN
|
||||
|
||||
# Remove and delete the WIREGUARD_wg0 chain
|
||||
iptables -D FORWARD -j $CHAIN_NAME
|
||||
iptables -F $CHAIN_NAME
|
||||
iptables -X $CHAIN_NAME
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
WIREGUARD_INTERFACE=ADMINS
|
||||
WIREGUARD_LAN=10.0.0.1/24
|
||||
MASQUERADE_INTERFACE=eth0
|
||||
|
||||
iptables -t nat -I POSTROUTING -o $MASQUERADE_INTERFACE -j MASQUERADE -s $WIREGUARD_LAN
|
||||
|
||||
# Add a WIREGUARD_wg0 chain to the FORWARD chain
|
||||
CHAIN_NAME="WIREGUARD_$WIREGUARD_INTERFACE"
|
||||
iptables -N $CHAIN_NAME
|
||||
iptables -A FORWARD -j $CHAIN_NAME
|
||||
|
||||
# Accept related or established traffic
|
||||
iptables -A $CHAIN_NAME -o $WIREGUARD_INTERFACE -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
|
||||
|
||||
# Accept traffic from any Wireguard IP address connected to the Wireguard server
|
||||
iptables -A $CHAIN_NAME -s $WIREGUARD_LAN -i $WIREGUARD_INTERFACE -j ACCEPT
|
||||
|
||||
# Allow traffic to the local loopback interface
|
||||
iptables -A $CHAIN_NAME -o lo -j ACCEPT
|
||||
|
||||
# Drop everything else coming through the Wireguard interface
|
||||
iptables -A $CHAIN_NAME -i $WIREGUARD_INTERFACE -j DROP
|
||||
|
||||
# Return to FORWARD chain
|
||||
iptables -A $CHAIN_NAME -j RETURN
|
||||
BIN
Binary file not shown.
Binary file not shown.
Vendored
+4
-4
File diff suppressed because one or more lines are too long
Vendored
+20
-20
File diff suppressed because one or more lines are too long
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "app",
|
||||
"version": "4.0.0",
|
||||
"version": "4.0.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"build electron": "vite build && vite build --mode electron && cd ../../../../WGDashboard-Desktop && electron-builder",
|
||||
"build electron": "vite build && vite build --mode electron && cd ../../../../WGDashboard-Desktop && electron-builder --mac --win",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
+4
-4
@@ -36,8 +36,11 @@ export default {
|
||||
addAllowedIp(ip){
|
||||
if(this.store.checkCIDR(ip)){
|
||||
this.data.allowed_ips.push(ip);
|
||||
this.customAvailableIp = ''
|
||||
return true;
|
||||
}
|
||||
this.allowedIpFormatError = true;
|
||||
this.dashboardStore.newMessage('WGDashboard', 'Allowed IP is invalid', 'danger')
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -80,10 +83,7 @@ export default {
|
||||
:disabled="bulk">
|
||||
<button class="btn btn-outline-success btn-sm rounded-end-3"
|
||||
:disabled="bulk || !this.customAvailableIp"
|
||||
@click="this.addAllowedIp(this.customAvailableIp)
|
||||
? this.customAvailableIp = '' :
|
||||
this.allowedIpFormatError = true;
|
||||
this.dashboardStore.newMessage('WGDashboard', 'Allowed IP is invalid', 'danger')"
|
||||
@click="this.addAllowedIp(this.customAvailableIp)"
|
||||
type="button" id="button-addon2">
|
||||
<i class="bi bi-plus-lg"></i>
|
||||
</button>
|
||||
|
||||
+12
@@ -30,12 +30,24 @@ export default {
|
||||
this.data.private_key = this.keypair.privateKey;
|
||||
this.data.public_key = this.keypair.publicKey;
|
||||
},
|
||||
testKey(key){
|
||||
const reg = /^[A-Za-z0-9+/]{43}=?=?$/;
|
||||
return reg.test(key)
|
||||
},
|
||||
checkMatching(){
|
||||
try{
|
||||
if(this.keypair.privateKey){
|
||||
if(this.testKey(this.keypair.privateKey)){
|
||||
this.keypair.publicKey = window.wireguard.generatePublicKey(this.keypair.privateKey)
|
||||
if (window.wireguard.generatePublicKey(this.keypair.privateKey)
|
||||
!== this.keypair.publicKey){
|
||||
this.error = true;
|
||||
this.dashboardStore.newMessage("WGDashboard", "Private Key and Public Key does not match.", "danger");
|
||||
}else{
|
||||
this.data.private_key = this.keypair.privateKey
|
||||
this.data.public_key = this.keypair.publicKey
|
||||
}
|
||||
}
|
||||
}
|
||||
}catch (e){
|
||||
this.error = true;
|
||||
|
||||
@@ -200,7 +200,8 @@ export default {
|
||||
})
|
||||
this.loading = false;
|
||||
if (this.configurationPeers.length > 0){
|
||||
const sent = this.configurationPeers.map(x => x.total_sent + x.cumu_sent).reduce((x,y) => x + y).toFixed(4);
|
||||
const sent = this.configurationPeers.map(x => x.total_sent + x.cumu_sent)
|
||||
.reduce((x,y) => x + y).toFixed(4);
|
||||
const receive = this.configurationPeers.map(x => x.total_receive + x.cumu_receive).reduce((x,y) => x + y).toFixed(4);
|
||||
if (
|
||||
this.historyDataSentDifference[this.historyDataSentDifference.length - 1] !== sent
|
||||
@@ -259,13 +260,13 @@ export default {
|
||||
connectedPeers: this.configurationPeers.filter(x => x.status === "running").length,
|
||||
totalUsage: this.configurationPeers.length > 0 ?
|
||||
this.configurationPeers.filter(x => !x.restricted)
|
||||
.map(x => x.total_data + x.cumu_data).reduce((a, b) => a + b).toFixed(4) : 0,
|
||||
.map(x => x.total_data + x.cumu_data).reduce((a, b) => a + b, 0).toFixed(4) : 0,
|
||||
totalReceive: this.configurationPeers.length > 0 ?
|
||||
this.configurationPeers.filter(x => !x.restricted)
|
||||
.map(x => x.total_receive + x.cumu_receive).reduce((a, b) => a + b).toFixed(4) : 0,
|
||||
.map(x => x.total_receive + x.cumu_receive).reduce((a, b) => a + b, 0).toFixed(4) : 0,
|
||||
totalSent: this.configurationPeers.length > 0 ?
|
||||
this.configurationPeers.filter(x => !x.restricted)
|
||||
.map(x => x.total_sent + x.cumu_sent).reduce((a, b) => a + b).toFixed(4) : 0
|
||||
.map(x => x.total_sent + x.cumu_sent).reduce((a, b) => a + b, 0).toFixed(4) : 0
|
||||
}
|
||||
|
||||
return k
|
||||
|
||||
@@ -11,16 +11,22 @@ export default {
|
||||
const store = DashboardConfigurationStore()
|
||||
let theme = "dark"
|
||||
let totpEnabled = false;
|
||||
let version = undefined;
|
||||
if (!store.IsElectronApp){
|
||||
await fetchGet("/api/getDashboardTheme", {}, (res) => {
|
||||
await Promise.all([
|
||||
fetchGet("/api/getDashboardTheme", {}, (res) => {
|
||||
theme = res.data
|
||||
});
|
||||
await fetchGet("/api/isTotpEnabled", {}, (res) => {
|
||||
}),
|
||||
fetchGet("/api/isTotpEnabled", {}, (res) => {
|
||||
totpEnabled = res.data
|
||||
});
|
||||
}),
|
||||
fetchGet("/api/getDashboardVersion", {}, (res) => {
|
||||
version = res.data
|
||||
})
|
||||
]);
|
||||
}
|
||||
store.removeActiveCrossServer();
|
||||
return {store, theme, totpEnabled}
|
||||
return {store, theme, totpEnabled, version}
|
||||
},
|
||||
data(){
|
||||
return {
|
||||
@@ -146,7 +152,7 @@ export default {
|
||||
</div>
|
||||
</div>
|
||||
<small class="text-muted pb-3 d-block w-100 text-center mt-3">
|
||||
WGDashboard v4.0 | Developed with ❤️ by
|
||||
WGDashboard {{ this.version }} | Developed with ❤️ by
|
||||
<a href="https://github.com/donaldzou" target="_blank"><strong>Donald Zou</strong></a>
|
||||
</small>
|
||||
<div class="messageCentre text-body position-absolute end-0 m-3">
|
||||
|
||||
+80
-22
@@ -2,7 +2,7 @@
|
||||
|
||||
# wgd.sh - Copyright(C) 2024 Donald Zou [https://github.com/donaldzou]
|
||||
# Under Apache-2.0 License
|
||||
trap "kill $TOP_PID"
|
||||
#trap "kill $TOP_PID"
|
||||
export TOP_PID=$$
|
||||
|
||||
app_name="dashboard.py"
|
||||
@@ -65,8 +65,6 @@ _determineOS(){
|
||||
OS=$ID
|
||||
elif [ -f /etc/redhat-release ]; then
|
||||
OS="redhat"
|
||||
# elif [ -f /etc/arch-release ]; then
|
||||
# OS="arch"
|
||||
else
|
||||
printf "[WGDashboard] %s Sorry, your OS is not supported. Currently the install script only support Debian-based, Red Hat-based OS." "$heavy_crossmark"
|
||||
printf "%s\n" "$helpMsg"
|
||||
@@ -87,6 +85,9 @@ _installPython(){
|
||||
{ sudo yum install -y python3 net-tools ; printf "\n\n"; } >> ./log/install.txt
|
||||
fi
|
||||
;;
|
||||
alpine)
|
||||
{ apk update; apk add python3 net-tools; printf "\n\n"; } &>> ./log/install.txt
|
||||
;;
|
||||
esac
|
||||
|
||||
if ! python3 --version > /dev/null 2>&1
|
||||
@@ -112,6 +113,9 @@ _installPythonVenv(){
|
||||
{ sudo yum install -y python3-virtualenv; printf "\n\n"; } >> ./log/install.txt
|
||||
fi
|
||||
;;
|
||||
alpine)
|
||||
{ apk add python3 py3-virtualenv; printf "\n\n"; } &>> ./log/install.txt
|
||||
;;
|
||||
*)
|
||||
printf "[WGDashboard] %s Sorry, your OS is not supported. Currently the install script only support Debian-based, Red Hat-based OS.\n" "$heavy_crossmark"
|
||||
printf "%s\n" "$helpMsg"
|
||||
@@ -123,18 +127,6 @@ _installPythonVenv(){
|
||||
ubuntu|debian)
|
||||
{ sudo apt-get update; sudo apt-get install ${pythonExecutable}-venv; } &>> ./log/install.txt
|
||||
;;
|
||||
# centos|fedora|redhat|rhel)
|
||||
# if command -v dnf &> /dev/null; then
|
||||
# { sudo dnf install -y ${pythonExecutable}-virtualenv; printf "\n\n"; } >> ./log/install.txt
|
||||
# else
|
||||
# { sudo yum install -y ${pythonExecutable}-virtualenv; printf "\n\n"; } >> ./log/install.txt
|
||||
# fi
|
||||
# ;;
|
||||
# *)
|
||||
# printf "[WGDashboard] %s Sorry, your OS is not supported. Currently the install script only support Debian-based, Red Hat-based OS.\n" "$heavy_crossmark"
|
||||
# printf "%s\n" "$helpMsg"
|
||||
# kill $TOP_PID
|
||||
# ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
@@ -166,6 +158,9 @@ _installPythonPip(){
|
||||
{ sudo dnf install -y ${pythonExecutable}-pip; printf "\n\n"; } >> ./log/install.txt
|
||||
fi
|
||||
;;
|
||||
alpine)
|
||||
{ apk add py3-pip; printf "\n\n"; } &>> ./log/install.txt
|
||||
;;
|
||||
*)
|
||||
printf "[WGDashboard] %s Sorry, your OS is not supported. Currently the install script only support Debian-based, Red Hat-based OS.\n" "$heavy_crossmark"
|
||||
printf "%s\n" "$helpMsg"
|
||||
@@ -247,9 +242,6 @@ install_wgd(){
|
||||
_installPythonVenv
|
||||
_installPythonPip
|
||||
|
||||
|
||||
|
||||
|
||||
if [ ! -d "db" ]
|
||||
then
|
||||
printf "[WGDashboard] Creating ./db folder\n"
|
||||
@@ -257,6 +249,7 @@ install_wgd(){
|
||||
fi
|
||||
_check_and_set_venv
|
||||
printf "[WGDashboard] Upgrading Python Package Manage (PIP)\n"
|
||||
{ date; python3 -m ensurepip --upgrade; printf "\n\n"; } >> ./log/install.txt
|
||||
{ date; python3 -m pip install --upgrade pip; printf "\n\n"; } >> ./log/install.txt
|
||||
printf "[WGDashboard] Installing latest Python dependencies\n"
|
||||
{ date; python3 -m pip install -r requirements.txt ; printf "\n\n"; } >> ./log/install.txt
|
||||
@@ -328,6 +321,54 @@ stop_wgd() {
|
||||
fi
|
||||
}
|
||||
|
||||
startwgd_docker() {
|
||||
_checkWireguard
|
||||
printf "[WGDashboard][Docker] WireGuard configuration started\n"
|
||||
{ date; start_core ; printf "\n\n"; } >> ./log/install.txt
|
||||
gunicorn_start
|
||||
}
|
||||
|
||||
start_core() {
|
||||
local iptable_dir="/opt/wireguarddashboard/src/iptable-rules"
|
||||
# Check if wg0.conf exists in /etc/wireguard
|
||||
if [[ ! -f /etc/wireguard/wg0.conf ]]; then
|
||||
echo "[WGDashboard][Docker] wg0.conf not found. Running generate configuration."
|
||||
newconf_wgd
|
||||
else
|
||||
echo "[WGDashboard][Docker] wg0.conf already exists. Skipping WireGuard configuration generation."
|
||||
fi
|
||||
# Re-assign config_files to ensure it includes any newly created configurations
|
||||
local config_files=$(find /etc/wireguard -type f -name "*.conf")
|
||||
|
||||
# Set file permissions
|
||||
find /etc/wireguard -type f -name "*.conf" -exec chmod 600 {} \;
|
||||
find "$iptable_dir" -type f -name "*.sh" -exec chmod +x {} \;
|
||||
|
||||
# Start WireGuard for each config file
|
||||
for file in $config_files; do
|
||||
config_name=$(basename "$file" ".conf")
|
||||
wg-quick up "$config_name"
|
||||
done
|
||||
}
|
||||
|
||||
|
||||
|
||||
newconf_wgd() {
|
||||
local wg_port_listen=$wg_port
|
||||
local wg_addr_range=$wg_net
|
||||
private_key=$(wg genkey)
|
||||
public_key=$(echo "$private_key" | wg pubkey)
|
||||
cat <<EOF >"/etc/wireguard/wg0.conf"
|
||||
[Interface]
|
||||
PrivateKey = $private_key
|
||||
Address = $wg_addr_range
|
||||
ListenPort = $wg_port_listen
|
||||
SaveConfig = true
|
||||
PostUp = /opt/wireguarddashboard/src/iptable-rules/postup.sh
|
||||
PreDown = /opt/wireguarddashboard/src/iptable-rules/postdown.sh
|
||||
EOF
|
||||
}
|
||||
|
||||
start_wgd_debug() {
|
||||
printf "%s\n" "$dashes"
|
||||
_checkWireguard
|
||||
@@ -337,7 +378,20 @@ start_wgd_debug() {
|
||||
}
|
||||
|
||||
update_wgd() {
|
||||
new_ver=$(venv_python -c "import json; import urllib.request; data = urllib.request.urlopen('https://api.github.com/repos/donaldzou/WGDashboard/releases/latest').read(); output = json.loads(data);print(output['tag_name'])")
|
||||
_determineOS
|
||||
if ! python3 --version > /dev/null 2>&1
|
||||
then
|
||||
printf "[WGDashboard] Python is not installed, trying to install now\n"
|
||||
_installPython
|
||||
else
|
||||
printf "[WGDashboard] %s Python is installed\n" "$heavy_checkmark"
|
||||
fi
|
||||
|
||||
_checkPythonVersion
|
||||
_installPythonVenv
|
||||
_installPythonPip
|
||||
|
||||
new_ver=$($venv_python -c "import json; import urllib.request; data = urllib.request.urlopen('https://api.github.com/repos/donaldzou/WGDashboard/releases/latest').read(); output = json.loads(data);print(output['tag_name'])")
|
||||
printf "%s\n" "$dashes"
|
||||
printf "[WGDashboard] Are you sure you want to update to the %s? (Y/N): " "$new_ver"
|
||||
read up
|
||||
@@ -356,7 +410,7 @@ update_wgd() {
|
||||
rm wgd.sh.old
|
||||
else
|
||||
printf "%s\n" "$dashes"
|
||||
printf "| Update Canceled. |\n"
|
||||
printf "[WGDashboard] Update Canceled.\n"
|
||||
printf "%s\n" "$dashes"
|
||||
fi
|
||||
}
|
||||
@@ -373,6 +427,10 @@ if [ "$#" != 1 ];
|
||||
else
|
||||
start_wgd
|
||||
fi
|
||||
elif [ "$1" = "docker_start" ]; then
|
||||
printf "%s\n" "$dashes"
|
||||
startwgd_docker
|
||||
printf "%s\n" "$dashes"
|
||||
elif [ "$1" = "stop" ]; then
|
||||
if check_wgd_status; then
|
||||
printf "%s\n" "$dashes"
|
||||
@@ -394,7 +452,7 @@ if [ "$#" != 1 ];
|
||||
if check_wgd_status; then
|
||||
printf "%s\n" "$dashes"
|
||||
stop_wgd
|
||||
printf "| WGDashboard is stopped. |\n"
|
||||
printf "[WGDashboard] WGDashboard is stopped.\n"
|
||||
sleep 4
|
||||
start_wgd
|
||||
else
|
||||
@@ -402,7 +460,7 @@ if [ "$#" != 1 ];
|
||||
fi
|
||||
elif [ "$1" = "debug" ]; then
|
||||
if check_wgd_status; then
|
||||
printf "| WGDashboard is already running. |\n"
|
||||
printf "[WGDashboard] WGDashboard is already running.\n"
|
||||
else
|
||||
start_wgd_debug
|
||||
fi
|
||||
|
||||
Reference in New Issue
Block a user