Compare commits

..

No commits in common. "1.3" and "main" have entirely different histories.
1.3 ... main

30 changed files with 76 additions and 3629 deletions

9
GenMac
View file

@ -1,9 +0,0 @@
#!/bin/bash
OUI_PREFIX="00:50:56"
echo -e "\nOUI Prefix: $OUI_PREFIX"
LAST_OCTETS=$(openssl rand -hex 3 | sed 's/\(..\)/\1:/g; s/.$//')
echo -e "Generated MAC: ${OUI_PREFIX}:${LAST_OCTETS}"

24
Gvpn
View file

@ -1,24 +0,0 @@
#!/bin/bash
unset VPN;
VPN=(
'Real;~/Nextcloud2/guydev/network/wireguard/real/users/002-Guy.conf'
'Ingt;~/Nextcloud2/guydev/network/wireguard/ingtegration/chateauguay/user/U-003-dana.conf'
)
unset Items;
for Item in "${VPN[@]}"
do
echo -e "Item is: $Item"
IFS=";" read -r Name Def <<< $Item
echo -e "
Name : $Name
Def : $Def
"
Items+="$Name\n"
done
echo -e "${Items[@]}"

73
LICENSE Normal file
View file

@ -0,0 +1,73 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2025 boig01
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

3
README.md Normal file
View file

@ -0,0 +1,3 @@
# network-scripts
Network Related Scripts

View file

@ -1,48 +0,0 @@
#!/bin/bash
#
# version 231012_1439
#
read -p "Enter VLAN Number (Ex: 16) : " VLAN
read -p "Enter Device Name (Ex: enp5s0) : " DEV
echo -e "
VLAN = $VLAN
Device = $DEV
"
if [ "$(nmcli con |grep br${VLAN}|wc -l)" -eq "0" ]
then
echo -e "** Adding bridge br${VLAN}..."
nmcli con add \
type bridge \
con-name br${VLAN} \
ifname br${VLAN} \
ipv4.method disabled \
ipv6.method ignore \
autoconnect yes
else
echo "** br${VLAN} found"
fi
echo -e "** Putting br${VLAN} in up state..."
nmcli con up "br${VLAN}"
echo -e "** Adding VLAN ${VLAN} to $DEV --> vlan-${DEV}.${VLAN} and then to br${VLAN}"
nmcli con add \
type vlan \
con-name vlan-${DEV}.${VLAN} \
ifname ${DEV}.${VLAN} \
dev ${DEV} \
id ${VLAN} \
ipv4.method disabled \
ipv6.method ignore \
master br${VLAN} \
autoconnect yes
echo -e "\n** All done."

View file

@ -1,141 +0,0 @@
#!/bin/bash
#
# https://github.com/AlexStragies/lsnetdev/blob/master/nettree.sh
#
DIRECTION="UP"
UTF=""
TREE=""
GV=""
which tree >/dev/null && TREE=1 || UTF=1
function usage() {
cat << USAGEEND
The script prints network devices hierarchy as a tree view.
Possible arguments:
-u prints tree bottom-up (default). Physical devices are roots of the tree.
-d prints tree top-down. Logical devices are roots of the tree.
-s X connect to host X via SSH to query information
-t Use 'tree' to print the tree by constructing a tree in TMP (default).
-G Print GraphViz Syntax graph, node and edge definitions.
-g Print GraphViz Syntax node and edge definitions only.
-l use UTF8 characters (default, if 'tree' is not installed).
USAGEEND
}
function print() {
local indent="$1"; shift
local firstrun=1; if [ "$1" = "1" ]; then firstrun=0; shift; fi
while [ -n "$1" ]; do
local D="${1# *}"
[ "$firstrun" = 1 -a -n "${devicesup[$D]}" ] && shift && continue;
echo -n "$indent ┗━ $D";
if [ -z "${devicesdown[$D]}" ]; then echo ; else
echo " ━┓";
print "$(echo \ \ $D\ \ \ | sed 's/./ /g')$indent" 1 ${devicesdown[$D]}
fi
shift;
done
}
function buildFolderTree() {
local firstrun=1; if [ "$1" = 1 ]; then firstrun=0; shift; fi
while [ -n "$1" ]; do
local D=${1# *}
[ "$firstrun" = 1 -a -n "${devicesup[$D]}" ] && shift && continue;
mkdir $D
if [ -n "${devicesdown[$D]}" ]; then
cd $D;
for P in ${devicesdown[$D]}; do buildFolderTree 1 "$P";done
cd ..
fi
shift;
done
}
function addRelation() {
local A="$1"
local B="$2"
local props="$3"
[ "$DIRECTION" = "UP" ] && C="$A" && A="$B" && B="$C"
conns["\"$A\" -- \"$B\""]="$props"
devicesdown[$A]="${devicesdown[$A]} $B"
devicesup[$B]="${devicesup[$B]} $A"
}
while [ ! -z "$1" ]; do
case "$1" in
-d) DIRECTION=DOWN ;;
-u) DIRECTION=UP ;;
-t) GV="";GVNE="";TREE=1 ;UTF="" ;;
-G) GV=1 ;GVNE=1 ;TREE="";UTF="" ;;
-g) GV="";GVNE=1 ;TREE="";UTF="" ;;
-l) GV="";GVNE="";TREE="";UTF=1 ;;
-s) PFX="ssh -M $2"
shift
;;
-h) usage ; exit 0 ;;
*) usage ; exit 1 ;;
esac
shift
done
declare -A devices
declare -A devicesup
declare -A devicesdown
declare -A conns
SCN="/sys/class/net/"
for CDEV in $($PFX find /sys/class/net/ ! -name lo -type l |sort); do
DCLASS="RJ45"
NDEV=$(basename $CDEV)
devices[$NDEV]=""
$PFX readlink $CDEV | grep -q devices/virtual && DCLASS="virtual"
$PFX [ -e $CDEV/bonding/ ] && DCLASS="bond"
$PFX [ -e $CDEV/phy80211/ ] && DCLASS="wireless"
$PFX [ -e $CDEV/dsa/ ] && DCLASS="dsa"
$PFX [ -e $CDEV/bridge/ ] && { DCLASS="bridge"
$PFX grep -q 1 $CDEV/bridge/vlan_filtering && DCLASS="switch"
}
$PFX grep -q 512 $CDEV/type && { DCLASS="ppp"
PNPP="/proc/net/pppoe"
$PFX [ -e $PNPP ] && P=$($PFX cat $PNPP | awk 'NR==2{print $3}')
[ -n "$P" ] && $PFX [ -e $SCN/$P ] && {
addRelation "$NDEV" "$P" 'label="PPPoE"'
}
}
for LOW in $($PFX find $CDEV/ -name 'lower_*'); do
LOW=${LOW#*_}
addRelation "$NDEV" "$LOW" 'label=""'
done
devices[$NDEV]="label=\"${NDEV}\""
devices[$NDEV]="${devices[$NDEV]}, class=\"${DCLASS}\""
done
[ -n "$GV" ] && {
echo 'graph iftree {'
}
[ -n "$GVNE" ] && {
for iDEV in "${!devices[@]}"; do
echo " \"${iDEV}\"["${devices[$iDEV]}"];"
done
for conn in "${!conns[@]}"; do
echo \ \ $conn[${conns[$conn]}]\;;
done
}
[ -n "$GV" ] && { echo '}'; }
if [ "$TREE" = "1" ]; then
TMPD=$(mktemp -qd)
cd $TMPD
buildFolderTree "${!devices[@]}";
tree --noreport *
find $TMPD -delete
fi
if [ "$UTF" = "1" ]; then
print "" "${!devices[@]}" | colrm 1 4
fi

View file

@ -1,9 +0,0 @@
#!/bin/bash
unset VPN;
VPN={
Real;~/Nextcloud2/guydev/network/wireguard/real/users/002-Guy.conf
Ingt;~/Nextcloud2/guydev/network/wireguard/ingtegration/chateauguay/user/U-003-dana.conf
}

View file

@ -1,136 +0,0 @@
#!/bin/bash
#
# AUTOWG written by Hamdi KADRI
# APACHE LICENSE version 2.0 applies
# This script is intended to create configurations for
# a point-to-point Wireguard connection between a server
# and a client (/30 network)
#
# Step zero: declare configurations as variables
servercfg="[Interface]
Address = <serverwgIP>
SaveConfig = true
ListenPort = <port>
PrivateKey = <server-privatekey>
[Peer]
PublicKey = <client-pubkey>
PresharedKey = <psk>
AllowedIPs = <clientwgIP>"
clientcfg="[Interface]
PrivateKey = <client-privatekey>
Address = <clientwgIP> <dnsconfiguration>
[Peer]
PublicKey = <server-pubkey>
PresharedKey = <psk>
AllowedIPs = <clientwgIP>
EndPoint = <serverIP>:<port>
PersistentKeepalive = 20"
postcfg="[Interface]
Address = <serverwgIP>
SaveConfig = true
ListenPort = <port>
PrivateKey = <server-privatekey>
PostUp = iptables -A FORWARD -i <wgintname> -j ACCEPT
PostUp = iptables -t nat -A POSTROUTING -o <srvinternetintname> -j MASQUERADE
PostDown = iptables -D FORWARD -i <wgintname> -j ACCEPT
PostDown = iptables -t nat -D POSTROUTING -o <srvinternetintname> -j MASQUERADE
[Peer]
PublicKey = <client-pubkey>
PresharedKey = <psk>
AllowedIPs = <clientwgIP>
"
# Step one: ask for some parameters (as an assistant)
# We need: point-to-point IPs, Server IP, port
echo "AutoWG requires some informations before generating your config"
echo "Please provide the next parameters."
echo "This script will not check if the IPs and netmask are valid!"
echo "Press Enter to continue.."
echo
read
read -p "Server IP for the Wireguard interface: " serverwgIP
read -p "Client IP for the Wireguard interface: " clientwgIP
read -p "Network Mask (in CIDR) for both server and client WG interfaces (example: /30): " netmask
read -p "Server Public IP address: " serverIP
read -p "Network Port for Wireguard communication: " port
read -p "Wireguard interface name? (for example wg0): " wgintname
read -p "Route all traffic to server via Wireguard? [y/N]: " internetaccess
if [[ "$internetaccess" =~ ^([yY][eE][sS]|[yY])$ ]]
then
clientcfg=$(echo "$clientcfg" | sed "s|AllowedIPs = <clientwgIP>|AllowedIPs = 0.0.0.0/0|g" )
read -p "Which server interface has internet access? " srvinternetintname
servercfg=$(echo "$postcfg" | sed "s|<wgintname>|${wgintname}|g" | sed "s|<srvinternetintname>|${srvinternetintname}|g" )
echo
RED='\033[0;31m'
NC='\033[0m' # No Color
printf "${RED}IMPORTANT:${NC} You need to enable IP Forwarding on the server\n"
echo "On Linux servers, uncomment the line \"net.ipv4.ip_forward=1\" in /etc/sysctl.conf"
echo "then run \"sysctl -p\""
echo
#### Experimental DNS support ####
read -p "Push DNS servers to client? [y/N]: " dns
if [[ "$dns" =~ ^([yY][eE][sS]|[yY])$ ]]
then
read -p "Enter dns servers IPs separated by spaces: " dnsservers
dnscfg="\nDNS = $dnsservers"
clientcfg=$(echo "$clientcfg" | sed "s|<dnsconfiguration>|$dnscfg|g" )
else
clientcfg=$(echo "$clientcfg" | sed "s|<dnsconfiguration>||g" )
fi
##################################
else
clientcfg=$(echo "$clientcfg" | sed "s|<dnsconfiguration>||g" )
fi
# Step two: generate keypairs
## Generate keypairs for machine 1 (client)
client_prvkey=$(wg genkey)
client_pubkey=$(echo $client_prvkey | wg pubkey)
## Generate keypairs for machine 2 (server)
server_prvkey=$(wg genkey)
server_pubkey=$(echo $server_prvkey | wg pubkey)
# New : generate PSK
psk=$(wg genpsk)
# Step three: generate configuration
serverconf=$(echo "$servercfg" | sed "s|<serverwgIP>|${serverwgIP}${netmask}|g" | \
sed "s|<port>|${port}|g" | sed "s|<server-privatekey>|${server_prvkey}|g" |\
sed "s|<client-pubkey>|${client_pubkey}|g" | sed "s|<clientwgIP>|${clientwgIP}|g" |\
sed "s|<psk>|${psk}|g" )
clientconf=$(echo "$clientcfg" | sed "s|<client-privatekey>|${client_prvkey}|g" | \
sed "s|<clientwgIP>|${clientwgIP}${netmask}|g" | sed "s|<server-pubkey>|${server_pubkey}|g" | \
sed "s|<serverIP>|${serverIP}|g" | sed "s|<port>|${port}|g" | sed "s|<psk>|${psk}|g" )
# Step four: display configuration for machine 1 (client)
echo
echo "** Client Side /etc/wireguard/${wgintname}.conf **"
echo "$clientconf"
echo
# Step five: display configuration for machine 2 (server)
echo
echo "** Server Side /etc/wireguard/${wgintname}.conf **"
echo "$serverconf"
echo
# Step Seven: Saving to a text file
#
echo "** Client Side /etc/wireguard/${wgintname}.conf **" > wireguard-conf.txt
echo "$clientconf" >> wireguard-conf.txt
echo >> wireguard-conf.txt
echo "** Server Side /etc/wireguard/${wgintname}.conf **" >> wireguard-conf.txt
echo "$serverconf" >> wireguard-conf.txt
echo >> wireguard-conf.txt

View file

@ -1,3 +0,0 @@
/interface wireguard peers
add allowed-address=192.168.61.1/32 disabled=no name="pcyves" interface=WG01 \
preshared-key="K/C9aXn6DJqjN0nHCygojPjY+B40S6EWKGAQRoo05O4=" public-key="IaUPgaro0xZSL5EFrOSttqScvN6GdwzJtV8YgmRAQzM="

View file

@ -1,13 +0,0 @@
[Interface]
PrivateKey = IGvOgupuIXaVgyLbboX4ASg2syfGuMxZnBb5vPpdu0E=
ListenPort = 51821
Address = 192.168.61.1/32
DNS = 1.1.1.1,8.8.8.8
[Peer]
PublicKey = /cMmECzL5y6qwn7t0b9jybw3rlo+M71eKqfbm0JgshE=
PresharedKey = K/C9aXn6DJqjN0nHCygojPjY+B40S6EWKGAQRoo05O4=
AllowedIPs = 0.0.0.0/0
Endpoint = 65.94.149.174:14233
PersistentKeepalive = 25

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

View file

@ -1,7 +0,0 @@
[hAP-AC2]
Rtr_Addr_Public=beec0baa227b.sn.mynetname.net
Rrt_Port=14233
Rtr_Interface=WG01
Rtr_Addr_Private=192.168.61.254
Rtr_CIDR_Mask=24
Rtr_PUB_KEY=/cMmECzL5y6qwn7t0b9jybw3rlo+M71eKqfbm0JgshE=

View file

@ -1,3 +0,0 @@
/ip address add address=172.14.40.004/32 comment=WG-CTG interface=wg-ctg
/interface wireguard peers add allowed-address=172.16.254.004/32 client-keepalive=10 disabled=no comment="2" \
interface=WG-Devices preshared-key="efrLuDEVeDNpj13qlIqbjCiKlPVxE8T+hLt+2gQHF40=" public-key="lRlZ5uUBQsCH4G259f+q2yKAH4rxc2y+KHDlHaksmwo="

View file

@ -1,405 +0,0 @@
#!/bin/bash
Version=241231-1054
debug=0
CORP="ingtegration-rb5009" # default value
ScriptName=$(basename "$0")
ScriptDir=$(dirname "0")
IniFile=${ScriptDir}/${ScriptName}.ini
BaseDir="/home/boig01/temp/wireguard"
((debug)) && echo -e "
ScriptDir = $ScriptDir
IniFile = $IniFile
"
NumUser=0
NameUser=""
NumRouter=0
NameRouter=""
Mode=0
BOLD=$( tput bold)
NORMAL=$( tput sgr0)
RESET=$( tput sgr0)
NC=$( tput sgr0) # No color
BOLD=$( tput bold)
BLACK=$( tput setaf 0)
RED=$( tput setaf 1)
GREEN=$( tput setaf 2)
YELLOW=$( tput setaf 3)
BLUE=$( tput setaf 4)
MAGENTA=$( tput setaf 5)
CYAN=$( tput setaf 6)
WHITE=$( tput setaf 7)
DEFAULT=$( tput setaf 9)
#---ini file parameters
unset PARAMS;
PARAMS=(
Endpoint_Rtr_Addr_Public
Endpoint_Rtr_Addr_Private
Endpoint_Rrt_Port
Endpoint_Rtr_PUB_KEY
Endpoint_Usr_Addr
Endpoint_Usr_Port
Endpoint_Usr_PUB_KEY
)
#========== INTERNAL FUNCTIONS ================================================
#---------- function Info -----------------------------------------------------
#
# With date / time prefix
#
Info()
{
printf "${GREEN}%s ${NC} %s\n" "$( date +%F_%T )" "$*"
}
#---------- function Message --------------------------------------------------
#
# Send to STDOUT
#
function Message()
{
printf "\n${GREEN}[i] ${BLUE}%s${NC}\n" "$*"
}
#---------- ip2int ------------------------------------------------------------
#
function ip2int()
{
local a b c d
{ IFS=. read a b c d; } <<< $1
echo $(((((((a << 8) | b) << 8) | c) << 8) | d))
}
#---------- int2ip ------------------------------------------------------------
#
function int2ip()
{
local ui32=$1; shift
local ip n
for n in 1 2 3 4; do
ip=$((ui32 & 0xff))${ip:+.}$ip
ui32=$((ui32 >> 8))
done
echo $ip
}
#---------- CreateUser --------------------------------------------------------
#
function CreateUser()
{
local debug=0
local ClientName="$1"
local Corp="$2"
#local CLIENT_NUM=$(printf "%03d" $3)
local WgUsrDir="${BaseDir}/${Corp}/users" # BaseDir global variable
#---Create paths if not there
[ ! -d "$WgUsrDir" ] && mkdir -p "${WgUsrDir}"
CLIENT_PRIV_KEY=$(wg genkey)
CLIENT_PUB_KEY=$(echo "${CLIENT_PRIV_KEY}" | wg pubkey)
CLIENT_PRE_SHARED_KEY=$(wg genpsk)
#CLIENT_FILE_PREFIX="${CLIENT_NUM}-${ClientName}"
CLIENT_FILE_PREFIX="${ClientName}"
CLIENT_FILE_WIN="${WgUsrDir}/${CLIENT_FILE_PREFIX}.conf"
CLIENT_FILE_RTR="${WgUsrDir}/${CLIENT_FILE_PREFIX}.Endpoint.rsc"
((debug)) && echo -e "
Corp = $Corp
ClientName = $ClientName
CLIENT_FILE_WIN = $CLIENT_FILE_WIN
CLIENT_FILE_RTR = $CLIENT_FILE_RTR
" && exit
echo -e "Client:
${GREEN}---------------------------------------------------------${NC}"
echo -e "[Interface]
PrivateKey = ${CLIENT_PRIV_KEY}
ListenPort = 51821
Address = 10.8.38.${ClientNum}/32
DNS = 1.1.1.1,8.8.8.8
[Peer]
PublicKey = ${Endpoint_Usr_PUB_KEY}
PresharedKey = ${CLIENT_PRE_SHARED_KEY}
AllowedIPs = 10.8.0.0/16
Endpoint = ${Endpoint_Usr_Addr}:${Endpoint_Usr_Port}
PersistentKeepalive = 25
" | tee "${CLIENT_FILE_WIN}"
echo -e "\${CORP} Router:
${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard peers
add allowed-address=10.8.38.${ClientNum}/32 disabled=no comment=\"User ${ClientName}\" interface=wg1 \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\"${CLIENT_PUB_KEY}\""| tee "${CLIENT_FILE_RTR}"
Message "QR Code:"
qrencode -t ansiutf8 -l L < "${CLIENT_FILE_WIN}"
qrencode -l L -s 6 -d 225 -o "${CLIENT_FILE_WIN}.png" < "${CLIENT_FILE_WIN}"
}
#---------- CreateRouter ------------------------------------------------------
#
function CreateRouter()
{
local debug=1
local RouterNum="$1"
local RouterSubnet="$2"
local Corp="$3"
local BaseDir="${BaseDir}/${Corp}" # BaseDir global variable
local WgRtrDir="${BaseDir}/routers"
#---Create paths if not there
[ ! -d "$WgRtrDir" ] && mkdir -p "${WgRtrDir}"
RTR_PRIV_KEY=$(wg genkey)
Endpoint_Rtr_PUB_KEY=$(echo "${RTR_PRIV_KEY}" | wg pubkey)
RTR_PRE_SHARED_KEY=$(wg genpsk)
RTR_NUM=$(printf "%03d" $1)
RTR_FILE_PREFIX="${RTR_NUM}-Router"
RTR_FILE_RTR="${WgRtrDir}/${RTR_FILE_PREFIX}_Client.rsc"
RTR_FILE_RTR_ENDPOINT="${WgRtrDir}/${RTR_FILE_PREFIX}_Endpoint.rsc"
((debug)) && echo -e "
Corp = $Corp
RTR_NUM = $RTR_NUM
CLIENT_FILE_RTR = $RTR_FILE_RTR
BaseDir = $BaseDir
PreShared Key = $RTR_PRE_SHARED_KEY
" && exit
[ -d "${BaseDir}" ] && Message "Creating dir ${BaseDir}" && mkdir -p "${BaseDir}"
Message "Generated output files:"
echo -e "${GREEN}---------------------------------------------------------${NC}
${RTR_FILE_RTR}
${RTR_FILE_RTR_ENDPOINT}
"
Message "Client Router Config:"
echo -e "${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard
add listen-port=13239 mtu=1420 name=wg01 private-key=\"${RTR_PRIV_KEY}\"
/ip address add address=172.18.1.${RouterNum}/32 comment=wg-wg01 interface=wg01
/interface wireguard peers add allowed-address=172.16.18.254 client-keepalive=10 disabled=no comment=\"CCR1 Montreal\" interface=wg01 \\
endpoint-address=${Endpoint_Rtr_Addr_Public} endpoint-port=${Endpoint_Rrt_Port} preshared-key=\"${RTR_PRE_SHARED_KEY}\" public-key=\"${Endpoint_Rtr_PUB_KEY}\"
/system script add dont-require-permissions=no name=ping-CCR1 owner=admin policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source=\\
\"/ping interval=10 10.1.8.11 count=61\"
/system/scheduler add interval=10m name=Ping-CCR1 on-event=\"/system/script/run ping-CCR1\" policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon start-date=apr/02/2022 start-time=12:00:00 " \
| tee "${RTR_FILE_RTR}"
#echo -e "\n"
Message "${EndpointID} endpoint Config:"
echo -e "${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard peers add allowed-address=10.1.41.${RouterNum}/32,${RouterSubnet} disabled=no comment=\"Router ${RouterNum} ${NameRouter}\" \\
interface=WG-Routers preshared-key=\"${RTR_PRE_SHARED_KEY}\" public-key=\"${Endpoint_Rtr_PUB_KEY}\"
/ip route add dst-address=${RouterSubnet} gateway=10.1.41.${RouterNum}" \
| tee "${RTR_FILE_RTR_ENDPOINT}"
}
#---------- function RrtSubnet ------------------------------------------------
#
RtrSubnet()
{
local RtrNum=$1
BaseNum=$(ip2int $Start_Subnet) # Subnet de depart en format integer
Nth=$((RtrNum-1)) # Le router #1 est "0" dans la séquence de subnet, #2 est 1, etc
Nth=$((Nth*NAPS)) # Decimal a aditionner en fonction pour le Nth router
Subnet=$((BaseNum+Nth)) # Nth subnet calculé
# Subnet="${Subnet}/$(Bits_Subnet=3})"
echo -e "$(int2ip $Subnet)/${Subnet_Bits}"
}
#---------- function Interactive ----------------------------------------------
#
function Interactive()
{
echo -e "\nInteractive function"
}
#---------- function Help -----------------------------------------------------
#
function Help()
{
echo -e "
MikroTik WireGuard configurator
usage:
${ScriptName} [Options]
-c Corp name
-i Interactive (will ask for all needed infos)
-l List endpoints in config
-n User mode: # ot the new user (Unique user number between 1 and 253)
-u User name (example: AdrianSmith, don't use space or accentuated chars)
-r Router mode: # of the new client router (EVOQ router #, like 1 or 11)
-s Router Name (example: Montreal-1 , will appear as comment in endpoint router )
When in user mode, you must provide name & unique user number between 2 and 253.
This user number will be assigned an ip address 10.1.40.[user #].
" && exit
}
#================ MAIN ========================================================
#
((!$#)) && Help && exit # If no command parameters passed, help and bail out
echo -e "\n${GREEN}${ScriptName} ${BLUE}configurator version ${YELLOW}$Version${NC}"
while getopts c:dhiln:r:s:u: option
do
case "${option}" in
c) CORP=${OPTARG}
;;
d) debug=1
;;
h) Help
exit
;;
i) Interactive
exit
;;
l) Message "Listing endpoints in ${IniFile}"
grep '\[' ${IniFile}
exit
;;
n) NumUser=${OPTARG}
Mode="User"
;;
r) NumRouter=${OPTARG}
Mode="Router"
;;
s) NameRouter="${OPTARG}"
;;
u) NameUser="${OPTARG}"
;;
*) echo -e "Usage (bad argument: $OPTARG) \n"
exit 1;;
esac
done
((debug)) && echo -e "
NumRouter = ${NumRouter}
NumUser = ${NumUser}
RtrSubnet = $(RtrSubnet ${NumRouter})
"
if [[ "${NumRouter}" -ne "0" && "${NumUser}" -ne "0" ]]
then
echo "** Error, can't use user and router # simulteaneously"
exit 1
fi
#---Endpoint Router Config
EndpointID=RB5009
for PARAM in "${PARAMS[@]}"
do
eval ${PARAM}=$(sed -nr "/^\[${CORP}\]/ { :l /^${PARAM}[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" ${IniFile})
done
#Endpoint_Rtr_Addr_Public=$(sed -nr "/^\[${CORP}\]/ { :l /^Endpoint_Rtr_Addr_Public[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" ./genconfig.ini)
#Endpoint_Rtr_Addr_Private=$(sed -nr "/^\[${CORP}\]/ { :l /^Endpoint_Rtr_Addr_Private[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" ./genconfig.ini)
#Endpoint_Rrt_Port=$(sed -nr "/^\[${CORP}\]/ { :l /^Endpoint_Rrt_Port[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" ./genconfig.ini)
#Endpoint_Rtr_PUB_KEY=$(sed -nr "/^\[${CORP}\]/ { :l /^Endpoint_Rtr_PUB_KEY[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" ./genconfig.ini)
#Endpoint_Usr_Addr=$(sed -nr "/^\[${CORP}\]/ { :l /^Endpoint_Usr_Addr[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" ./genconfig.ini)
#Endpoint_Usr_Port=$(sed -nr "/^\[${CORP}\]/ { :l /^Endpoint_Usr_Port[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" ./genconfig.ini)
#Endpoint_Usr_PUB_KEY=$(sed -nr "/^\[${CORP}\]/ { :l /^Endpoint_Usr_PUB_KEY[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" ./genconfig.ini)
echo -e "
CORP = $CORP
Endpoint_Rtr_Addr_Public = $Endpoint_Rtr_Addr_Public
Endpoint_Rtr_Addr_Private = $Endpoint_Rtr_Addr_Private
Endpoint_Rrt_Port = $Endpoint_Rrt_Port
Endpoint_Rtr_PUB_KEY = $Endpoint_Rtr_PUB_KEY
Endpoint_Usr_Addr = $Endpoint_Usr_Addr
Endpoint_Usr_Port = $Endpoint_Usr_Port
Endpoint_Usr_PUB_KEY = $Endpoint_Usr_PUB_KEY
"
((debug)) && printf "Parameters : %s\n" "${PARAMS[@]}"
#exit
#---Client Router Subnets
Start_Subnet=10.1.41.0
Bits_Subnet=8
Subnet_Bits=$((32-Bits_Subnet)) # Router address subnet bits
NAPS=$((2**Bits_Subnet)) # Nombre d'Adresses Par Subnet
case "$Mode" in
User) Message "Creating User"
CreateUser ${NameUser} ${CORP}
exit
;;
Router) Message "Creating Router with $(RtrSubnet ${NumRouter})"
CreateRouter $NumRouter $(RtrSubnet ${NumRouter}) ${CORP}
exit
;;
*) echo -e "\n** ERROR : User # was not provided"
Help
;;
esac

View file

@ -1,117 +0,0 @@
#!/bin/bash
#
# (c) IngTegration inc 2023
# GPL licensed
#
debug=0
ClientName="$1"
ClientNum="$2"
Corp="$3"
Endpoint_Usr_PUB_KEY="CHANGE_ME" # put router WG public key here
RtrSubnetPrefix="10.0.254" # WG subnet prefix
DnsSrv="1.1.1.1 8.8.8.8"
AllowedIps="0.0.0.0/0" # Allowed IP for clients
RtrInterf="wg01" # Router WG Interface
Endpoint_Usr_Port=51844
#local CLIENT_NUM=$(printf "%03d" $3)
#local WgUsrDir="${BaseDir}/${Corp}/users" # BaseDir global variable
WgUsrDir="."
Endpoint_Usr_Addr="${RtrSubnetPrefix}.${ClientNum}"
BOLD=$( tput bold)
NORMAL=$( tput sgr0)
RESET=$( tput sgr0)
NC=$( tput sgr0) # No color
BOLD=$( tput bold)
BLACK=$( tput setaf 0)
RED=$( tput setaf 1)
GREEN=$( tput setaf 2)
YELLOW=$( tput setaf 3)
BLUE=$( tput setaf 4)
MAGENTA=$( tput setaf 5)
CYAN=$( tput setaf 6)
WHITE=$( tput setaf 7)
DEFAULT=$( tput setaf 9)
#===========Internal Functions=================================================
#
#-------------Help-------------------------------------------------------------
#
function Help()
{
cat << EOF
usage: $(basename "$0") [ClientName] [ClientNum] [Corp]
ClientName : Name of the roadwarrior client (Ex. marlene)
ClientNum : Roadwarrior sequence number, will translate into ip last octet
1 --> SubnetPrefix.1 (Ex: 172.16.20.1)
Corp : Name of RoadWarrior Company (Ex: ExoC)
EOF
exit
}
#---------------Message--------------------------------------------------------
#
function Message()
{
printf "\n${GREEN}[i] ${BLUE}%s${NC}\n" "$*"
}
((!$#)) && Help # Call help if no argument supplied
ClientPadNum=$(printf "%03d" $ClientNum)
CLIENT_PRIV_KEY=$(wg genkey)
CLIENT_PUB_KEY=$(echo "${CLIENT_PRIV_KEY}" | wg pubkey)
CLIENT_PRE_SHARED_KEY=$(wg genpsk)
#CLIENT_FILE_PREFIX="${CLIENT_NUM}-${ClientName}"
CLIENT_FILE_PREFIX="${ClientPadNum}-${Corp}-${ClientName}"
CLIENT_FILE_WIN="${WgUsrDir}/${CLIENT_FILE_PREFIX}.conf"
CLIENT_FILE_RTR="${WgUsrDir}/${CLIENT_FILE_PREFIX}.Endpoint.rsc"
((debug)) && echo -e "
Corp = $Corp
ClientName = $ClientName
CLIENT_FILE_WIN = $CLIENT_FILE_WIN
CLIENT_FILE_RTR = $CLIENT_FILE_RTR
" && exit
echo -e "Client:
${GREEN}---------------------------------------------------------${NC}"
echo -e "[Interface]
PrivateKey = ${CLIENT_PRIV_KEY}
ListenPort = ${Endpoint_Usr_Port}
Address = ${RtrSubnetPrefix}.${ClientNum}/32
DNS = ${DnsSrv}
[Peer]
PublicKey = ${Endpoint_Usr_PUB_KEY}
PresharedKey = ${CLIENT_PRE_SHARED_KEY}
AllowedIPs = ${AllowedIps}
Endpoint = ${Endpoint_Usr_Addr}:${Endpoint_Usr_Port}
PersistentKeepalive = 25
" | tee "${CLIENT_FILE_WIN}"
echo -e "\n${Corp} Router:
${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard peers
add allowed-address=${RtrSubnetPrefix}.${ClientNum}/32 disabled=no comment=\"User ${ClientName}\" interface=${RtrInterf} \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\"${CLIENT_PUB_KEY}\"" | tee "${CLIENT_FILE_RTR}"
Message "QR Code:"
qrencode -t ansiutf8 -l L < "${CLIENT_FILE_WIN}"
qrencode -l L -s 6 -d 225 -o "${CLIENT_FILE_WIN}.png" < "${CLIENT_FILE_WIN}"

Binary file not shown.

View file

@ -1,296 +0,0 @@
#!/bin/bash
Version=240226-1434
debug=0
CORP=IngTegration
RouterID=RB5009
Rtr_CCR1_Addr="199.168.223.11"
Rtr_CCR1_Port="13232"
Usr_CCR1_Addr="199.168.223.11"
Usr_CCR1_Port="13233"
ScriptName=$(basename "$0")
BaseDir="/home/boig01/temp/wireguard/ingt"
WgRtrDir="${BaseDir}/routers"
WgUsrDir="${BaseDir}/users"
RTR_CCR1_PUB_KEY="tZRvoRBOEBEz6sNZQmw1M2NE2OH78vkHib1iQgbxDDE="
USR_CCR1_PUB_KEY="tZRvoRBOEBEz6sNZQmw1M2NE2OH78vkHib1iQgbxDDE="
NumUser=0
NumRouter=0
NameUser=0
Mode=0
YELLOW='\033[0;33m'
GREEN='\033[0;32m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Create paths if not there
[ ! -d "$WgRtrDir" ] && mkdir -p "${WgRtrDir}"
[ ! -d "$WgUsrDir" ] && mkdir -p "${WgUsrDir}"
#---Client Router Subnets
Start_Subnet=172.18.1.0
Bits_Subnet=8
Subnet_Bits=$((32-Bits_Subnet)) # Router address subnet bits
NAPS=$((2**Bits_Subnet)) # Nombre d'Adresses Par Subnet
#=================== function Help ============================================
#
function Help()
{
echo -e "
WireGuard-MikroTik ${BLUE}${CORP}${NC} configurator
usage:
${ScriptName} [Options]
-n User # (Unique user number between 1 and 253)
-u User name (AdrianSmith)
-r Router # (EVOQ router #, like 1 or 11)
When in user mode, you must provide name & unique user number between 2 and 253.
This user number will be assigned an ip address 10.1.40.[user #].
" && exit
}
#=================== function Info =============================================
#
# Avec date / time prefix
#
Info() { printf "${GREEN}%s ${NC} %s\n" "$( date +%F_%T )" "$*" >&2; } # send to stderr
#=================== function Message ==========================================
#
# Send to STDOUT
#
Message() {
printf "\n${GREEN}[i] ${BLUE}%s${NC}" "$*"
}
#=================== function ip2int ===========================================
#
ip2int()
{
local a b c d
{ IFS=. read a b c d; } <<< $1
echo $(((((((a << 8) | b) << 8) | c) << 8) | d))
}
#=================== function int2ip ===========================================
#
int2ip()
{
local ui32=$1; shift
local ip n
for n in 1 2 3 4; do
ip=$((ui32 & 0xff))${ip:+.}$ip
ui32=$((ui32 >> 8))
done
echo $ip
}
#======================== CreateUser ==========================================
#
function CreateUser()
{
ClientName=$1
ClientNum=$2
CLIENT_PRIV_KEY=$(wg genkey)
CLIENT_PUB_KEY=$(echo "${CLIENT_PRIV_KEY}" | wg pubkey)
CLIENT_PRE_SHARED_KEY=$(wg genpsk)
CLIENT_NUM=$(printf "%03d" $2)
CLIENT_FILE_PREFIX="${CLIENT_NUM}-${ClientName}"
CLIENT_FILE_WIN="${WgUsrDir}/${CLIENT_FILE_PREFIX}.conf"
CLIENT_FILE_RTR="${WgUsrDir}/${CLIENT_FILE_PREFIX}.CCR1.rsc"
((debug)) && echo -e "
ClientName = $1
CLIENT_NUM = $CLIENT_NUM
CLIENT_FILE_WIN = $CLIENT_FILE_WIN
CLIENT_FILE_RTR = $CLIENT_FILE_RTR
" && exit
echo -e "Client:
${GREEN}---------------------------------------------------------${NC}"
echo -e "[Interface]
PrivateKey = ${CLIENT_PRIV_KEY}
ListenPort = 51821
Address = 10.8.38.${ClientNum}/32
DNS = 1.1.1.1,8.8.8.8
[Peer]
PublicKey = ${USR_CCR1_PUB_KEY}
PresharedKey = ${CLIENT_PRE_SHARED_KEY}
AllowedIPs = 10.8.0.0/16
Endpoint = ${Usr_CCR1_Addr}:${Usr_CCR1_Port}
PersistentKeepalive = 25
" | tee "${CLIENT_FILE_WIN}"
echo -e "\nAtom Router:
${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard peers
add allowed-address=10.8.38.${ClientNum}/32 disabled=no comment=\"User ${ClientName}\" interface=wg1 \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\"${CLIENT_PUB_KEY}\""| tee "${CLIENT_FILE_RTR}"
}
#======================== CreateRouter ========================================
#
function CreateRouter()
{
RouterNum="$1"
RouterSubnet="$2"
RTR_PRIV_KEY=$(wg genkey)
RTR_PUB_KEY=$(echo "${RTR_PRIV_KEY}" | wg pubkey)
RTR_PRE_SHARED_KEY=$(wg genpsk)
RTR_NUM=$(printf "%03d" $1)
RTR_FILE_PREFIX="${RTR_NUM}-Router"
RTR_FILE_RTR="${WgRtrDir}/${RTR_FILE_PREFIX}.rsc"
RTR_FILE_RTR_CCR1="${WgRtrDir}/${RTR_FILE_PREFIX}.CCR1.rsc"
((debug)) && echo -e "
ClientName = $1
CLIENT_NUM = $RTR_NUM
CLIENT_FILE_RTR = $RTR_FILE_RTR
" && exit
Message "Generated output files:"
echo -e "${GREEN}---------------------------------------------------------${NC}
${RTR_FILE_RTR}
${RTR_FILE_RTR_CCR1}
"
Message "Router Client Config:"
echo -e "${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard
add listen-port=13239 mtu=1420 name=wg01 private-key=\"${RTR_PRIV_KEY}\"
/ip address add address=10.1.41.${RouterNum}/32 comment=wg-wg01 interface=wg01
/ip route add dst-address=10.0.0.0/8 gateway=wg01
/ip route add dst-address=192.168.0.0/16 gateway=wg01
/interface wireguard peers add allowed-address=10.0.0.0/8,192.168.0.0/16 client-keepalive=10 disabled=no comment=\"CCR1 Montreal\" interface=wg01 \\
endpoint-address=${Rtr_CCR1_Addr} endpoint-port=${Rtr_CCR1_Port} preshared-key=\"${RTR_PRE_SHARED_KEY}\" public-key=\"${RTR_CCR1_PUB_KEY}\"
/system script add dont-require-permissions=no name=ping-CCR1 owner=admin policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source=\\
\"/ping interval=10 10.1.8.11 count=61\"
/system/scheduler add interval=10m name=Ping-CCR1 on-event=\"/system/script/run ping-CCR1\" policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon start-date=apr/02/2022 start-time=12:00:00 " \
| tee "${RTR_FILE_RTR}"
#echo -e "\n"
Message "${RouterID} Config:"
echo -e "${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard peers add allowed-address=10.1.41.${RouterNum}/32,${RouterSubnet} disabled=no comment=\"Router ${RouterNum}\" \\
interface=WG-Routers preshared-key=\"${RTR_PRE_SHARED_KEY}\" public-key=\"${RTR_PUB_KEY}\"
/ip route add dst-address=${RouterSubnet} gateway=10.1.41.${RouterNum}" \
| tee "${RTR_FILE_RTR_CCR1}"
}
#=================== function RrtSubnet ========================================
#
RtrSubnet()
{
local RtrNum=$1
BaseNum=$(ip2int $Start_Subnet) # Subnet de depart en format integer
Nth=$((RtrNum-1)) # Le router #1 est "0" dans la séquence de subnet, #2 est 1, etc
Nth=$((Nth*NAPS)) # Decimal a aditionner en fonction pour le Nth router
Subnet=$((BaseNum+Nth)) # Nth subnet calculé
# Subnet="${Subnet}/$(Bits_Subnet=3})"
echo -e "$(int2ip $Subnet)/${Subnet_Bits}"
}
#================ MAIN ========================================================
#
((!$#)) && Help && exit # If no command parameters passed, help and bail out
echo -e "\nWireGuard-MikroTik ${BLUE}${CORP}${NC} configurator version $Version\n"
while getopts dhn:r:u: option
do
case "${option}" in
d) debug=1
;;
h) Help
exit ;;
n) NumUser=${OPTARG}
Mode="User"
;;
r) NumRouter=${OPTARG}
Mode="Router"
;;
u) NameUser=${OPTARG}
;;
*) echo -e "Usage (bad argument: $OPTARG) \n"
exit 1;;
esac
done
((debug)) && echo -e "
NumRouter = ${NumRouter}
NumUser = ${NumUser}
RtrSubnet = $(RtrSubnet ${NumRouter})
" && exit
if [[ "${NumRouter}" -ne "0" && "${NumUser}" -ne "0" ]]
then
echo "** Error, can't use user and router # simulteaneously"
exit 1
fi
case "$Mode" in
User) Message "Creating User"
CreateUser $NameUser $NumUser
exit
;;
Router) Message "Creating Router with $(RtrSubnet ${NumRouter})"
CreateRouter $NumRouter $(RtrSubnet ${NumRouter})
exit
;;
*) echo -e "\n** ERROR : User # was not provided"
Help
;;
esac

View file

@ -1,66 +0,0 @@
[ingtegration-rb5009]
Addr_Public="seve.ingtegration.com"
01_InterfaceName="WG-Devices"
01_PUBKEY="MmTMFo+Fs3N9jrcVeGKkmMi2NoZctvSB7813LCN12nY="
01_Addr="172.16.254.2"
01_Subnet="172.16.254.0/24"
01_Port="14321"
02_InterfaceName="WG-Users"
02_PUBKEY="iPArVoKAjEYTsvSb2NdQRDIUxHPHBgGTHAK3uAKKvkw="
01_Subnet="172.16.40.0/24"
02_Addr="172.16.40.254"
02_Port="14322"
[evoq-mtl]
Addr_Public="66.171.167.250"
01_InterfaceName="WG-Routers"
01_PUBKEY="9au45IDNJhHDNtN+LIpJDyMFTEYdN9WOSSHEJS8WRmw="
01_Subnet="10.1.41.0/24"
01_Addr="10.1.41.254"
01_Port="13232"
02_InterfaceName="WG-Users"
02_PUBKEY="9au45IDNJhHDNtN+LIpJDyMFTEYdN9WOSSHEJS8WRmw="
02_Subnet="10.1.42.0/24"
02_Addr="10.1.42.254"
02_Port="13233"
[koze-maison]
Addr_Public="b4a30b139a75.sn.mynetname.net"
01_Subnet="10.1.41.0/24"
01_Addr="172.16.41.254"
01_Port="13232"
01_PUBKEY="8e1iXWniMo+3OU1FsNPAgrG0av9d/Ijf9ybj75z9GWE="
01_InterfaceName="WG-Users"
[rrf-rb5009]
Addr_Public="142.217.209.155"
01_Subnet="172.16.41.0/24"
01_Addr_Private="172.16.41.254"
01_Port="14231"
01_PUBKEY="FYmwzlP4m2IkS4VpDSwhN6NHHJBrEBbIqf9+GS7VWxo="
01_InterfaceName="WG-Users"
[cccp-hexs]
Addr_Public="199.168.223.11"
01_Subnet="10.8.37.0/24"
01_Addr="10.8.37.254"
01_Port="13233"
01_PUBKEY="nAwCkIHkPlgJwpU+t84mBSOUsylfDj+nudD3neZoaiU="
01_InterfaceName="WG-Users"
[cccp-rb2011]
Addr_Public="199.168.223.10"
01_InterfaceName="WG-Users"
01_Subnet="10.8.37.0/25"
01_Addr="10.8.35.126"
01_Port="13232"
01_PUBKEY="nAwCkIHkPlgJwpU+t84mBSOUsylfDj+nudD3neZoaiU="
02_InterfaceName="WG-Routers"
02_Subnet="10.8.37.129/25"
02_Addr="10.8.34.254"
02_Port="13233"
02_PUBKEY="kIV/vXbuNWWc//zU27+g3QcrOIYuVh8/Bo/g8O2iwUQ="

View file

@ -1,146 +0,0 @@
#!/bin/bash
#
debug=0
ScriptName=$(basename "$0")
RouterName="RB5009-CTG"
RouterAddrPublic="heh08h84mnt.sn.mynetname.net"
RouterPort="14322"
RouterAddrPrivate="172.16.254.2"
RouterInterface="WG-Devices"
BOLD=$( tput bold)
NORMAL=$( tput sgr0)
RESET=$( tput sgr0)
NC=$( tput sgr0) # No color
BOLD=$( tput bold)
BLACK=$( tput setaf 0)
RED=$( tput setaf 1)
GREEN=$( tput setaf 2)
YELLOW=$( tput setaf 3)
BLUE=$( tput setaf 4)
MAGENTA=$( tput setaf 5)
CYAN=$( tput setaf 6)
WHITE=$( tput setaf 7)
DEFAULT=$( tput setaf 9)
#---------- function Message --------------------------------------------------
#
# Send to STDOUT
#
function Message()
{
printf "\n${GREEN}[i] ${BLUE}%s${NC}\n" "$*"
}
function CreateRouter()
{
local debug=0
local DeviceNum="$1" # voir plus bas avec printf
local DeviceName="$2"
local DeviceInterface="$3"
DeviceAllowedAddress="172.16.40.2"
DevicePrivKey=$(wg genkey)
DevicePubKey=$(echo "${DevicePrivKey}" | wg pubkey)
DevicePSK=$(wg genpsk)
DeviceNumPad=$(printf "%03d" $1) # 3 digit pad of $1
DeviceFilesPrefix="R-${DeviceNumPad}"
RouterFileCfg="${DeviceFilesPrefix}_RouterCfg.rsc"
DeviceFileCfg="${DeviceFilesPrefix}_DeviceCfg.rsc"
((debug)) && echo -e "
DeviceNum = $DeviceNum
DevicePrivKey = $DevicePrivKey
DevicePubKey = $DevicePubKey
DevicePSK = $DevicePSK
DeviceFileCfg = $DeviceFileCfg
RouterFileCfg = $RouterFileCfg
" | column -t && exit
Message "Generated output files:"
echo -e "${GREEN}---------------------------------------------------------${NC}
${RouterFileCfg}
${DeviceFileCfg}
"
Message "Router Config:"
echo -e "${GREEN}---------------------------------------------------------${NC}"
echo -e "S'assurer que sur router: /interface wireguard add listen-port=${RouterPort} mtu=1420 name=${RouterInterface}\n"
echo -e "/interface wireguard peers add allowed-address=172.16.254.${DeviceNum}/32 client-keepalive=10 disabled=no comment=\"${DeviceName}\" \\
interface=WG-Devices preshared-key=\"${DevicePSK}\" public-key=\"${DevicePubKey}\""
#| tee "${RouterFileCfg}"
Message "${DeviceName} device Config:"
echo -e "${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard add listen-port=13239 mtu=1420 name=${DeviceInterface} private-key=\"${DevicePrivKey}\"
/interface wireguard peers add allowed-address=${RouterAddrPrivate} client-keepalive=15 disabled=no comment=\"${RouterName}\" \\
interface=${DeviceInterface} preshared-key=\"${DevicePSK}\" public-key=\"${DevicePubKey}\" endpoint-address=${RouterAddrPublic} endpoint-port=${RouterPort}
/ip route add dst-address=0.0.0.0 gateway=${RouterAddrPrivate}"
#| tee "${DeviceFileCfg}"
}
Help() {
cat << EOF
usage: $(basename "$0") [OPTIONS]
-d Device Number
-n Device Name
-i Device Interface
-h This help
EOF
}
((!$#)) && Help
while getopts d:n:i:h option
do
case "${option}" in
d) DeviceNumber=${OPTARG};;
n) DeviceName=${OPTARG};;
i) DeviceInterface=${OPTARG};;
h) Help
exit 0;;
*) echo -e "Usage (bad argument: ${OPTARG}) \n"
exit 1;;
esac
done
((debug)) && echo -e "
DeviceNumber = $DeviceNumber
DeviceName = $DeviceName
DeviceInterface = $DeviceInterface
" | column -t && exit
CreateRouter ${DeviceNumber} ${DeviceName} ${DeviceInterface}

View file

@ -1,31 +0,0 @@
CCR1016 EVOQ
============
/ip address
add address=10.1.41.254/24 interface=WG-Routers network=10.1.41.0
/interface wireguard
add comment=10.1.32.0/24 listen-port=13232 mtu=1420 name=WG-Routers
/interface wireguard peers
add allowed-address=10.1.40.1/32 client-keepalive=10s comment="User squirion" interface=WG-Users preshared-key="+tgz1wqMtrota6gxmMtEix3wiZI85IM8Ty5x7ucgbiA=" public-key="6KhC7Ai2As7ShqKC1tlKQ1eKp8MLdrljBdJBCUIjal8="
WG "Server":
------------
Router WAN Addr : heh08h84mnt.sn.mynetname.net
Router WAN Port : 14322
Router Local Address: 172.16.254.2/24
Device: WG-Devices
Public Key: MmTMFo+Fs3N9jrcVeGKkmMi2NoZctvSB7813LCN12nY=
-d [device num] -n [device name] -i [device interface]
genconfig_router -d 4 -n Fuengirola -i wg-ctg

View file

@ -1,431 +0,0 @@
#!/bin/bash
Version=250731-1953
debug=0
ScriptMode="" # Script gen mode for client: user or router
BOLD=$( tput bold)
NORMAL=$( tput sgr0)
RESET=$( tput sgr0)
NC=$( tput sgr0) # No color
BOLD=$( tput bold)
BLACK=$( tput setaf 0)
RED=$( tput setaf 1)
GREEN=$( tput setaf 2)
YELLOW=$( tput setaf 3)
BLUE=$( tput setaf 4)
MAGENTA=$( tput setaf 5)
CYAN=$( tput setaf 6)
WHITE=$( tput setaf 7)
DEFAULT=$( tput setaf 9)
#---ini file parameters list
unset PARAMS;
PARAMS=(
RtrInterface
Rtr_Addr_Admin
Rtr_Addr_Public
Rrt_Port
Rtr_Addr_Private
Rtr_CIDR_Mask
Rtr_PUB_KEY
Rtr_DNS
Rtr_Route_Subnet
)
#---A enlever apres testing
export RouterName=""
export RouterInterface=""
export DeviceName=""
export Company=""
export CORP=""
export UserName=""
#========== INTERNAL FUNCTIONS ================================================
#---------- function Info -----------------------------------------------------
#
# With date / time prefix
#
Info()
{
printf "${GREEN}%s ${NC} %s\n" "$( date +%F_%T )" "$*"
}
#---------- function Message --------------------------------------------------
#
# Send to STDOUT
#
function Message()
{
printf "\n${GREEN}[i] ${BLUE}%s${NC}\n" "$*"
}
#---------- ip2int ------------------------------------------------------------
#
function ip2int()
{
local a b c d
{ IFS=. read a b c d; } <<< $1
echo $(((((((a << 8) | b) << 8) | c) << 8) | d))
}
#---------- int2ip ------------------------------------------------------------
#
function int2ip()
{
local ui32=$1; shift
local ip n
for n in 1 2 3 4; do
ip=$((ui32 & 0xff))${ip:+.}$ip
ui32=$((ui32 >> 8))
done
echo $ip
}
#---------- RouterCommand -----------------------------------------------------
#
function RouterConnect()
{
local Command="$"
}
#---------- CreateUser --------------------------------------------------------
#
function CreateUser()
{
local RouterName=$1
local RouterInterface=$2
local UserNumber=$3
local UserName=$4
local debug=0
RouterCfg="${RouterName}.cfg"
#---Read values from config file
for PARAM in "${PARAMS[@]}"
do
eval local ${PARAM}=$(sed -nr "/^\[${RouterName}\]/ { :l /^${PARAM}[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" $RouterCfg)
done
Digits=000
Temp="${Digits}${UserNumber}"
ClientNumPad=$(echo ${Temp:(-${#Digits})})
IFS=. read -r octet1 octet2 octet3 octet4 <<< "$Rtr_Addr_Private"
Subnet="${octet1}.${octet2}.${octet3}"
UserAddress=${Subnet}.${UserNumber}/32
Message "Subnet : $Subnet"
Message "ClientNumPad : $ClientNumPad"
((debug)) && echo -e "
DEBUG - CreateUser
User Number = $1
UserName = $2
UserName = $3
UserAddress = $UserAddress
Rtr_Addr_Public = $Rtr_Addr_Public
Rrt_Port = $Rrt_Port
RouterInterface = $RouterInterface
Rtr_Addr_Private = $Rtr_Addr_Private
Rtr_CIDR_Mask = $Rtr_CIDR_Mask
Rtr_PUB_KEY = $Rtr_PUB_KEY
Subnet = $Subnet
Rtr_DNS = $Rtr_DNS
Rtr_Route_Subnet = $Rtr_Route
" | column -t && exit
CLIENT_PRIV_KEY=$(wg genkey)
CLIENT_PUB_KEY=$(echo "${CLIENT_PRIV_KEY}" | wg pubkey)
CLIENT_PRE_SHARED_KEY=$(wg genpsk)
ROUTER_PUB_KEY="$RouterPubKey"
CLIENT_FILE_PREFIX="U-${ClientNumPad}-${UserName}"
CLIENT_FILE_WIN="${CLIENT_FILE_PREFIX}.conf"
CLIENT_FILE_RTR="${CLIENT_FILE_PREFIX}.Peer.rsc"
echo -e "\nClient:
${GREEN}---------------------------------------------------------${NC}"
echo -e "[Interface]
PrivateKey = ${CLIENT_PRIV_KEY}
ListenPort = 51821
Address = ${UserAddress}
DNS = ${Rtr_DNS}
[Peer]
PublicKey = ${Rtr_PUB_KEY}
PresharedKey = ${CLIENT_PRE_SHARED_KEY}
AllowedIPs = ${Rtr_Route_Subnet}
Endpoint = ${Rtr_Addr_Public}:${Rrt_Port}
PersistentKeepalive = 25
" | tee "${CLIENT_FILE_WIN}"
echo -e "\nRouter:
${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard peers
add allowed-address=${Subnet}.${UserNumber}/32 disabled=no name=\"${UserName}\" interface=${RouterInterface} \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\"${CLIENT_PUB_KEY}\""| tee "${CLIENT_FILE_RTR}"
Message "QR Code:"
qrencode -t ansiutf8 -l L < "${CLIENT_FILE_WIN}"
qrencode -l L -s 6 -d 225 -o "${CLIENT_FILE_WIN}.png" < "${CLIENT_FILE_WIN}"
Message "Generated User Files:"
ls -1 ${CLIENT_FILE_PREFIX}*
}
#---------- CreateRouter ------------------------------------------------------
#
function CreateRouter()
{
local debug=1
local RouterNum="$1"
local RouterSubnet="$2"
local Corp="$3"
local BaseDir="${BaseDir}/${Corp}" # BaseDir global variable
local WgRtrDir="${BaseDir}/routers"
#---Create paths if not there
[ ! -d "$WgRtrDir" ] && mkdir -p "${WgRtrDir}"
RTR_PRIV_KEY=$(wg genkey)
Endpoint_Rtr_PUB_KEY=$(echo "${RTR_PRIV_KEY}" | wg pubkey)
RTR_PRE_SHARED_KEY=$(wg genpsk)
RTR_NUM=$(printf "%03d" $1)
RTR_FILE_PREFIX="${RTR_NUM}-Router"
RTR_FILE_RTR="${WgRtrDir}/${RTR_FILE_PREFIX}_Client.rsc"
RTR_FILE_RTR_ENDPOINT="${WgRtrDir}/${RTR_FILE_PREFIX}_Endpoint.rsc"
((debug)) && echo -e "
Corp = $Corp
RTR_NUM = $RTR_NUM
CLIENT_FILE_RTR = $RTR_FILE_RTR
BaseDir = $BaseDir
PreShared Key = $RTR_PRE_SHARED_KEY
" && exit
[ -d "${BaseDir}" ] && Message "Creating dir ${BaseDir}" && mkdir -p "${BaseDir}"
Message "Generated output files:"
echo -e "${GREEN}---------------------------------------------------------${NC}
${RTR_FILE_RTR}
${RTR_FILE_RTR_ENDPOINT}
"
Message "Client Router Config:"
echo -e "${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard
add listen-port=13239 mtu=1420 name=wg01 private-key=\"${RTR_PRIV_KEY}\"
/ip address add address=172.18.1.${RouterNum}/32 comment=wg-wg01 interface=wg01
/interface wireguard peers add allowed-address=172.16.18.254 client-keepalive=10 disabled=no comment=\"CCR1 Montreal\" interface=wg01 \\
endpoint-address=${Endpoint_Rtr_Addr_Public} endpoint-port=${Endpoint_Rrt_Port} preshared-key=\"${RTR_PRE_SHARED_KEY}\" public-key=\"${Endpoint_Rtr_PUB_KEY}\"
/system script add dont-require-permissions=no name=ping-CCR1 owner=admin policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source=\\
\"/ping interval=10 10.1.8.11 count=61\"
/system/scheduler add interval=10m name=Ping-CCR1 on-event=\"/system/script/run ping-CCR1\" policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon start-date=apr/02/2022 start-time=12:00:00 " \
| tee "${RTR_FILE_RTR}"
#echo -e "\n"
Message "${EndpointID} endpoint Config:"
echo -e "${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard peers add allowed-address=10.1.41.${RouterNum}/32,${RouterSubnet} disabled=no comment=\"Router ${RouterNum} ${NameRouter}\" \\
interface=WG-Routers preshared-key=\"${RTR_PRE_SHARED_KEY}\" public-key=\"${Endpoint_Rtr_PUB_KEY}\"
/ip route add dst-address=${RouterSubnet} gateway=10.1.41.${RouterNum}" \
| tee "${RTR_FILE_RTR_ENDPOINT}"
}
#---------- GetRouter_Infos ----------------------------------------------------
#
function GetRouter_Infos()
{
local RouterName="$1"
local IniFile="${1}.cfg"
local debug=0
((debug)) && echo -e "\nIniFile = ${IniFile}\n"
#read -p "Entrer l'interface du router: " RouterInterface
echo -e "[${RouterName}]" >> ${IniFile}
for PARAM in "${PARAMS[@]}"
do
echo -e "\nPARAM = $PARAM"
eval 'read -p "Entrer ${PARAM} " Value'
eval 'echo ${PARAM}=${Value} >> ${IniFile}'
done
((debug)) && echo "${FUNCNAME[0]} exit"
}
#---------- Help ---------------------------------------------------------------
#
function Help() {
cat << EOF
usage: $(basename "$0") [OPTIONS]
-a Debug mode
-d Device Name
-h Show this message
-i Interactive
-u User Name
-n User / Device number
EOF
}
#================= MAIN =======================================================
#
((!$#)) && Help && exit
while getopts ad:hi:n:qu: option
do
case "${option}" in
a) debug=1
;;
d) DeviceName="${OPTARG}"
;;
h) Help
exit
;;
i) Interactive
exit
;;
n) UserNumber="${OPTARG}"
;;
u) UserName="${OPTARG}"
;;
*) Message "Usage (bad argument: $OPTARG)"
exit 1
;;
esac
done
#---Init global variables
#for PARAM in "${PARAMS[@]}"
#do
# eval export '${PARAM}=""'
# done
if [[ ! -z ${UserName} ]] # User mode prioritised if both specified
then
ScriptMode=User
Message "User mode"
elif [[ ! -z ${DeviceName} ]]
then
ScriptMode=Device
Message "Device mode"
else
Message "Must use either -u or -d"
exit
fi
CfgNum=$(find . -maxdepth 1 -iname "*.cfg" |wc -l)
Message "Avant demande router infos"
if [[ $CfgNum -eq 1 ]]
then
RouterCfg=$(find . -maxdepth 1 -iname "*.cfg" -printf "%f")
RouterName="${RouterCfg%.*}"
else
read -p "Entrer Nom du Router: " RouterName
((debug)) && echo -e "Router Name = ${RouterName}"
GetRouter_Infos "${RouterName}"
RouterCfg=${RouterName}.cfg
fi
((debug)) && echo -e "
Après GetRouter_Infos
RouterName : $RouterName
RouterInterface : $RouterInterface
"
for PARAM in "${PARAMS[@]}"
do
eval ${PARAM}=$(sed -nr "/^\[${RouterName}\]/ { :l /^${PARAM}[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" $RouterCfg)
done
echo -e "Avant Create User"
((debug)) && echo -e "
RouterName = $RouterName
DeviceName = $DeviceName
UserNumber = $UserNumber
UserName = $UserName
Rtr_Addr_Admin = $Rtr_Addr_Admin
Rtr_Addr_Public = $Rtr_Addr_Public
Rrt_Port = $Rrt_Port
RtrInterface = $RtrInterface
Rtr_Addr_Private = $Rtr_Addr_Private
Rtr_CIDR_Mask = $Rtr_CIDR_Mask
Rtr_PUB_KEY = $Rtr_PUB_KEY
" | column -t && exit
case "${ScriptMode}" in
User) CreateUser ${RouterName} ${RtrInterface} ${UserNumber} ${UserName}
exit
;;
Router) CreateRouter ${RouterName} ${UserNumber} ${DeviceName}
;;
*) Message "Bad mode passed ${ScriptMode}"
exit 1
;;
esac
Message "All done."

View file

@ -1,306 +0,0 @@
#!/bin/bash
debug=0
BOLD=$( tput bold)
NORMAL=$( tput sgr0)
RESET=$( tput sgr0)
NC=$( tput sgr0) # No color
BOLD=$( tput bold)
BLACK=$( tput setaf 0)
RED=$( tput setaf 1)
GREEN=$( tput setaf 2)
YELLOW=$( tput setaf 3)
BLUE=$( tput setaf 4)
MAGENTA=$( tput setaf 5)
CYAN=$( tput setaf 6)
WHITE=$( tput setaf 7)
DEFAULT=$( tput setaf 9)
#---ini file parameters list
unset PARAMS;
PARAMS=(
Rtr_Addr_Public
Rrt_Port
Rtr_Interface
Rtr_Addr_Private
Rtr_CIDR_Mask
Rtr_PUB_KEY
)
export RouterName=""
export Company=""
export CORP=""
#========== INTERNAL FUNCTIONS ================================================
#---------- function Info -----------------------------------------------------
#
# With date / time prefix
#
Info()
{
printf "${GREEN}%s ${NC} %s\n" "$( date +%F_%T )" "$*"
}
#---------- function Message --------------------------------------------------
#
# Send to STDOUT
#
function Message()
{
printf "\n${GREEN}[i] ${BLUE}%s${NC}\n" "$*"
}
#---------- ip2int ------------------------------------------------------------
#
function ip2int()
{
local a b c d
{ IFS=. read a b c d; } <<< $1
echo $(((((((a << 8) | b) << 8) | c) << 8) | d))
}
#---------- int2ip ------------------------------------------------------------
#
function int2ip()
{
local ui32=$1; shift
local ip n
for n in 1 2 3 4; do
ip=$((ui32 & 0xff))${ip:+.}$ip
ui32=$((ui32 >> 8))
done
echo $ip
}
#---------- CreateUser --------------------------------------------------------
#
function CreateUser()
{
local CORP=$1
local RouterCfg=$2
local UserNumber=$3
local NameUser=$4
local debug=1
#---Read values from config file
for PARAM in "${PARAMS[@]}"
do
eval local ${PARAM}=$(sed -nr "/^\[${CORP}\]/ { :l /^${PARAM}[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" $RouterCfg)
done
Digits=000
Temp="${Digits}${UserNumber}"
ClientNumPad=$(echo ${Temp:(-${#Digits})})
IFS=. read -r octet1 octet2 octet3 octet4 <<< "$Rtr_Addr_Private"
Subnet="${octet1}.${octet2}.${octet3}"
Message "Subnet : $Subnet"
Message "ClientNumPad : $ClientNumPad"
((debug)) && echo -e "
DEBUG - CreateUser
UserNumber = $1
NameUser = $2
Company = $3
Rtr_Addr_Public = $Rtr_Addr_Public
Rrt_Port = $Rrt_Port
Rtr_Interface = $Rtr_Interface
Rtr_Addr_Private = $Rtr_Addr_Private
Rtr_CIDR_Mask = $Rtr_CIDR_Mask
Rtr_PUB_KEY = $Rtr_PUB_KEY
Subnet = $Subnet
" && exit
CLIENT_PRIV_KEY=$(wg genkey)
CLIENT_PUB_KEY=$(echo "${CLIENT_PRIV_KEY}" | wg pubkey)
CLIENT_PRE_SHARED_KEY=$(wg genpsk)
ROUTER_PUB_KEY="$RouterPubKey"
CLIENT_FILE_PREFIX="${ClientNumPad}-${NameUser}"
CLIENT_FILE_WIN="${CLIENT_FILE_PREFIX}.conf"
CLIENT_FILE_RTR="${CLIENT_FILE_PREFIX}.Peer.rsc"
echo -e "\nClient:
${GREEN}---------------------------------------------------------${NC}"
echo -e "[Interface]
PrivateKey = ${CLIENT_PRIV_KEY}
ListenPort = 51821
Address = ${Subnet}.${UserNumber}/32
DNS = 1.1.1.1,8.8.8.8
[Peer]
PublicKey = ${ROUTER_PUB_KEY}
PresharedKey = ${CLIENT_PRE_SHARED_KEY}
AllowedIPs = 0.0.0.0/0
Endpoint = ${RouterAddressPub}:${RouterPort}
PersistentKeepalive = 25
" | tee "${CLIENT_FILE_WIN}"
echo -e "\nRouter:
${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard peers
add allowed-address=${Subnet}.${UserNumber}/32 disabled=no name=\"${NameUser}\" interface=${Rtr_Interface} \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\"${CLIENT_PUB_KEY}\""| tee "${CLIENT_FILE_RTR}"
Message "QR Code:"
qrencode -t ansiutf8 -l L < "${CLIENT_FILE_WIN}"
qrencode -l L -s 6 -d 225 -o "${CLIENT_FILE_WIN}.png" < "${CLIENT_FILE_WIN}"
ls -1 ${ClientNumPad}*
}
function GetRouter_Infos()
{
local RouterName="$1"
local IniFile="${1}.cfg"
local debug=0
((debug)) && echo -e "\nIniFile = ${IniFile}\n"
read -p "Entrer CORP: " CORP
echo -e "[${CORP}]" | tee ${IniFile}
for PARAM in "${PARAMS[@]}"
do
#eval ${PARAM}=$(sed -nr "/^\[${CORP}\]/ { :l /^${PARAM}[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" ${IniFile})
echo -e "\nPARAM = $PARAM"
eval 'read -p "Entrer ${PARAM} " Variable'
eval 'echo ${PARAM}=${Variable} | tee -a ${IniFile}'
done
((debug)) && echo "GetRouter_Infos exit"
}
Help() {
cat << EOF
usage: $(basename "$0") [OPTIONS]
-c Company name
-h Show this message
-i Interactive
-u User Name
-n User number
EOF
}
((!$#)) && Help && exit
while getopts c:dhin:r:u: option
do
case "${option}" in
c) CORP=${OPTARG}
;;
d) debug=1
;;
h) Help
exit
;;
i) Interactive
exit
;;
n) UserNumber="${OPTARG}"
;;
r) RouterName="${OPTARG}" # à enlever
;;
u) NameUser="${OPTARG}"
;;
*) echo -e "Usage (bad argument: $OPTARG) \n"
exit 1;;
esac
done
#---Init global variables
#for PARAM in "${PARAMS[@]}"
#do
# eval export '${PARAM}=""'
# done
CfgNum=$(find . -maxdepth 1 -iname "*.cfg" |wc -l)
#Message "Found $CfgNum config files"
if [[ $CfgNum -eq 1 ]]
then
RouterCfg=$(find . -maxdepth 1 -iname "*.cfg" -printf "%f")
else
read -p "Entrer Nom du Router: " RouterName
((debug)) && echo -e "Router Name = ${RouterName}"
GetRouter_Infos "${RouterName}"
RouterCfg=${RouterName}.cfg
fi
((debug)) &&echo -e "
RouterCfg : $RouterCfg
CORP : $CORP
"
#((debug)) && echo -e "Avant PARAM"
for PARAM in "${PARAMS[@]}"
do
eval ${PARAM}=$(sed -nr "/^\[${CORP}\]/ { :l /^${PARAM}[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" $RouterCfg)
done
echo -e "
Avant Create User
UserNumber = $UserNumber
NameUser = $NameUser
CORP = $CORP
Rtr_Addr_Public = $Rtr_Addr_Public
Rrt_Port = $Rrt_Port
Rtr_Interface = $Rtr_Interface
Rtr_Addr_Private = $Rtr_Addr_Private
Rtr_CIDR_Mask = $Rtr_CIDR_Mask
Rtr_PUB_KEY = $Rtr_PUB_KEY
"
exit
CreateUser ${CORP} ${RouterCfg} ${UserNumber} ${NameUser}
#${Rtr_Addr_Public} ${Rrt_Port} ${Rtr_Interface} ${Rtr_Addr_Private} ${Rtr_CIDR_Mask} "${Rtr_PUB_KEY}"
exit
CLIENT_PRIV_KEY=$(wg genkey)
CLIENT_PUB_KEY=$(echo "${CLIENT_PRIV_KEY}" | wg pubkey)
CLIENT_PRE_SHARED_KEY=$(wg genpsk)
echo -e "
CLIENT_PRIV_KEY $CLIENT_PRIV_KEY
CLIENT_PUB_KEY $CLIENT_PUB_KEY
CLIENT_PRE_SHARED_KEY $CLIENT_PRE_SHARED_KEY
"

View file

@ -1,430 +0,0 @@
#!/bin/bash
Version=250731-1953
debug=0
ScriptMode="" # Script gen mode for client: user or router
BOLD=$( tput bold)
NORMAL=$( tput sgr0)
RESET=$( tput sgr0)
NC=$( tput sgr0) # No color
BOLD=$( tput bold)
BLACK=$( tput setaf 0)
RED=$( tput setaf 1)
GREEN=$( tput setaf 2)
YELLOW=$( tput setaf 3)
BLUE=$( tput setaf 4)
MAGENTA=$( tput setaf 5)
CYAN=$( tput setaf 6)
WHITE=$( tput setaf 7)
DEFAULT=$( tput setaf 9)
#---ini file parameters list
unset PARAMS;
PARAMS=(
RtrInterface
Rtr_Addr_Admin
Rtr_Addr_Public
Rrt_Port
Rtr_Addr_Private
Rtr_CIDR_Mask
Rtr_PUB_KEY
Rtr_DNS
Rtr_Route
)
export RouterName=""
export RouterInterface=""
export DeviceName=""
export Company=""
export CORP=""
export UserName=""
#========== INTERNAL FUNCTIONS ================================================
#---------- function Info -----------------------------------------------------
#
# With date / time prefix
#
Info()
{
printf "${GREEN}%s ${NC} %s\n" "$( date +%F_%T )" "$*"
}
#---------- function Message --------------------------------------------------
#
# Send to STDOUT
#
function Message()
{
printf "\n${GREEN}[i] ${BLUE}%s${NC}\n" "$*"
}
#---------- ip2int ------------------------------------------------------------
#
function ip2int()
{
local a b c d
{ IFS=. read a b c d; } <<< $1
echo $(((((((a << 8) | b) << 8) | c) << 8) | d))
}
#---------- int2ip ------------------------------------------------------------
#
function int2ip()
{
local ui32=$1; shift
local ip n
for n in 1 2 3 4; do
ip=$((ui32 & 0xff))${ip:+.}$ip
ui32=$((ui32 >> 8))
done
echo $ip
}
#---------- RouterCommand -----------------------------------------------------
#
function RouterConnect()
{
local Command="$"
}
#---------- CreateUser --------------------------------------------------------
#
function CreateUser()
{
local RouterName=$1
local RouterInterface=$2
local UserNumber=$3
local UserName=$4
local debug=0
RouterCfg="${RouterName}.cfg"
#---Read values from config file
for PARAM in "${PARAMS[@]}"
do
eval local ${PARAM}=$(sed -nr "/^\[${RouterName}\]/ { :l /^${PARAM}[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" $RouterCfg)
done
Digits=000
Temp="${Digits}${UserNumber}"
ClientNumPad=$(echo ${Temp:(-${#Digits})})
IFS=. read -r octet1 octet2 octet3 octet4 <<< "$Rtr_Addr_Private"
Subnet="${octet1}.${octet2}.${octet3}"
UserAddress=${Subnet}.${UserNumber}/32
Message "Subnet : $Subnet"
Message "ClientNumPad : $ClientNumPad"
((debug)) && echo -e "
DEBUG - CreateUser
User Number = $1
UserName = $2
UserName = $3
UserAddress = $UserAddress
Rtr_Addr_Public = $Rtr_Addr_Public
Rrt_Port = $Rrt_Port
RouterInterface = $RouterInterface
Rtr_Addr_Private = $Rtr_Addr_Private
Rtr_CIDR_Mask = $Rtr_CIDR_Mask
Rtr_PUB_KEY = $Rtr_PUB_KEY
Subnet = $Subnet
" | column -t && exit
CLIENT_PRIV_KEY=$(wg genkey)
CLIENT_PUB_KEY=$(echo "${CLIENT_PRIV_KEY}" | wg pubkey)
CLIENT_PRE_SHARED_KEY=$(wg genpsk)
ROUTER_PUB_KEY="$RouterPubKey"
CLIENT_FILE_PREFIX="U-${ClientNumPad}-${UserName}"
CLIENT_FILE_WIN="${CLIENT_FILE_PREFIX}.conf"
CLIENT_FILE_RTR="${CLIENT_FILE_PREFIX}.Peer.rsc"
echo -e "\nClient:
${GREEN}---------------------------------------------------------${NC}"
echo -e "[Interface]
PrivateKey = ${CLIENT_PRIV_KEY}
ListenPort = 51821
Address = ${UserAddress}
DNS = 1.1.1.1,8.8.8.8
[Peer]
PublicKey = ${Rtr_PUB_KEY}
PresharedKey = ${CLIENT_PRE_SHARED_KEY}
AllowedIPs = 0.0.0.0/0
Endpoint = ${Rtr_Addr_Public}:${Rrt_Port}
PersistentKeepalive = 25
" | tee "${CLIENT_FILE_WIN}"
echo -e "\nRouter:
${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard peers
add allowed-address=${Subnet}.${UserNumber}/32 disabled=no name=\"${UserName}\" interface=${RouterInterface} \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\"${CLIENT_PUB_KEY}\""| tee "${CLIENT_FILE_RTR}"
Message "QR Code:"
qrencode -t ansiutf8 -l L < "${CLIENT_FILE_WIN}"
qrencode -l L -s 6 -d 225 -o "${CLIENT_FILE_WIN}.png" < "${CLIENT_FILE_WIN}"
Message "Generated User Files:"
ls -1 ${CLIENT_FILE_PREFIX}*
}
#---------- CreateRouter ------------------------------------------------------
#
function CreateRouter()
{
local debug=1
local RouterNum="$1"
local RouterSubnet="$2"
local Corp="$3"
local BaseDir="${BaseDir}/${Corp}" # BaseDir global variable
local WgRtrDir="${BaseDir}/routers"
#---Create paths if not there
[ ! -d "$WgRtrDir" ] && mkdir -p "${WgRtrDir}"
RTR_PRIV_KEY=$(wg genkey)
Endpoint_Rtr_PUB_KEY=$(echo "${RTR_PRIV_KEY}" | wg pubkey)
RTR_PRE_SHARED_KEY=$(wg genpsk)
RTR_NUM=$(printf "%03d" $1)
RTR_FILE_PREFIX="${RTR_NUM}-Router"
RTR_FILE_RTR="${WgRtrDir}/${RTR_FILE_PREFIX}_Client.rsc"
RTR_FILE_RTR_ENDPOINT="${WgRtrDir}/${RTR_FILE_PREFIX}_Endpoint.rsc"
((debug)) && echo -e "
Corp = $Corp
RTR_NUM = $RTR_NUM
CLIENT_FILE_RTR = $RTR_FILE_RTR
BaseDir = $BaseDir
PreShared Key = $RTR_PRE_SHARED_KEY
" && exit
[ -d "${BaseDir}" ] && Message "Creating dir ${BaseDir}" && mkdir -p "${BaseDir}"
Message "Generated output files:"
echo -e "${GREEN}---------------------------------------------------------${NC}
${RTR_FILE_RTR}
${RTR_FILE_RTR_ENDPOINT}
"
Message "Client Router Config:"
echo -e "${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard
add listen-port=13239 mtu=1420 name=wg01 private-key=\"${RTR_PRIV_KEY}\"
/ip address add address=172.18.1.${RouterNum}/32 comment=wg-wg01 interface=wg01
/interface wireguard peers add allowed-address=172.16.18.254 client-keepalive=10 disabled=no comment=\"CCR1 Montreal\" interface=wg01 \\
endpoint-address=${Endpoint_Rtr_Addr_Public} endpoint-port=${Endpoint_Rrt_Port} preshared-key=\"${RTR_PRE_SHARED_KEY}\" public-key=\"${Endpoint_Rtr_PUB_KEY}\"
/system script add dont-require-permissions=no name=ping-CCR1 owner=admin policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source=\\
\"/ping interval=10 10.1.8.11 count=61\"
/system/scheduler add interval=10m name=Ping-CCR1 on-event=\"/system/script/run ping-CCR1\" policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon start-date=apr/02/2022 start-time=12:00:00 " \
| tee "${RTR_FILE_RTR}"
#echo -e "\n"
Message "${EndpointID} endpoint Config:"
echo -e "${GREEN}---------------------------------------------------------${NC}"
echo -e "/interface wireguard peers add allowed-address=10.1.41.${RouterNum}/32,${RouterSubnet} disabled=no comment=\"Router ${RouterNum} ${NameRouter}\" \\
interface=WG-Routers preshared-key=\"${RTR_PRE_SHARED_KEY}\" public-key=\"${Endpoint_Rtr_PUB_KEY}\"
/ip route add dst-address=${RouterSubnet} gateway=10.1.41.${RouterNum}" \
| tee "${RTR_FILE_RTR_ENDPOINT}"
}
#---------- GetRouter_Infos ----------------------------------------------------
#
function GetRouter_Infos()
{
local RouterName="$1"
local IniFile="${1}.cfg"
local debug=0
((debug)) && echo -e "\nIniFile = ${IniFile}\n"
#read -p "Entrer l'interface du router: " RouterInterface
echo -e "[${RouterName}]" >> ${IniFile}
for PARAM in "${PARAMS[@]}"
do
echo -e "\nPARAM = $PARAM"
eval 'read -p "Entrer ${PARAM} " Value'
eval 'echo ${PARAM}=${Value} >> ${IniFile}'
done
((debug)) && echo "${FUNCNAME[0]} exit"
}
#---------- Help ---------------------------------------------------------------
#
function Help() {
cat << EOF
usage: $(basename "$0") [OPTIONS]
-a Debug mode
-d Device Name
-h Show this message
-i Interactive
-u User Name
-n User / Device number
EOF
}
#================= MAIN =======================================================
#
((!$#)) && Help && exit
while getopts ad:hi:n:qu: option
do
case "${option}" in
a) debug=1
;;
d) DeviceName="${OPTARG}"
;;
h) Help
exit
;;
i) Interactive
exit
;;
n) UserNumber="${OPTARG}"
;;
u) UserName="${OPTARG}"
;;
*) Message "Usage (bad argument: $OPTARG)"
exit 1
;;
esac
done
#---Init global variables
#for PARAM in "${PARAMS[@]}"
#do
# eval export '${PARAM}=""'
# done
if [[ ! -z ${UserName} ]] # User mode prioritised if both specified
then
ScriptMode=User
Message "User mode"
elif [[ ! -z ${DeviceName} ]]
then
ScriptMode=Device
Message "Device mode"
else
Message "Must use either -u or -d"
exit
fi
CfgNum=$(find . -maxdepth 1 -iname "*.cfg" |wc -l)
Message "Avant demande router infos"
if [[ $CfgNum -eq 1 ]]
then
RouterCfg=$(find . -maxdepth 1 -iname "*.cfg" -printf "%f")
RouterName="${RouterCfg%.*}"
else
read -p "Entrer Nom du Router: " RouterName
((debug)) && echo -e "Router Name = ${RouterName}"
GetRouter_Infos "${RouterName}"
RouterCfg=${RouterName}.cfg
fi
((debug)) && echo -e "
Après GetRouter_Infos
RouterName : $RouterName
RouterInterface : $RouterInterface
"
for PARAM in "${PARAMS[@]}"
do
eval ${PARAM}=$(sed -nr "/^\[${RouterName}\]/ { :l /^${PARAM}[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" $RouterCfg)
done
echo -e "Avant Create User"
((debug)) && echo -e "
RouterName = $RouterName
DeviceName = $DeviceName
UserNumber = $UserNumber
UserName = $UserName
Rtr_Addr_Admin = $Rtr_Addr_Admin
Rtr_Addr_Public = $Rtr_Addr_Public
Rrt_Port = $Rrt_Port
RtrInterface = $RtrInterface
Rtr_Addr_Private = $Rtr_Addr_Private
Rtr_CIDR_Mask = $Rtr_CIDR_Mask
Rtr_PUB_KEY = $Rtr_PUB_KEY
" | column -t && exit
case "${ScriptMode}" in
User) CreateUser ${RouterName} ${RtrInterface} ${UserNumber} ${UserName}
exit
;;
Router) CreateRouter ${RouterName} ${UserNumber} ${DeviceName}
;;
*) Message "Bad mode passed ${ScriptMode}"
exit 1
;;
esac
Message "All done."

View file

@ -1,34 +0,0 @@
1) Le script fonctionne en partant du principe qu'il va sauver / utiliser un fichier INI et les fichiers Wireguard générés en relation avec ça dans un répertoire
Ça veut dire qu'on doit utiliser quelque chose qui ressemble à:
Compagnie / router1
Compagnie / router2
Donc, on fait un "cd" Compagnie/router1 et on utilise de là
On pourrait aussi avoir: Compagnie / router1 / interface 1 (j'ai la plupart du temps WG_Users et WG_Routers!)
2) Les paramètres sont contenus dans un array au début du script. Je vais ajouter un champs sur chaque ligne pour un "nom de field" plus facile à comprendre
PARAMS=(
RtrInterface Nom de l'interface Wireguard avec laquelle sera associée la config du client
Rtr_Addr_Admin L'adresse IP où le script va connecter pour ajouter la config du client (futur)
Rtr_Addr_Public L'adresse publique sur laquelle le client connecte: IP ou FQDN
Rrt_Port Le port de l'interface associée du router sur lequel le client connecte
Rtr_Addr_Private L'adresse du router, sur le subnet alloué au clients. Mon standard, genre: 10.1.2.254 et le client #1 aura 10.1.2.1, client #2 10.1.2.2, etc
Rtr_CIDR_Mask Le masque du subnet associé à l'interface du router sur son interface
Rtr_PUB_KEY La clef publique associée à l'interface du router
Rtr_DNS Le/les DNS qu'on place dans la config du client
Rtr_Route_Subnet Le subnet qui est associé au routage pour la connexion client. 0.0.0.0/0 pour envoyer tout le trafic via cette connexion wireguard.
)
3) Je conseille d'utiliser des noms de user et routers avec un # de séquence associé. Ça permet de savoir quel IP sera allouée à chaque client
Ex: U001-Guy, U002-Marc (Users)
R001-Toronto, R002-Quebec (Routers)
4) Les paramètres de la CLI on beaucoup changé avec la dernière version, voir la manière actuelle dans l'exemple ci-bas
## Utilisation
~~~bash
# Pour l'instant, minimal (autres paramètres = futur):
../genconfig_simple -n 1 -u marc
~~~

View file

@ -1,37 +0,0 @@
#!/bin/bash
---ini file parameters list
unset PARAMS;
PARAMS=(
"RtrInterface;Interface Router"
"Rtr_Addr_Admin;Router Adresse Admin"
"Rtr_Addr_Public;Router Adresse Publique"
"Rrt_Port;Router IP Port"
"Rtr_Addr_Private;Router Adresse Privee"
"Rtr_CIDR_Mask;Router Adresse Privee CIDR Mask"
"Rtr_PUB_KEY;Router Public Key"
"Rtr_DNS;Clients DNS"
"Rtr_Route;Clients Route"
)
for PARAM in "${PARAMS[@]}"
do
Parameter=$(echo "$PARAM" | cut -f1 -d\;)
Description=$(echo "$PARAM" | cut -f2 -d\;)
echo -e "\n${Description} = ${Parameter}"
#eval 'read -p "Entrer ${PARAM} " Value'
#eval 'echo ${PARAM}=${Value} >> ${IniFile}'
done
exit
for PARAM in "${PARAMS[@]}"
do
eval ${PARAM}=$(sed -nr "/^\[${RouterName}\]/ { :l /^${PARAM}[ ]*=/ { s/[^=]*=[ ]*//; p; q;}; n; b l;}" $RouterCfg)
done

View file

@ -1,30 +0,0 @@
#!/bin/bash
#---ini file parameters
unset PARAMS;
PARAMS=(
'Rtr_Addr_Public,Router Adresse Publique'
'Rrt_Port,Router Port'
'Rtr_Addr_Private,Router Adresse Privee'
'Rtr_CIDR_Mask,Router Private CIDR Mask'
'Rtr_PUB_KEY,Router Public Key'
)
for PARAM in "${PARAMS[@]}"
do
{ IFS=, read Param Desc; } <<< ${PARAM}
read -p "Entrer ${Desc} : " Value
eval ${Param}="${Value}"
done
echo -e "\n"
echo -e "
Rtr_Addr_Public = $Rtr_Addr_Public
Rrt_Port = $Rrt_Port
Rtr_Addr_Private = $Rtr_Addr_Private
Rtr_CIDR_Private = $Rtr_CIDR_Mask
Rtr_PUB_KEY = $Rtr_PUB_KEY
" | column -t

View file

@ -1,3 +0,0 @@
/ip address add address=172.14.40.004/32 comment=WG-CTG interface=wg-ctg
/interface wireguard peers add allowed-address=172.16.254.004/32 client-keepalive=10 disabled=no comment="2" \
interface=WG-Devices preshared-key="efrLuDEVeDNpj13qlIqbjCiKlPVxE8T+hLt+2gQHF40=" public-key="lRlZ5uUBQsCH4G259f+q2yKAH4rxc2y+KHDlHaksmwo="

View file

@ -1,316 +0,0 @@
#!/bin/bash
#=================== Environment ===============================================
#
ScriptName=$(basename "$0")
SshUser=ansible
#SshKey="/home/wireguard/.ssh/ansible_evoq_rsa"
SshKey="/home/boig01/.ssh/ansible_evoq_rsa"
#BaseDir="/home/wireguard"
BaseDir="/dev/shm"
CCR1=10.1.8.11
CCR2=10.1.8.12
Version=240222_1842
CORP="EVOQ"
TmpUserList=$(mktemp -p /dev/shm)
# Wireguard For Routers
RtrCCR1Int=WG-Routers
RtrCCR1PubKey="9au45IDNJhHDNtN+LIpJDyMFTEYdN9WOSSHEJS8WRmw="
RtrCCR1Prefix="10.1.32"
RtrCCR1Address="10.1.32.254/24"
RtrCCR1Port=13232
WgRtrDir="${BaseDir}/routers"
# Wireguard For Users
UsrCCR1Int=WG-Users
UsrCCR1PubKey="EsxauwYNBotyfDJzy9yCUXDci2gHbtZLhUWnMgMP0AY="
UsrCCR1Prefix="10.1.33"
UsrCCR1Address="10.1.33.254/24"
UsrCCR1Port=13233
WgUsrDir="${BaseDir}/users"
YELLOW='\033[0;33«m'
GREEN='\033[0;32m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Create paths if not there
[ ! -d "$WgRtrDir" ] && mkdir -p "${WgRtrDir}"
[ ! -d "$WgUsrDir" ] && mkdir -p "${WgUsrDir}"
#=================== function Info =============================================
#
# Avec date / time prefix
#
Info() { printf "${GREEN} %s ${NC} %s\n" "$( date +%F_%T )" "$*" >&2; } # send to stderr
#=================== function Message ==========================================
#
Message() { printf "${GREEN}%s ${NC}\n" "$*" ;} # send to stderr
#=================== function Help =============================================
#
function Help ()
{
echo -e "
usage: $ScriptName [options]
-l List WireGuard clients on CCR1
-h This help
"
}
#=================== function addCCR1 ==========================================
#
function addCCR1() {
local Router="$1"
echo -e "\nAdding ${Router} Wireguard account to CCR1..."
ssh -i ${SSHKey} ansible@${CCR1} "/ppp secret add local-address=10.1.31.254 name=${Router} password=${L2TPPass} remote-address=${CCRSideIP} routes=\"${ip_Subnet} $CCRSideIP 1\" service=l2tp"
if [ $? = 0 ]
then
echo "${Router} Wireguard account successfully added to CCR1"
else
echo "Failed to add ${Router} Wireguard account to CCR1"
fi
}
#=================== function newClient =======================================
#
function newClient() {
ENDPOINT="${SERVER_PUB_IP}:${SERVER_PORT}"
echo ""
echo "Tell me a name for the client."
echo "The name must consist of alphanumeric character. It may also include an underscore or a dash and can't exceed 15 chars."
until [[ ${CLIENT_NAME} =~ ^[a-zA-Z0-9_-]+$ && ${CLIENT_EXISTS} == '0' && ${#CLIENT_NAME} -lt 16 ]]; do
read -rp "Client name: " -e CLIENT_NAME
CLIENT_EXISTS=$(grep -c -E "^### Client ${CLIENT_NAME}\$" "$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf")
if [[ ${CLIENT_EXISTS} == '1' ]]; then
echo ""
echo "A client with the specified name was already created, please choose another name."
echo ""
fi
done
for DOT_IP in {2..254}; do
DOT_EXISTS=$(grep -c "${SERVER_WG_IPV4::-1}${DOT_IP}" "$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf")
if [[ ${DOT_EXISTS} == '0' ]]; then
break
fi
done
if [[ ${DOT_EXISTS} == '1' ]]; then
echo ""
echo "The subnet configured supports only 253 clients."
exit 99
fi
BASE_IP=$(echo "$SERVER_WG_IPV4" | awk -F '.' '{ print $1"."$2"."$3 }')
until [[ ${IPV4_EXISTS} == '0' ]]; do
read -rp "Client's WireGuard IPv4: ${BASE_IP}." -e -i "${DOT_IP}" DOT_IP
CLIENT_WG_IPV4="${BASE_IP}.${DOT_IP}"
IPV4_EXISTS=$(grep -c "$CLIENT_WG_IPV4/24" "$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf")
if [[ ${IPV4_EXISTS} == '1' ]]; then
echo ""
echo "A client with the specified IPv4 was already created, please choose another IPv4."
echo ""
fi
done
BASE_IP=$(echo "$SERVER_WG_IPV6" | awk -F '::' '{ print $1 }')
until [[ ${IPV6_EXISTS} == '0' ]]; do
read -rp "Client's WireGuard IPv6: ${BASE_IP}::" -e -i "${DOT_IP}" DOT_IP
CLIENT_WG_IPV6="${BASE_IP}::${DOT_IP}"
IPV6_EXISTS=$(grep -c "${CLIENT_WG_IPV6}/64" "$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf")
if [[ ${IPV6_EXISTS} == '1' ]]; then
echo ""
echo "A client with the specified IPv6 was already created, please choose another IPv6."
echo ""
fi
done
# Generate key pair for the client
CLIENT_PRIV_KEY=$(wg genkey)
CLIENT_PUB_KEY=$(echo "${CLIENT_PRIV_KEY}" | wg pubkey)
CLIENT_PRE_SHARED_KEY=$(wg genpsk)
mkdir -p "$(pwd)/wireguard/${SERVER_WG_NIC}/client/${CLIENT_NAME}" >/dev/null 2>&1
HOME_DIR="$(pwd)/wireguard/${SERVER_WG_NIC}/client/${CLIENT_NAME}"
# Create client file and add the server as a peer
echo "[Interface]
PrivateKey = ${CLIENT_PRIV_KEY}
Address = ${CLIENT_WG_IPV4}/32,${CLIENT_WG_IPV6}/128
DNS = ${CLIENT_DNS_1},${CLIENT_DNS_2}
[Peer]
PublicKey = ${SERVER_PUB_KEY}
PresharedKey = ${CLIENT_PRE_SHARED_KEY}
Endpoint = ${ENDPOINT}
AllowedIPs = 0.0.0.0/0,::/0" >>"${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.conf"
# Add the client as a peer to the MikroTik (to client folder)
echo "# WireGuard client peer configure
/interface wireguard peers
add allowed-address=${CLIENT_WG_IPV4}/32 comment=\\
${SERVER_WG_NIC}-client-${CLIENT_NAME} interface=${SERVER_WG_NIC} \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\\
\"${CLIENT_PUB_KEY}\"
" >"${HOME_DIR}/mikrotik-peer-${SERVER_WG_NIC}-client-${CLIENT_NAME}.rsc"
# Add the client as a peer to the MikroTik
echo "# WireGuard client peer configure
/interface wireguard peers
add allowed-address=${CLIENT_WG_IPV4}/32 comment=\\
${SERVER_WG_NIC}-client-${CLIENT_NAME} interface=${SERVER_WG_NIC} \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\\
\"${CLIENT_PUB_KEY}\"
" >> "$(pwd)/wireguard/${SERVER_WG_NIC}/mikrotik/${SERVER_WG_NIC}.rsc"
# Add the client as a peer to the server
echo -e "\n### Client ${CLIENT_NAME}
[Peer]
PublicKey = ${CLIENT_PUB_KEY}
PresharedKey = ${CLIENT_PRE_SHARED_KEY}
AllowedIPs = ${CLIENT_WG_IPV4}/32,${CLIENT_WG_IPV6}/128" >>"$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf"
echo -e "\nHere is your client config file as a QR Code:"
qrencode -t ansiutf8 -l L <"${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.conf"
qrencode -l L -s 6 -d 225 -o "${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.png" <"${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.conf"
echo -e "${INFO} Config available in ${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.conf"
echo -e "${INFO} QR is also available in ${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.png"
echo -e "${INFO} MikroTik peer config available in ${HOME_DIR}/mikrotik-${SERVER_WG_NIC}-client-${CLIENT_NAME}.rsc"
}
#=================== function manageMenu ======================================
#
function manageMenu() {
echo ""
echo "It looks like this WireGuard interface is already."
echo ""
echo "What do you want to do?"
echo " 1) Add a new client"
echo " 2) Exit"
until [[ ${MENU_OPTION} =~ ^[1-4]$ ]]; do
read -rp "Select an option [1-2]: " MENU_OPTION
done
case "${MENU_OPTION}" in
1)
newClient
;;
2)
exit 0
;;
esac
}
#=================== function listConfs =======================================
#
function listConfs() {
local directory
directory="$(pwd)/wireguard"
if [ -d "${directory}" ]; then
echo "List of existing configurations:"
i=1
for folder in "${directory}"/*/; do
local users count folder_name
users="${folder}/client/"
count=$(find "$users" -maxdepth 1 -mindepth 1 -type d 2>/dev/null | wc -l)
folder_name=$(basename "${folder}")
echo "${i}. ${folder_name} [${count} user(s)]"
((i++))
done
fi
echo ""
}
#=================== function listCCR1 =========================================
#
# Filter 1: enlever les ";" et remplacer ^m par LF
# Filter 2: Grouper 2 lignes consecutives
# Filter 3: Print field #4 et #3
#
function ListCCR() {
Message "User List"
ssh -i $SshKey ${SshUser}@${CCR1} "/interface/wireguard/peers/print proplist=comment,interface" \
| grep User | tr -d ";" | sed -e "s/\r//g" \
| awk 'NR%2 {printf("%s ", $0); next} {print $0}' \
| awk '{print $4, $3}' | tee ${TmpUserList}
LastEntry=$(cat ${TmpUserList} | sort -r | head -1 | awk '{ print $1 }')
NextEntry=$(($LastEntry+1))
echo -e "
Last Entry = $LastEntry
Next Entry = $NextEntry
"
}
#=================== MAIN =====================================================
#
echo -e "\nWireGuard-MikroTik ${BLUE}${CORP}${NC} configurator\n"
((!$#)) && Help && exit
while getopts cfhl option
do
case "${option}" in
c) BoolCreate=1 ;;
f) VarFileLog=1;;
h) Help
exit 0;;
l) ListCCR ;;
*) Help
exit 1;;
esac
done
rm -f ${TmpUserList}
exit
#? Check for root, OS, WireGuard
installCheck
listConfs
#? Check server exist
serverName
#? Check if WireGuard is already installed and load params
if [[ -e $(pwd)/wireguard/${SERVER_WG_NIC}/params ]]; then
# shellcheck source=/dev/null
source "$(pwd)/wireguard/${SERVER_WG_NIC}/params"
manageMenu
else
newInterface
fi

View file

@ -1,111 +0,0 @@
inférence
WG-Users
========
Public Key: cat4H07058+1VLQu2ns9tWGImfMx0hrHZI6F9WTsFR8=
Win10 10.100.100.100 Elair-Riverra661
/interface/wireguard/peers/add allowed-address=10.100.99.101 interface=WG-Users persistent-keepalive=10 public-key=
https://github.com/IgorKha/wireguard-mikrotik
[i] Config available in /home/boig01/temp/wireguard/wg01/client/Laptop/wg01-client-Laptop.conf
[i] QR is also available in /home/boig01/temp/wireguard/wg01/client/Laptop/wg01-client-Laptop.png
[i] MikroTik peer config available in /home/boig01/temp/wireguard/wg01/client/Laptop/mikrotik-wg01-client-Laptop.rsc
[i] MikroTik interface config available in /home/boig01/temp/wireguard/wg01/mikrotik/wg01.rsc
[i] If you want to add more clients, you simply need to run this script another time!
mikrotik/wg01.rsc
=================
# WireGuard interface configure
/interface wireguard
add listen-port=13231 mtu=1420 name=wg01 private-key=\
"mHAePE+zX9qDM9VyN0PZ5wolk3RY7c+dZgAsOdvw/HA="
/ip firewall filter
add action=accept chain=input comment=wg-wg01 dst-port=13231 protocol=udp
/ip firewall filter move [/ip firewall filter find comment=wg-wg01] 1
/ip address
add address=10.100.99.1/24 comment=wg-wg01 interface=wg01
# WireGuard client peer configure
/interface wireguard peers
add allowed-address=10.100.99.2/32 comment=\
wg01-client-Laptop interface=wg01 \
preshared-key="6V1dSygIB9cfq//EKLZmVl4qLVmKgHAqqeGQt84uvqY=" public-key=\
"gwi0ou0D2fWFcB1WNcarGHUu31DG1InGu39EryMnSGc="
client/Laptop/wg01-client-Laptop.conf
=====================================
[Interface]
PrivateKey = YJ+4MBqJj/uoJFatfkh5yDghJUDmigKhxiT50vMSP0A=
Address = 10.100.99.2/32,fd42:55:24::2/128
DNS = 1.1.1.1,8.8.8.8
[Peer]
PublicKey = Oe03xZcw+Fj0s2WwLTyg7mW7bm0p7gwKFnoNWXbciE8=
PresharedKey = 6V1dSygIB9cfq//EKLZmVl4qLVmKgHAqqeGQt84uvqY=
Endpoint = 172.16.16.136:13231
AllowedIPs = 0.0.0.0/0,::/0
CLIENT_PRIV_KEY=$(wg genkey)
CLIENT_PUB_KEY=$(echo "${CLIENT_PRIV_KEY}" | wg pubkey)
CLIENT_PRE_SHARED_KEY=$(wg genpsk)
echo -e "CLIENT_PUB_KEY: $CLIENT_PUB_KEY \nCLIENT_PRE_SHARED_KEY: $CLIENT_PRE_SHARED_KEY"
echo "[Interface]
PrivateKey = ${CLIENT_PRIV_KEY}
Address = ${CLIENT_WG_IPV4}/32,${CLIENT_WG_IPV6}/128
DNS = ${CLIENT_DNS_1},${CLIENT_DNS_2}
[Peer]
PublicKey = ${SERVER_PUB_KEY}
PresharedKey = ${CLIENT_PRE_SHARED_KEY}
Endpoint = ${ENDPOINT}
AllowedIPs = 0.0.0.0/0,::/0" >>"${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.conf"
# Add the client as a peer to the MikroTik (to client folder)
echo "# WireGuard client peer configure
/interface wireguard peers
add allowed-address=${CLIENT_WG_IPV4}/32 comment=\\
${SERVER_WG_NIC}-client-${CLIENT_NAME} interface=${SERVER_WG_NIC} \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\\
\"${CLIENT_PUB_KEY}\"
" >"${HOME_DIR}/mikrotik-peer-${SERVER_WG_NIC}-client-${CLIENT_NAME}.rsc"
# Add the client as a peer to the MikroTik
echo "# WireGuard client peer configure
/interface wireguard peers
add allowed-address=${CLIENT_WG_IPV4}/32 comment=\\
${SERVER_WG_NIC}-client-${CLIENT_NAME} interface=${SERVER_WG_NIC} \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\\
\"${CLIENT_PUB_KEY}\"
" >> "$(pwd)/wireguard/${SERVER_WG_NIC}/mikrotik/${SERVER_WG_NIC}.rsc"

View file

@ -1,477 +0,0 @@
#!/usr/bin/env bash
BLUE='\033[0;34m'
NC='\033[0m'
INFO="${BLUE}[i]${NC}"
function checkOS() {
#? Check OS version
if [[ -e /etc/debian_version ]]; then
# shellcheck source=/dev/null
source /etc/os-release
OS="${ID}" # debian or ubuntu
if [[ ${ID} == "debian" || ${ID} == "raspbian" ]]; then
if [[ ${VERSION_ID} -lt 10 ]]; then
echo "Your version of Debian (${VERSION_ID}) is not supported. Please use Debian 10 Buster or later"
exit 95
fi
OS=debian #* overwrite if raspbian
fi
elif [[ -e /etc/fedora-release ]]; then
# shellcheck source=/dev/null
source /etc/os-release
OS="${ID}"
elif [[ -e /etc/centos-release ]]; then
# shellcheck source=/dev/null
source /etc/os-release
OS=centos
elif [[ -e /etc/oracle-release ]]; then
# shellcheck source=/dev/null
source /etc/os-release
OS=oracle
elif [[ -e /etc/arch-release ]]; then
OS=arch
elif [[ "$(uname -s)" == "Darwin" ]]; then
OS=macos
else
echo "Looks like you aren't running this installer on a Debian, Ubuntu, Fedora, CentOS, Oracle or Arch Linux system"
exit 95
fi
export OS
}
function installWireGuard() {
#? Check root user
if [[ "${EUID}" -ne 0 ]] && [[ "${OS}" != "macos" ]]; then
echo ""
echo "You need to run this script as root"
echo ""
exit 13
fi
#? Install WireGuard tools and module
if [[ ${OS} == 'ubuntu' ]] || [[ ${OS} == 'debian' && ${VERSION_ID} -gt 10 ]]; then
apt-get update
apt-get install -y wireguard qrencode
elif [[ ${OS} == 'debian' ]]; then
if ! grep -rqs "^deb .* buster-backports" /etc/apt/; then
echo "deb http://deb.debian.org/debian buster-backports main" >/etc/apt/sources.list.d/backports.list
apt-get update
fi
apt update
apt-get install -y qrencode
apt-get install -y -t buster-backports wireguard
elif [[ ${OS} == 'fedora' ]]; then
if [[ ${VERSION_ID} -lt 32 ]]; then
dnf install -y dnf-plugins-core
dnf copr enable -y jdoss/wireguard
dnf install -y wireguard-dkms
fi
dnf install -y wireguard-tools qrencode
elif [[ ${OS} == 'centos' ]]; then
yum -y install epel-release elrepo-release
if [[ ${VERSION_ID} -eq 7 ]]; then
yum -y install yum-plugin-elrepo
fi
yum -y install kmod-wireguard wireguard-tools qrencode
elif [[ ${OS} == 'oracle' ]]; then
https://www.dataroma.com/m/m_activity.php?m=GC&typ=b dnf install -y oraclelinux-developer-release-el8
dnf config-manager --disable -y ol8_developer
dnf config-manager --enable -y ol8_developer_UEKR6
dnf config-manager --save -y --setopt=ol8_developer_UEKR6.includepkgs='wireguard-tools*'
dnf install -y wireguard-tools qrencode
elif [[ ${OS} == 'arch' ]]; then
pacman -Sq --needed --noconfirm wireguard-tools qrencode
elif [[ ${OS} == 'macos' ]]; then
if ! command -v brew &> /dev/null
then
echo ""
echo "Brew is not installed. Please install it and run this script again."
echo "https://brew.sh/"
exit 1
fi
brew install wireguard-tools qrencode
fi
echo ""
echo "The installation is complete. Now you need to re-run the script with user access rights (not root)."
echo ""
exit 0
}
function installCheck() {
if ! command -v wg &> /dev/null
then
echo "You must have \"wireguard-tools\" and \"qrencode\" installed."
read -n1 -r -p "Press any key to continue and install needed packages..."
installWireGuard
fi
}
function serverName() {
until [[ ${SERVER_WG_NIC} =~ ^[a-zA-Z0-9_]+$ && ${#SERVER_WG_NIC} -lt 16 ]]; do
echo "Tell me a name for the server WireGuard interface. ('wg0' is used by default)"
read -rp "WireGuard interface name (server name): " -e SERVER_WG_NIC
SERVER_WG_NIC=${SERVER_WG_NIC:-wg0}
done
}
function installQuestions() {
echo "I need to ask you a few questions before starting the setup."
echo "You can leave the default options and just press enter if you are ok with them."
echo ""
# Detect public IPv4 or IPv6 address and pre-fill for the user
SERVER_PUB_IP=$(host myip.opendns.com resolver1.opendns.com | grep -oE 'has address [0-9.]+' | cut -d ' ' -f3)
echo "Your public IPv4 address is ${SERVER_PUB_IP}"
if [[ -z ${SERVER_PUB_IP} ]]; then
# Detect public IPv6 address
if [[ ${OS} == "macos" ]]; then
# Detect public IPv6 address on macOS
SERVER_PUB_IP=$(ifconfig | grep -A4 'en0:' | grep 'inet6' | awk '{print $2}')
else
# Detect public IPv6 address on Linux
SERVER_PUB_IP=$(ip -6 addr | sed -ne 's|^.* inet6 \([^/]*\)/.* scope global.*$|\1|p' | head -1)
fi
fi
# while true; do
# read -rp "Enter IPv4 or IPv6 public address: " -e -i "${SERVER_PUB_IP}" SERVER_PUB_IP
while true; do
read -rp "Enter IPv4 or IPv6 public address [default used ${SERVER_PUB_IP}]: " -e USER_INPUT_SERVER_PUB_IP
SERVER_PUB_IP=${USER_INPUT_SERVER_PUB_IP:-$SERVER_PUB_IP}
if [[ ${SERVER_PUB_IP} =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
break
elif [[ ${SERVER_PUB_IP} =~ ^[0-9a-fA-F:]+:[0-9a-fA-F:]*$ ]]; then
SERVER_PUB_IP="[${SERVER_PUB_IP}]"
break
else
echo "Invalid IP address. Please enter a valid IPv4 or IPv6 address."
fi
done
until [[ ${SERVER_WG_IPV4} =~ ^([0-9]{1,3}\.){3} ]]; do
# read -rp "Server's WireGuard IPv4: " -e -i 10."$(shuf -i 0-250 -n 1)"."$(shuf -i 0-250 -n 1)".1 SERVER_WG_IPV4
if [[ ${OS} == "macos" ]]; then
SERVER_WG_IPV4="10.$(jot -r 1 0 250).$(jot -r 1 0 250).1"
read -rp "Server's WireGuard IPv4 [default used ${SERVER_WG_IPV4}]: " -e USER_INPUT_SERVER_WG_IPV4
SERVER_WG_IPV4=${USER_INPUT_SERVER_WG_IPV4:-$SERVER_WG_IPV4}
else
read -rp "Server's WireGuard IPv4: " -e -i 10."$(shuf -i 0-250 -n 1)"."$(shuf -i 0-250 -n 1)".1 SERVER_WG_IPV4
fi
done
until [[ ${SERVER_WG_IPV6} =~ ^([a-f0-9]{1,4}:){3,4}: ]]; do
# read -rp "Server's WireGuard IPv6: " -e -i fd42:"$(shuf -i 10-90 -n 1)":"$(shuf -i 10-90 -n 1)"::1 SERVER_WG_IPV6
if [[ ${OS} == 'macos' ]]; then
SERVER_WG_IPV6="fd42:$(jot -r 1 10 90):$(jot -r 1 10 90)::1"
read -rp "Server's WireGuard IPv6 [default used ${SERVER_WG_IPV6}]: " -e USER_INPUT_SERVER_WG_IPV6
SERVER_WG_IPV6=${USER_INPUT_SERVER_WG_IPV6:-$SERVER_WG_IPV6}
else
read -rp "Server's WireGuard IPv6: " -e -i fd42:"$(shuf -i 10-90 -n 1)":"$(shuf -i 10-90 -n 1)"::1 SERVER_WG_IPV6
fi
done
# Generate random number within private ports range
RANDOM_PORT=$(shuf -i 49152-65535 -n1)
until [[ ${SERVER_PORT} =~ ^[0-9]+$ ]] && [ "${SERVER_PORT}" -ge 1 ] && [ "${SERVER_PORT}" -le 65535 ]; do
# read -rp "Server's WireGuard port [1-65535]: " -e -i "${RANDOM_PORT}" SERVER_PORT
if [[ ${OS} == 'macos' ]]; then
read -rp "Server's WireGuard port [1-65535] [default ${RANDOM_PORT}]: " -e USER_INPUT_SERVER_PORT
SERVER_PORT=${USER_INPUT_SERVER_PORT:-$RANDOM_PORT}
else
read -rp "Server's WireGuard port [1-65535]: " -e -i "${RANDOM_PORT}" SERVER_PORT
fi
done
# Adguard DNS by default
until [[ ${CLIENT_DNS_1} =~ ^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$ ]]; do
# read -rp "First DNS resolver to use for the clients: " -e -i 94.140.14.14 CLIENT_DNS_1
if [[ ${OS} == 'macos' ]]; then
CLIENT_DNS_1='94.140.14.14'
read -rp "First DNS resolver to use for the clients [default ${CLIENT_DNS_1}]: " -e USER_INPUT_CLIENT_DNS_1
CLIENT_DNS_1=${USER_INPUT_CLIENT_DNS_1:-$CLIENT_DNS_1}
else
read -rp "First DNS resolver to use for the clients: " -e -i 94.140.14.14 CLIENT_DNS_1
fi
done
until [[ ${CLIENT_DNS_2} =~ ^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$ ]]; do
if [[ ${OS} == 'macos' ]]; then
CLIENT_DNS_DEF_2='94.140.15.15'
read -rp "Second DNS resolver to use for the clients (optional) [default ${CLIENT_DNS_DEF_2}]: " -e USER_INPUT_CLIENT_DNS_2
CLIENT_DNS_2=${USER_INPUT_CLIENT_DNS_2:-$CLIENT_DNS_DEF_2}
else
read -rp "Second DNS resolver to use for the clients (optional): " -e -i 94.140.15.15 CLIENT_DNS_2
if [[ ${CLIENT_DNS_2} == "" ]]; then
CLIENT_DNS_2="${CLIENT_DNS_1}"
fi
fi
done
echo ""
echo "Okay, that was all I needed. We are ready to setup your WireGuard server now."
echo "You will be able to generate a client at the end of the installation."
read -n1 -r -p "Press any key to continue..."
}
function newInterface() {
# Run setup questions first
installQuestions
# Make sure the directory exists (this does not seem the be the case on fedora)
mkdir -p "$(pwd)"/wireguard/"${SERVER_WG_NIC}"/mikrotik >/dev/null 2>&1
SERVER_PRIV_KEY=$(wg genkey)
SERVER_PUB_KEY=$(echo "${SERVER_PRIV_KEY}" | wg pubkey)
# Save WireGuard settings #SERVER_PUB_NIC=${SERVER_PUB_NIC}
echo "SERVER_PUB_IP=${SERVER_PUB_IP}
SERVER_WG_NIC=${SERVER_WG_NIC}
SERVER_WG_IPV4=${SERVER_WG_IPV4}
SERVER_WG_IPV6=${SERVER_WG_IPV6}
SERVER_PORT=${SERVER_PORT}
SERVER_PRIV_KEY=${SERVER_PRIV_KEY}
SERVER_PUB_KEY=${SERVER_PUB_KEY}
CLIENT_DNS_1=${CLIENT_DNS_1}
CLIENT_DNS_2=${CLIENT_DNS_2}" > "$(pwd)/wireguard/${SERVER_WG_NIC}/params"
# Save WireGuard settings to the MikroTik
echo "# WireGuard interface configure
/interface wireguard
add listen-port=${SERVER_PORT} mtu=1420 name=${SERVER_WG_NIC} private-key=\\
\"${SERVER_PRIV_KEY}\"
/ip firewall filter
add action=accept chain=input comment=wg-${SERVER_WG_NIC} dst-port=${SERVER_PORT} protocol=udp
/ip firewall filter move [/ip firewall filter find comment=wg-${SERVER_WG_NIC}] 1
/ip address
add address=${SERVER_WG_IPV4}/24 comment=wg-${SERVER_WG_NIC} interface=${SERVER_WG_NIC}
" > "$(pwd)/wireguard/${SERVER_WG_NIC}/mikrotik/${SERVER_WG_NIC}.rsc"
# Add server interface
echo "[Interface]
Address = ${SERVER_WG_IPV4}/24,${SERVER_WG_IPV6}/64
ListenPort = ${SERVER_PORT}
PrivateKey = ${SERVER_PRIV_KEY}" > "$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf"
newClient
echo -e "${INFO} MikroTik interface config available in $(pwd)/wireguard/${SERVER_WG_NIC}/mikrotik/${SERVER_WG_NIC}.rsc"
echo -e "${INFO} If you want to add more clients, you simply need to run this script another time!"
}
function newClient() {
ENDPOINT="${SERVER_PUB_IP}:${SERVER_PORT}"
echo ""
echo "Tell me a name for the client."
echo "The name must consist of alphanumeric character. It may also include an underscore or a dash and can't exceed 15 chars."
until [[ ${CLIENT_NAME} =~ ^[a-zA-Z0-9_-]+$ && ${CLIENT_EXISTS} == '0' && ${#CLIENT_NAME} -lt 16 ]]; do
read -rp "Client name: " -e CLIENT_NAME
CLIENT_EXISTS=$(grep -c -E "^### Client ${CLIENT_NAME}\$" "$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf")
if [[ ${CLIENT_EXISTS} == '1' ]]; then
echo ""
echo "A client with the specified name was already created, please choose another name."
echo ""
fi
done
for DOT_IP in {2..254}; do
if [[ ${OS} == 'macos' ]]; then
DOT_EXISTS=$(grep -c "$(echo "${SERVER_WG_IPV4}" | rev | cut -c 2- | rev)${DOT_IP}" "$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf")
else
DOT_EXISTS=$(grep -c "${SERVER_WG_IPV4::-1}${DOT_IP}" "$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf")
fi
if [[ ${DOT_EXISTS} == '0' ]]; then
break
fi
done
if [[ ${DOT_EXISTS} == '1' ]]; then
echo ""
echo "The subnet configured supports only 253 clients."
exit 99
fi
BASE_IP=$(echo "$SERVER_WG_IPV4" | awk -F '.' '{ print $1"."$2"."$3 }')
until [[ ${IPV4_EXISTS} == '0' ]]; do
if [[ ${OS} == 'macos' ]]; then
read -rp "Client's WireGuard IPv4 [default used ${BASE_IP}.${DOT_IP}]: " -e USER_INPUT_DOT_IP
DOT_IP=${USER_INPUT_DOT_IP:-$DOT_IP}
else
read -rp "Client's WireGuard IPv4: ${BASE_IP}." -e -i "${DOT_IP}" DOT_IP
fi
CLIENT_WG_IPV4="${BASE_IP}.${DOT_IP}"
IPV4_EXISTS=$(grep -c "$CLIENT_WG_IPV4/24" "$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf")
if [[ ${IPV4_EXISTS} == '1' ]]; then
echo ""
echo "A client with the specified IPv4 was already created, please choose another IPv4."
echo ""
fi
done
BASE_IP=$(echo "$SERVER_WG_IPV6" | awk -F '::' '{ print $1 }')
until [[ ${IPV6_EXISTS} == '0' ]]; do
if [[ ${OS} == 'macos' ]]; then
read -rp "Client's WireGuard IPv6 [default used ${BASE_IP}::${DOT_IP}]: " -e USER_INPUT_DOT_IP
DOT_IP=${USER_INPUT_DOT_IP:-$DOT_IP}
else
read -rp "Client's WireGuard IPv6: ${BASE_IP}::" -e -i "${DOT_IP}" DOT_IP
fi
CLIENT_WG_IPV6="${BASE_IP}::${DOT_IP}"
IPV6_EXISTS=$(grep -c "${CLIENT_WG_IPV6}/64" "$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf")
if [[ ${IPV6_EXISTS} == '1' ]]; then
echo ""
echo "A client with the specified IPv6 was already created, please choose another IPv6."
echo ""
fi
done
# Asking for client's allowed IPs
until [[ ${ALLOWED_IPV4} =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$ ]]; do
if [[ ${OS} == 'macos' ]]; then
ALLOWED_IPV4="0.0.0.0/0"
read -rp "Client's allowed IPv4 [default used ${ALLOWED_IPV4}]: " -e USER_INPUT_ALLOWED_IPV4
ALLOWED_IPV4=${USER_INPUT_ALLOWED_IPV4:-$ALLOWED_IPV4}
else
read -rp "Client's allowed IPv4: " -e -i "0.0.0.0/0" ALLOWED_IPV4
fi
done
until [[ ${ALLOWED_IPV6} =~ ^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(\/((1(1[0-9]|2[0-8]))|([0-9][0-9])|([0-9])))?$ ]]; do
if [[ ${OS} == 'macos' ]]; then
ALLOWED_IPV6="::/0"
read -rp "Client's allowed IPv6 [default used ${ALLOWED_IPV6}]: " -e USER_INPUT_ALLOWED_IPV6
ALLOWED_IPV6=${USER_INPUT_ALLOWED_IPV6:-$ALLOWED_IPV6}
else
read -rp "Client's allowed IPv6: " -e -i "::/0" ALLOWED_IPV6
fi
done
# Generate key pair for the client
CLIENT_PRIV_KEY=$(wg genkey)
CLIENT_PUB_KEY=$(echo "${CLIENT_PRIV_KEY}" | wg pubkey)
CLIENT_PRE_SHARED_KEY=$(wg genpsk)
mkdir -p "$(pwd)/wireguard/${SERVER_WG_NIC}/client/${CLIENT_NAME}" >/dev/null 2>&1
HOME_DIR="$(pwd)/wireguard/${SERVER_WG_NIC}/client/${CLIENT_NAME}"
# Create client file and add the server as a peer
echo "[Interface]
PrivateKey = ${CLIENT_PRIV_KEY}
Address = ${CLIENT_WG_IPV4}/32,${CLIENT_WG_IPV6}/128
DNS = ${CLIENT_DNS_1},${CLIENT_DNS_2}
[Peer]
PublicKey = ${SERVER_PUB_KEY}
PresharedKey = ${CLIENT_PRE_SHARED_KEY}
Endpoint = ${ENDPOINT}
AllowedIPs = ${ALLOWED_IPV4},${ALLOWED_IPV6}" >>"${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.conf"
# Add the client as a peer to the MikroTik (to client folder)
echo "# WireGuard client peer configure
/interface wireguard peers
add allowed-address=${CLIENT_WG_IPV4}/32 comment=\\
${SERVER_WG_NIC}-client-${CLIENT_NAME} interface=${SERVER_WG_NIC} \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\\
\"${CLIENT_PUB_KEY}\"
" >"${HOME_DIR}/mikrotik-peer-${SERVER_WG_NIC}-client-${CLIENT_NAME}.rsc"
# Add the client as a peer to the MikroTik
echo "# WireGuard client peer configure
/interface wireguard peers
add allowed-address=${CLIENT_WG_IPV4}/32 comment=\\
${SERVER_WG_NIC}-client-${CLIENT_NAME} interface=${SERVER_WG_NIC} \\
preshared-key=\"${CLIENT_PRE_SHARED_KEY}\" public-key=\\
\"${CLIENT_PUB_KEY}\"
" >> "$(pwd)/wireguard/${SERVER_WG_NIC}/mikrotik/${SERVER_WG_NIC}.rsc"
# Add the client as a peer to the server
echo -e "\n### Client ${CLIENT_NAME}
[Peer]
PublicKey = ${CLIENT_PUB_KEY}
PresharedKey = ${CLIENT_PRE_SHARED_KEY}
AllowedIPs = ${CLIENT_WG_IPV4}/32,${CLIENT_WG_IPV6}/128" >>"$(pwd)/wireguard/${SERVER_WG_NIC}/${SERVER_WG_NIC}.conf"
echo -e "\nHere is your client config file as a QR Code:"
qrencode -t ansiutf8 -l L <"${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.conf"
qrencode -l L -s 6 -d 225 -o "${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.png" <"${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.conf"
echo -e "${INFO} Config available in ${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.conf"
echo -e "${INFO} QR is also available in ${HOME_DIR}/${SERVER_WG_NIC}-client-${CLIENT_NAME}.png"
echo -e "${INFO} MikroTik peer config available in ${HOME_DIR}/mikrotik-${SERVER_WG_NIC}-client-${CLIENT_NAME}.rsc"
}
function manageMenu() {
echo ""
echo "It looks like this WireGuard interface is already."
echo ""
echo "What do you want to do?"
echo " 1) Add a new client"
echo " 2) Exit"
until [[ ${MENU_OPTION} =~ ^[1-4]$ ]]; do
read -rp "Select an option [1-2]: " MENU_OPTION
done
case "${MENU_OPTION}" in
1)
newClient
;;
2)
exit 0
;;
esac
}
#? List of existing configurations
function listConfs() {
local directory
directory="$(pwd)/wireguard"
if [ -d "${directory}" ]; then
echo "List of existing configurations:"
i=1
for folder in "${directory}"/*/; do
local users count folder_name
users="${folder}/client/"
count=$(find "$users" -maxdepth 1 -mindepth 1 -type d 2>/dev/null | wc -l)
folder_name=$(basename "${folder}")
echo "${i}. ${folder_name} [${count} user(s)]"
((i++))
done
fi
echo ""
}
echo ""
echo "Welcome to WireGuard-MikroTik configurator!"
echo "The git repository is available at: https://github.com/IgorKha/wireguard-mikrotik"
echo ""
#? Check OS
checkOS
echo "Your OS is ${OS}"
#? Check for root, WireGuard
installCheck
listConfs
#? Check server exist
serverName
#? Check if WireGuard is already installed and load params
if [[ -e $(pwd)/wireguard/${SERVER_WG_NIC}/params ]]; then
# shellcheck source=/dev/null
source "$(pwd)/wireguard/${SERVER_WG_NIC}/params"
manageMenu
else
newInterface
fi