Compare commits

..

6 Commits

4 changed files with 237 additions and 94 deletions

1
.gitignore vendored
View File

@ -23,5 +23,4 @@ downloads/
test/ test/
tmp/ tmp/
var/ var/
*.conf
*.log *.log

View File

@ -63,7 +63,7 @@ ____
## `wg-client-management`.sh ## `wg-client-management`.sh
**Description:** **Description:**
> Creating or deleting client config for wireguard and sending config and info to email. > Creating or deleting client config for wireguard and sending config and info to email/telegram.
**Dependencies:** **Dependencies:**
> >
@ -73,6 +73,7 @@ ____
> * [grepcidr](https://github.com/ryantig/grepcidr) (tested version 2.0 on [Debian GNU/Linux 11](http://ftp.debian.org/debian/dists/bullseye/)) > * [grepcidr](https://github.com/ryantig/grepcidr) (tested version 2.0 on [Debian GNU/Linux 11](http://ftp.debian.org/debian/dists/bullseye/))
> * [Python 3](https://www.python.org/downloads/) (tested version 3.9.5 on [Debian GNU/Linux 11](http://ftp.debian.org/debian/dists/bullseye/)) > * [Python 3](https://www.python.org/downloads/) (tested version 3.9.5 on [Debian GNU/Linux 11](http://ftp.debian.org/debian/dists/bullseye/))
> * existing [/usr/local/bin/sendmail.py](https://git.hmp.today/pavel.muhortov/utils#sendmail-py) > * existing [/usr/local/bin/sendmail.py](https://git.hmp.today/pavel.muhortov/utils#sendmail-py)
> * [curl](https://curl.se/download.html) (tested version 7.74.0 on [Debian GNU/Linux 11](http://ftp.debian.org/debian/dists/bullseye/))
| POSITION | PARAMETERS | DESCRIPTION | DEFAULT | | POSITION | PARAMETERS | DESCRIPTION | DEFAULT |
|-----------|--------------|------------------------|---------------| |-----------|--------------|------------------------|---------------|
@ -80,7 +81,8 @@ ____
| 2 |**add\|del**|add or delete client config|**REQUIRED**| | 2 |**add\|del**|add or delete client config|**REQUIRED**|
| 3 |**\<username\>**|client username|**REQUIRED**| | 3 |**\<username\>**|client username|**REQUIRED**|
| 4 |**\<address\>**|client ip address|**REQUIRED**| | 4 |**\<address\>**|client ip address|**REQUIRED**|
| 5 |**[-f]**,**[--force]**|service will restart after add\|del username|| | 5 |**\<additional\>**|client description||
| 6 |**[-f]**,**[--force]**|service will restart after add\|del username||
Example usage: Example usage:
@ -107,6 +109,22 @@ sudo chmod +x /etc/wireguard/wg-client-management.sh
sudo mkdir /var/log/wireguard sudo mkdir /var/log/wireguard
``` ```
```bash
# edit wg-client-management.conf
sudo tee /etc/wireguard/wg-client-management.conf > /dev/null <<'EOF'
# sendmail configuration
from=user@host.zone
pass=password
dest=user@host.zone
smtp=smtp.host.zone
port=587
# telegram configuration
API_KEY=YOURAPIKEY
CHAT_ID=-100123456789
THRD_ID=123
EOF
```
```bash ```bash
# create link # create link
ln -s /etc/wireguard/wg-client-management.sh ./wg ln -s /etc/wireguard/wg-client-management.sh ./wg
@ -124,7 +142,7 @@ sudo ./wg wg0 del username address -f
```bash ```bash
# check journal # check journal
tail -f /var/log/wireguard/wg.log tail -f /var/log/wireguard/wg-client-management.log
``` ```
____ ____

10
wg-client-management.conf Normal file
View File

@ -0,0 +1,10 @@
# sendmail configuration
from=user@host.zone
pass=password
dest=user@host.zone
smtp=smtp.host.zone
port=587
# telegram configuration
API_KEY=YOURAPIKEY
CHAT_ID=-100123456789
THRD_ID=123

View File

@ -14,9 +14,11 @@
# - existing /usr/local/bin/sendmail.py # - existing /usr/local/bin/sendmail.py
# #
# PARAMETERS: # PARAMETERS:
# 1: "add|del" - add or delete client config # 1: interface - define wireguard interface
# 2: username - client username # 2: "add|del" - add or delete client config
# 3: address - client ip address # 3: username - client username
# 4: address - client ip address
# 5: additional - client description
# -f|--force - service will restart after username add|del # -f|--force - service will restart after username add|del
# #
# FUNCTIONS: # FUNCTIONS:
@ -30,7 +32,7 @@
# 1: message to print and logging # 1: message to print and logging
####################################### #######################################
addtologs() { addtologs() {
echo "$(date +'%Y.%m.%d-%H:%M:%S') $1" | tee -a "${logs}" printf "%s\n" "$(date +'%Y.%m.%d-%H:%M:%S') $1" | tee -a "${logs}"
} }
####################################### #######################################
@ -42,11 +44,11 @@ addtologs() {
####################################### #######################################
execquite() { execquite() {
addtologs "execution time is $(($(date +%s)-time)) seconds, exit" addtologs "execution time is $(($(date +%s)-time)) seconds, exit"
exit exit "${1}"
} }
####################################### #######################################
# Error exit procedure # Error exit procedure.
# Globals: # Globals:
# None # None
# Arguments: # Arguments:
@ -54,7 +56,35 @@ execquite() {
####################################### #######################################
execerror() { execerror() {
addtologs "error: $1" addtologs "error: $1"
execquite execquite 1
}
#######################################
# Parsing config file and creating global vars.
# Globals:
# None
# Arguments:
# None
#######################################
getconfig() {
logs=/var/log/wireguard/$(basename -s .sh "$(realpath "$0")").log
conf="$(dirname "$(realpath "$0")")/$(basename -s .sh "$(realpath "$0")").conf"
# wireguard configuration
serverpublkey=$(cat /etc/wireguard/pki/server-public.key)
servercfgname="/etc/wireguard/${iface_name}.conf"
clientpublkey=''
clientprivkey=''
clientconfdef="/etc/wireguard/client.conf.default"
# mail configuration
from="$(grep "from=" "${conf}" | cut -d= -f2)"
pass="$(grep "pass=" "${conf}" | cut -d= -f2)"
dest="$(grep "dest=" "${conf}" | cut -d= -f2)"
smtp="$(grep "smtp=" "${conf}" | cut -d= -f2)"
port="$(grep "port=" "${conf}" | cut -d= -f2)"
# telegram configuration
API_KEY=$(grep "API_KEY=" "${conf}" | cut -d= -f2)
CHAT_ID=$(grep "CHAT_ID=" "${conf}" | cut -d= -f2)
THRD_ID=$(grep "THRD_ID=" "${conf}" | cut -d= -f2)
} }
####################################### #######################################
@ -75,7 +105,7 @@ checkroot() {
} }
####################################### #######################################
# Send email notification about client connect # Send email notification about client config.
# Globals: # Globals:
# clientname # clientname
# faqprofile # faqprofile
@ -86,22 +116,54 @@ startsendmail() {
subj="[WG Settings] $(cat /etc/hostname): ${clientname} client profile" subj="[WG Settings] $(cat /etc/hostname): ${clientname} client profile"
( (
python3 /usr/local/bin/sendmail.py \ python3 /usr/local/bin/sendmail.py \
-u "$(grep "from=" /usr/local/bin/sendmail.config | cut -d= -f2)" \ -u "${from}" \
-p "$(grep "pass=" /usr/local/bin/sendmail.config | cut -d= -f2)" \ -p "${pass}" \
-d "$(grep "dest=" /usr/local/bin/sendmail.config | cut -d= -f2)" \ -d "${dest}" \
--smtp "$(grep "smtp=" /usr/local/bin/sendmail.config | cut -d= -f2)" \ --smtp "${smtp}" \
--port "$(grep "port=" /usr/local/bin/sendmail.config | cut -d= -f2)" \ --port "${port}" \
--stls "True" \ --stls "True" \
--subj "${subj}" \ --subj "${subj}" \
--text "${faqprofile}" \ --text "$(printf "%s\n" "${faqprofile}" | sed 's|`||g')" \
--file "/etc/wireguard/${clientname}.png,/etc/wireguard/${clientname}.conf" \ --file "/etc/wireguard/${clientname}.png,/etc/wireguard/${clientname}.conf"
>> /dev/null 2>&1 & ) > /dev/null 2>&1
) addtologs "sent mail with subject '${subj}' to ${dest}"
addtologs "sent mail with subject '${subj}'"
} }
####################################### #######################################
# Create wireguard client certificates # Send telegram notification about client config.
# Globals:
# clientname
# faqprofile
# ovpncfgdir
# API_KEY
# CHAT_ID
# THRD_ID
# Arguments:
# None
#######################################
# shellcheck disable=SC2030,2031
startsendtlgm() {
(
API_URL="https://api.telegram.org/bot${API_KEY}/sendMediaGroup?chat_id=${CHAT_ID}"
if grep -q "_" <<< "${CHAT_ID}"; then
THRD_ID=$(printf "%s\n" "${CHAT_ID}" | cut -d_ -f2)
CHAT_ID=$(printf "%s\n" "${CHAT_ID}" | cut -d_ -f1)
fi
if [ -n "${THRD_ID}" ]; then
API_URL="${API_URL}&message_thread_id=${THRD_ID}"
fi
curl "${API_URL}" \
-F "media=[{\"type\": \"document\", \"media\": \"attach://qr\", \"caption\": \"${faqprofile}\", \"parse_mode\": \"Markdown\"}, {\"type\": \"document\", \"media\": \"attach://cf\" }]" \
-F "qr=@/etc/wireguard/${clientname}.png" \
-F "cf=@/etc/wireguard/${clientname}.conf"
) > /dev/null 2>&1
addtologs "sent telegram media with ${clientname}.conf client profile to ${CHAT_ID}"
}
#######################################
# Create wireguard client peer.
# Globals: # Globals:
# clientname # clientname
# clientaddr # clientaddr
@ -109,24 +171,42 @@ startsendmail() {
# Arguments: # Arguments:
# None # None
####################################### #######################################
createcert() { createpeer() {
wg genkey | tee "/etc/wireguard/pki/${clientname}-private.key" | wg pubkey > "/etc/wireguard/pki/${clientname}-public.key" if [ -f "/etc/wireguard/pki/${clientname}-private.key" ]; then
addtologs "${clientname} private key exists, create skipped"
else
wg genkey | tee "/etc/wireguard/pki/${clientname}-private.key" > /dev/null 2>&1
addtologs "created ${clientname} new private key"
fi
wg pubkey > "/etc/wireguard/pki/${clientname}-public.key" < "/etc/wireguard/pki/${clientname}-private.key"
addtologs "created ${clientname} wireguard certificates"
clientpublkey=$(cat "/etc/wireguard/pki/${clientname}-public.key") clientpublkey=$(cat "/etc/wireguard/pki/${clientname}-public.key")
clientprivkey=$(cat "/etc/wireguard/pki/${clientname}-private.key") if grep -q -w "${clientpublkey}" "${servercfgname}"; then
addtologs "${clientname} peer configuration exists, create skipped"
else
wg set "${iface_name}" peer "${clientpublkey}" \ wg set "${iface_name}" peer "${clientpublkey}" \
allowed-ips "${clientaddr}/32" \ allowed-ips "${clientaddr}/32" \
persistent-keepalive 5 persistent-keepalive 5
{ {
echo -e "[Peer]" printf "%s\n" "[Peer]"
echo -e " PublicKey = ${clientpublkey}" printf "%s\n" " PublicKey = ${clientpublkey}"
echo -e " AllowedIPs = ${clientaddr}/32" printf "%s\n" " AllowedIPs = ${clientaddr}/32"
echo -e " PersistentKeepalive = 5" printf "%s\n" " PersistentKeepalive = 5"
} >> "${servercfgname}" } >> "${servercfgname}"
addtologs "created ${clientname} wireguard peer configuration"
fi
if ip ro | grep -q -w "${clientaddr}"; then
addtologs "${clientname} peer address exists in routes, create skipped"
else
ip -4 route add "${clientaddr}/32" dev "${iface_name}" ip -4 route add "${clientaddr}/32" dev "${iface_name}"
addtologs "created ${clientname} peer route"
fi
} }
####################################### #######################################
# Create wireguard client configuration # Create wireguard client configuration.
# Globals: # Globals:
# clientname # clientname
# clientaddr # clientaddr
@ -137,32 +217,38 @@ createcert() {
# None # None
####################################### #######################################
createconf() { createconf() {
clientprivkey=$(cat "/etc/wireguard/pki/${clientname}-private.key")
clientconf=$(cat "${clientconfdef}") clientconf=$(cat "${clientconfdef}")
clientconf=${clientconf//clientaddr/${clientaddr}} clientconf=${clientconf//clientaddr/${clientaddr}}
clientconf=${clientconf//clientprivkey/${clientprivkey}} clientconf=${clientconf//clientprivkey/${clientprivkey}}
clientconf=${clientconf//serverpublkey/${serverpublkey}} clientconf=${clientconf//serverpublkey/${serverpublkey}}
clientconf=${clientconf//clientaddrs/${clientaddr}} clientconf=${clientconf//clientaddrs/${clientaddr}}
printf "%s\n" "${clientconf}" > "/etc/wireguard/${clientname}.conf" printf "%s\n" "${clientconf}" > "/etc/wireguard/${clientname}.conf"
addtologs "created ${clientname} wireguard config file"
} }
####################################### #######################################
# Create wireguard client info, qr-code # Create wireguard client info, qr-code.
# Globals: # Globals:
# clientname # clientname
# Arguments: # Arguments:
# None # None
####################################### #######################################
createinfo() { createinfo() {
faqprofile=$(cat <<END faqprofile=$(printf "%s\n" \
WireGuard client: "WireGuard client:" \
https://www.wireguard.com/install/ "https://www.wireguard.com/install/" \
END "" \
) "${additional}" \
"" \
"Peer Address: \`$(grep 'Address' "/etc/wireguard/${clientname}.conf" | awk '{print $3}')\`" \
)
qrencode -o "/etc/wireguard/${clientname}.png" -t png -s 6 < "/etc/wireguard/${clientname}.conf" qrencode -o "/etc/wireguard/${clientname}.png" -t png -s 6 < "/etc/wireguard/${clientname}.conf"
addtologs "created ${clientname} qr code"
} }
####################################### #######################################
# Delete wireguard client certificates # Delete wireguard client peer.
# Globals: # Globals:
# clientname # clientname
# clientpublkey # clientpublkey
@ -170,12 +256,15 @@ END
# Arguments: # Arguments:
# None # None
####################################### #######################################
deletecert() { deletepeer() {
if [ -f "/etc/wireguard/pki/${clientname}-private.key" ]; then
wg pubkey > "/etc/wireguard/pki/${clientname}-public.key" < "/etc/wireguard/pki/${clientname}-private.key"
fi
if [ -f "/etc/wireguard/pki/${clientname}-public.key" ]; then
clientpublkey=$(cat "/etc/wireguard/pki/${clientname}-public.key") clientpublkey=$(cat "/etc/wireguard/pki/${clientname}-public.key")
clientprivkey=$(cat "/etc/wireguard/pki/${clientname}-private.key") if grep -q -w "${clientpublkey}" "${servercfgname}"; then
wg set "${iface_name}" peer "${clientpublkey}" remove wg set "${iface_name}" peer "${clientpublkey}" remove
rm -f "/etc/wireguard/pki/${clientname}-public.key"
rm -f "/etc/wireguard/pki/${clientname}-private.key"
# PublicKey = # PublicKey =
s2=$(grep -n "${clientpublkey}" "${servercfgname}" | cut -d":" -f1) s2=$(grep -n "${clientpublkey}" "${servercfgname}" | cut -d":" -f1)
# [Peer] # [Peer]
@ -185,29 +274,57 @@ deletecert() {
# PersistentKeepalive = # PersistentKeepalive =
s4=$(( s2 + 2 )) s4=$(( s2 + 2 ))
sed -i "${s1}d;${s2}d;${s3}d;${s4}d" "${servercfgname}" sed -i "${s1}d;${s2}d;${s3}d;${s4}d" "${servercfgname}"
addtologs "deleted ${clientname} wireguard peer configuration"
else
addtologs "${clientname} peer configuration does not exist, delete skipped"
fi
rm -f "/etc/wireguard/pki/${clientname}-public.key" > /dev/null 2>&1
rm -f "/etc/wireguard/pki/${clientname}-private.key" > /dev/null 2>&1
addtologs "deleted ${clientname} wireguard certificates"
else
addtologs "${clientname} certificates do not exist, delete skipped"
fi
if ip ro | grep -q -w "${clientaddr} dev ${iface_name}"; then
ip -4 route del "${clientaddr}/32" dev "${iface_name}" ip -4 route del "${clientaddr}/32" dev "${iface_name}"
addtologs "deleted ${clientname} peer route"
else
addtologs "${clientname} peer route does not exist, delete skipped"
fi
} }
####################################### #######################################
# Delete wireguard client configuration # Delete wireguard client configuration.
# Globals: # Globals:
# clientname # clientname
# Arguments: # Arguments:
# None # None
####################################### #######################################
deleteconf() { deleteconf() {
if [ -f "/etc/wireguard/${clientname}.conf" ]; then
rm -f "/etc/wireguard/${clientname}.conf" rm -f "/etc/wireguard/${clientname}.conf"
addtologs "deleted ${clientname} wireguard config file"
else
addtologs "${clientname} wireguard config does not exist, delete skipped"
fi
} }
####################################### #######################################
# Delete wireguard client qr-code # Delete wireguard client qr-code.
# Globals: # Globals:
# clientname # clientname
# Arguments: # Arguments:
# None # None
####################################### #######################################
deleteinfo() { deleteinfo() {
if [ -f "/etc/wireguard/${clientname}.png" ]; then
rm -f "/etc/wireguard/${clientname}.png" rm -f "/etc/wireguard/${clientname}.png"
addtologs "deleted ${clientname} qr code"
else
addtologs "${clientname} qr code does not exist, delete skipped"
fi
} }
# #
@ -218,6 +335,7 @@ iface_name=$1
clienttodo=$2 clienttodo=$2
clientname=$3 clientname=$3
clientaddr=$4 clientaddr=$4
additional=$5
resetforce=0 resetforce=0
for argument in "${@}"; do for argument in "${@}"; do
@ -233,61 +351,59 @@ done
time=$(date +%s) time=$(date +%s)
logs=/dev/null logs=/dev/null
if ! command -v qrencode &> /dev/null || \
! command -v /usr/local/bin/sendmail.py &> /dev/null || \
! command -v python3 &> /dev/null; then
execerror "Not found dependencies"
fi
# #
# MAIN: # MAIN:
# #
if checkroot; then if checkroot; then
serverpublkey=$(cat /etc/wireguard/pki/server-public.key) if ! command -v qrencode &> /dev/null || \
servercfgname="/etc/wireguard/${iface_name}.conf" ! command -v grepcidr &> /dev/null || \
clientpublkey='' ! command -v /usr/local/bin/sendmail.py &> /dev/null || \
clientprivkey='' ! command -v python3 &> /dev/null || \
clientconfdef="/etc/wireguard/client.conf.default" ! command -v curl &> /dev/null; then
logs=/var/log/wireguard/$(basename -s .sh "$0").log execerror "Not found dependencies"
fi
getconfig
if [ "${clienttodo}" == "add" ] && \ if [ "${clienttodo}" == "add" ] && \
[ -n "${iface_name}" ] && \
[ -n "${clientname}" ] && \ [ -n "${clientname}" ] && \
grepcidr "0.0.0.0/0" <(echo "${clientaddr}") >/dev/null; then grepcidr "0.0.0.0/0" <(echo "${clientaddr}") > /dev/null; then
if [ -f "/etc/wireguard/${clientname}.conf" ] || \ if ip ro | grep -q -w "${clientaddr}" || \
grep -q -w "${clientaddr}/32" "${servercfgname}"; then grep -q -w "${clientaddr}/32" "${servercfgname}"; then
execerror "wireguard config exist or address used, exit" addtologs "${clientaddr} address used, create peer, conf skipped"
else else
createcert && addtologs "created certificate for ${clientname}" createpeer
createconf && addtologs "created wg config file for ${clientname}" createconf
createinfo && addtologs "created info file for ${clientname}" fi
if [ ! -f "/etc/wireguard/${clientname}.conf" ]; then
addtologs "${clientname}.conf not found, create info skipped"
else
createinfo
startsendmail startsendmail
startsendtlgm
fi fi
if [ "${resetforce}" -eq 1 ];then if [ "${resetforce}" -eq 1 ];then
addtologs "restarting wg-quick@${iface_name}..." addtologs "restarting wg-quick@${iface_name}..."
systemctl restart "wg-quick@${iface_name}" systemctl restart "wg-quick@${iface_name}"
fi fi
elif [ "${clienttodo}" == "del" ] && \ elif [ "${clienttodo}" == "del" ] && \
[ -n "${iface_name}" ] && \
[ -n "${clientname}" ] && \ [ -n "${clientname}" ] && \
grepcidr "0.0.0.0/0" <(echo "${clientaddr}") >/dev/null; then grepcidr "0.0.0.0/0" <(echo "${clientaddr}") >/dev/null; then
if [ -f "/etc/wireguard/${clientname}.conf" ]; then deleteconf
deleteconf && addtologs "deleted wg config file for ${clientname}" deleteinfo
fi deletepeer
if [ -f "/etc/wireguard/${clientname}.png" ]; then
deleteinfo && addtologs "deleted info file for ${clientname}"
fi
if grep -q -w "${clientaddr}/32" "${servercfgname}"; then
deletecert && addtologs "deleted certificate for ${clientname}"
fi
if [ "${resetforce}" -eq 1 ];then if [ "${resetforce}" -eq 1 ];then
addtologs "restarting wg-quick@${iface_name}..." addtologs "restarting wg-quick@${iface_name}..."
systemctl "restart wg-quick@${iface_name}" systemctl "restart wg-quick@${iface_name}"
fi fi
else else
printf "%s\n" "Usage example: $0 'wg0' 'add' 'username(surname)' 'address(ww.xx.yy.zz) -f'" printf "%s\n" "Usage example: $0 'wg0' 'add' 'username(surname)' 'address(ww.xx.yy.zz)'"
printf "%s\n" "Usage example: $0 'wg0' 'add' 'username(surname)' 'address(ww.xx.yy.zz) 'additional client description'"
printf "%s\n" "Usage example: $0 'wg0' 'del' 'username(surname)' 'address(ww.xx.yy.zz)'" printf "%s\n" "Usage example: $0 'wg0' 'del' 'username(surname)' 'address(ww.xx.yy.zz)'"
printf "%s\n" "Usage example: $0 'wg0' 'del' 'username(surname)' 'address(ww.xx.yy.zz)' -f"
fi fi
else else
execerror "Restart this as root!" execerror "Restart this as root!"
fi fi
execquite execquite 0