Compare commits

..

No commits in common. "ebac39dc332ec0fe17de3a17df6cf94a7cbdc9a0" and "30087e906d3295d53e56d9bf71a9fbe936539217" have entirely different histories.

4 changed files with 94 additions and 237 deletions

1
.gitignore vendored
View File

@ -23,4 +23,5 @@ 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/telegram. > Creating or deleting client config for wireguard and sending config and info to email.
**Dependencies:** **Dependencies:**
> >
@ -73,7 +73,6 @@ ____
> * [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 |
|-----------|--------------|------------------------|---------------| |-----------|--------------|------------------------|---------------|
@ -81,8 +80,7 @@ ____
| 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 |**\<additional\>**|client description|| | 5 |**[-f]**,**[--force]**|service will restart after add\|del username||
| 6 |**[-f]**,**[--force]**|service will restart after add\|del username||
Example usage: Example usage:
@ -109,22 +107,6 @@ 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
@ -142,7 +124,7 @@ sudo ./wg wg0 del username address -f
```bash ```bash
# check journal # check journal
tail -f /var/log/wireguard/wg-client-management.log tail -f /var/log/wireguard/wg.log
``` ```
____ ____

View File

@ -1,10 +0,0 @@
# 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,11 +14,9 @@
# - existing /usr/local/bin/sendmail.py # - existing /usr/local/bin/sendmail.py
# #
# PARAMETERS: # PARAMETERS:
# 1: interface - define wireguard interface # 1: "add|del" - add or delete client config
# 2: "add|del" - add or delete client config # 2: username - client username
# 3: username - client username # 3: address - client ip address
# 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:
@ -32,7 +30,7 @@
# 1: message to print and logging # 1: message to print and logging
####################################### #######################################
addtologs() { addtologs() {
printf "%s\n" "$(date +'%Y.%m.%d-%H:%M:%S') $1" | tee -a "${logs}" echo "$(date +'%Y.%m.%d-%H:%M:%S') $1" | tee -a "${logs}"
} }
####################################### #######################################
@ -44,11 +42,11 @@ addtologs() {
####################################### #######################################
execquite() { execquite() {
addtologs "execution time is $(($(date +%s)-time)) seconds, exit" addtologs "execution time is $(($(date +%s)-time)) seconds, exit"
exit "${1}" exit
} }
####################################### #######################################
# Error exit procedure. # Error exit procedure
# Globals: # Globals:
# None # None
# Arguments: # Arguments:
@ -56,35 +54,7 @@ execquite() {
####################################### #######################################
execerror() { execerror() {
addtologs "error: $1" addtologs "error: $1"
execquite 1 execquite
}
#######################################
# 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)
} }
####################################### #######################################
@ -105,7 +75,7 @@ checkroot() {
} }
####################################### #######################################
# Send email notification about client config. # Send email notification about client connect
# Globals: # Globals:
# clientname # clientname
# faqprofile # faqprofile
@ -116,54 +86,22 @@ 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 "${from}" \ -u "$(grep "from=" /usr/local/bin/sendmail.config | cut -d= -f2)" \
-p "${pass}" \ -p "$(grep "pass=" /usr/local/bin/sendmail.config | cut -d= -f2)" \
-d "${dest}" \ -d "$(grep "dest=" /usr/local/bin/sendmail.config | cut -d= -f2)" \
--smtp "${smtp}" \ --smtp "$(grep "smtp=" /usr/local/bin/sendmail.config | cut -d= -f2)" \
--port "${port}" \ --port "$(grep "port=" /usr/local/bin/sendmail.config | cut -d= -f2)" \
--stls "True" \ --stls "True" \
--subj "${subj}" \ --subj "${subj}" \
--text "$(printf "%s\n" "${faqprofile}" | sed 's|`||g')" \ --text "${faqprofile}" \
--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}'"
} }
####################################### #######################################
# Send telegram notification about client config. # Create wireguard client certificates
# 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
@ -171,42 +109,24 @@ startsendtlgm() {
# Arguments: # Arguments:
# None # None
####################################### #######################################
createpeer() { createcert() {
if [ -f "/etc/wireguard/pki/${clientname}-private.key" ]; then wg genkey | tee "/etc/wireguard/pki/${clientname}-private.key" | wg pubkey > "/etc/wireguard/pki/${clientname}-public.key"
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")
if grep -q -w "${clientpublkey}" "${servercfgname}"; then clientprivkey=$(cat "/etc/wireguard/pki/${clientname}-private.key")
addtologs "${clientname} peer configuration exists, create skipped" wg set "${iface_name}" peer "${clientpublkey}" \
else allowed-ips "${clientaddr}/32" \
wg set "${iface_name}" peer "${clientpublkey}" \ persistent-keepalive 5
allowed-ips "${clientaddr}/32" \ {
persistent-keepalive 5 echo -e "[Peer]"
{ echo -e " PublicKey = ${clientpublkey}"
printf "%s\n" "[Peer]" echo -e " AllowedIPs = ${clientaddr}/32"
printf "%s\n" " PublicKey = ${clientpublkey}" echo -e " PersistentKeepalive = 5"
printf "%s\n" " AllowedIPs = ${clientaddr}/32" } >> "${servercfgname}"
printf "%s\n" " PersistentKeepalive = 5" ip -4 route add "${clientaddr}/32" dev "${iface_name}"
} >> "${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}"
addtologs "created ${clientname} peer route"
fi
} }
####################################### #######################################
# Create wireguard client configuration. # Create wireguard client configuration
# Globals: # Globals:
# clientname # clientname
# clientaddr # clientaddr
@ -217,38 +137,32 @@ createpeer() {
# 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=$(printf "%s\n" \ faqprofile=$(cat <<END
"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 peer. # Delete wireguard client certificates
# Globals: # Globals:
# clientname # clientname
# clientpublkey # clientpublkey
@ -256,75 +170,44 @@ createinfo() {
# Arguments: # Arguments:
# None # None
####################################### #######################################
deletepeer() { deletecert() {
if [ -f "/etc/wireguard/pki/${clientname}-private.key" ]; then clientpublkey=$(cat "/etc/wireguard/pki/${clientname}-public.key")
wg pubkey > "/etc/wireguard/pki/${clientname}-public.key" < "/etc/wireguard/pki/${clientname}-private.key" clientprivkey=$(cat "/etc/wireguard/pki/${clientname}-private.key")
fi wg set "${iface_name}" peer "${clientpublkey}" remove
rm -f "/etc/wireguard/pki/${clientname}-public.key"
if [ -f "/etc/wireguard/pki/${clientname}-public.key" ]; then rm -f "/etc/wireguard/pki/${clientname}-private.key"
clientpublkey=$(cat "/etc/wireguard/pki/${clientname}-public.key") # PublicKey =
if grep -q -w "${clientpublkey}" "${servercfgname}"; then s2=$(grep -n "${clientpublkey}" "${servercfgname}" | cut -d":" -f1)
wg set "${iface_name}" peer "${clientpublkey}" remove # [Peer]
# PublicKey = s1=$(( s2 - 1 ))
s2=$(grep -n "${clientpublkey}" "${servercfgname}" | cut -d":" -f1) # AllowedIPs =
# [Peer] s3=$(( s2 + 1 ))
s1=$(( s2 - 1 )) # PersistentKeepalive =
# AllowedIPs = s4=$(( s2 + 2 ))
s3=$(( s2 + 1 )) sed -i "${s1}d;${s2}d;${s3}d;${s4}d" "${servercfgname}"
# PersistentKeepalive = ip -4 route del "${clientaddr}/32" dev "${iface_name}"
s4=$(( s2 + 2 ))
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}"
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
} }
# #
@ -335,7 +218,6 @@ 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
@ -351,59 +233,61 @@ 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
if ! command -v qrencode &> /dev/null || \ serverpublkey=$(cat /etc/wireguard/pki/server-public.key)
! command -v grepcidr &> /dev/null || \ servercfgname="/etc/wireguard/${iface_name}.conf"
! command -v /usr/local/bin/sendmail.py &> /dev/null || \ clientpublkey=''
! command -v python3 &> /dev/null || \ clientprivkey=''
! command -v curl &> /dev/null; then clientconfdef="/etc/wireguard/client.conf.default"
execerror "Not found dependencies" logs=/var/log/wireguard/$(basename -s .sh "$0").log
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 ip ro | grep -q -w "${clientaddr}" || \ if [ -f "/etc/wireguard/${clientname}.conf" ] || \
grep -q -w "${clientaddr}/32" "${servercfgname}"; then grep -q -w "${clientaddr}/32" "${servercfgname}"; then
addtologs "${clientaddr} address used, create peer, conf skipped" execerror "wireguard config exist or address used, exit"
else else
createpeer createcert && addtologs "created certificate for ${clientname}"
createconf createconf && addtologs "created wg config file for ${clientname}"
fi createinfo && addtologs "created info file for ${clientname}"
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
deleteconf if [ -f "/etc/wireguard/${clientname}.conf" ]; then
deleteinfo deleteconf && addtologs "deleted wg config file for ${clientname}"
deletepeer fi
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)'" 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) '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 0 execquite