wireguard.sh 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. #!/usr/bin/env bash
  2. #
  3. # This is a Shell script for configure and start WireGuard VPN server.
  4. #
  5. # Copyright (C) 2019 Teddysun <[email protected]>
  6. #
  7. # Reference URL:
  8. # https://www.wireguard.com
  9. # https://git.zx2c4.com/WireGuard
  10. trap _exit INT QUIT TERM
  11. _red() {
  12. printf '\033[1;31;31m%b\033[0m' "$1"
  13. }
  14. _green() {
  15. printf '\033[1;31;32m%b\033[0m' "$1"
  16. }
  17. _yellow() {
  18. printf '\033[1;31;33m%b\033[0m' "$1"
  19. }
  20. _printargs() {
  21. printf -- "%s" "[$(date)] "
  22. printf -- "%s" "$1"
  23. printf "\n"
  24. }
  25. _info() {
  26. _printargs "$@"
  27. }
  28. _warn() {
  29. printf -- "%s" "[$(date)] "
  30. _yellow "$1"
  31. printf "\n"
  32. }
  33. _error() {
  34. printf -- "%s" "[$(date)] "
  35. _red "$1"
  36. printf "\n"
  37. exit 2
  38. }
  39. _exit() {
  40. printf "\n"
  41. _red "$0 has been terminated."
  42. printf "\n"
  43. exit 1
  44. }
  45. _exists() {
  46. local cmd="$1"
  47. if eval type type > /dev/null 2>&1; then
  48. eval type "$cmd" > /dev/null 2>&1
  49. elif command > /dev/null 2>&1; then
  50. command -v "$cmd" > /dev/null 2>&1
  51. else
  52. which "$cmd" > /dev/null 2>&1
  53. fi
  54. rt="$?"
  55. return ${rt}
  56. }
  57. _ipv4() {
  58. local ipv4="$( ip addr | egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | \
  59. egrep -v "^192\.168|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-2]\.|^10\.|^127\.|^255\.|^0\." | head -n 1 )"
  60. [ -z "${ipv4}" ] && ipv4="$( wget -qO- -t1 -T2 ipv4.icanhazip.com )"
  61. [ -z "${ipv4}" ] && ipv4="$( wget -qO- -t1 -T2 ipinfo.io/ip )"
  62. printf -- "%s" "${ipv4}"
  63. }
  64. _ipv6() {
  65. local ipv6=""
  66. ipv6="$(wget -qO- -t1 -T2 ipv6.icanhazip.com)"
  67. printf -- "%s" "${ipv6}"
  68. }
  69. _nic() {
  70. local nic=""
  71. nic="$(ip -4 route ls | grep default | grep -Po '(?<=dev )(\S+)' | head -1)"
  72. printf -- "%s" "${nic}"
  73. }
  74. _port() {
  75. local port="$(shuf -i 1024-20480 -n 1)"
  76. while true
  77. do
  78. if _exists "netstat" && netstat -tunlp | grep -w "${port}" > /dev/null 2>&1; then
  79. port="$(shuf -i 1024-20480 -n 1)"
  80. else
  81. break
  82. fi
  83. done
  84. printf -- "%s" "${port}"
  85. }
  86. _os() {
  87. local os=""
  88. [ -f "/etc/debian_version" ] && source /etc/os-release && os="${ID}" && printf -- "%s" "${os}" && return
  89. [ -f "/etc/fedora-release" ] && os="fedora" && printf -- "%s" "${os}" && return
  90. [ -f "/etc/redhat-release" ] && os="centos" && printf -- "%s" "${os}" && return
  91. }
  92. _os_full() {
  93. [ -f /etc/redhat-release ] && awk '{print ($1,$3~/^[0-9]/?$3:$4)}' /etc/redhat-release && return
  94. [ -f /etc/os-release ] && awk -F'[= "]' '/PRETTY_NAME/{print $3,$4,$5}' /etc/os-release && return
  95. [ -f /etc/lsb-release ] && awk -F'[="]+' '/DESCRIPTION/{print $2}' /etc/lsb-release && return
  96. }
  97. _os_ver() {
  98. local main_ver="$( echo $(_os_full) | grep -oE "[0-9.]+")"
  99. printf -- "%s" "${main_ver%%.*}"
  100. }
  101. _error_detect() {
  102. local cmd="$1"
  103. _info "${cmd}"
  104. eval ${cmd} 1> /dev/null
  105. if [ $? -ne 0 ]; then
  106. _error "Execution command (${cmd}) failed, please check it and try again."
  107. fi
  108. }
  109. # Check OS version
  110. check_os() {
  111. _info "Check OS version"
  112. if _exists "virt-what"; then
  113. virt="$(virt-what)"
  114. elif _exists "systemd-detect-virt"; then
  115. virt="$(systemd-detect-virt)"
  116. fi
  117. if [ -n "${virt}" -a "${virt}" = "lxc" ]; then
  118. _error "Virtualization method is LXC, which is not supported."
  119. fi
  120. if [ -n "${virt}" -a "${virt}" = "openvz" ] || [ -d "/proc/vz" ]; then
  121. _error "Virtualization method is OpenVZ, which is not supported."
  122. fi
  123. [ -z "$(_os)" ] && _error "Not supported OS."
  124. case "$(_os)" in
  125. ubuntu)
  126. [ -n "$(_os_ver)" -a "$(_os_ver)" -lt 16 ] && _error "Not supported OS, please change to Ubuntu 16+ and try again."
  127. ;;
  128. debian)
  129. [ -n "$(_os_ver)" -a "$(_os_ver)" -lt 8 ] && _error "Not supported OS, please change to Debian 8+ and try again."
  130. ;;
  131. fedora)
  132. [ -n "$(_os_ver)" -a "$(_os_ver)" -lt 29 ] && _error "Not supported OS, please change to Fedora 29+ and try again."
  133. ;;
  134. centos)
  135. [ -n "$(_os_ver)" -a "$(_os_ver)" -lt 7 ] && _error "Not supported OS, please change to CentOS 7+ and try again."
  136. ;;
  137. *)
  138. ;; # do nothing
  139. esac
  140. }
  141. # Install from repository
  142. install_wg_1() {
  143. _info "Install wireguard from repository"
  144. case "$(_os)" in
  145. ubuntu)
  146. _error_detect "add-apt-repository ppa:wireguard/wireguard"
  147. _error_detect "apt-get update"
  148. _error_detect "apt-get -y install linux-headers-$(uname -r)"
  149. _error_detect "apt-get -y install qrencode"
  150. _error_detect "apt-get -y install iptables"
  151. _error_detect "apt-get -y install wireguard"
  152. ;;
  153. debian)
  154. echo "deb http://deb.debian.org/debian/ unstable main" > /etc/apt/sources.list.d/unstable.list
  155. printf 'Package: *\nPin: release a=unstable\nPin-Priority: 90\n' > /etc/apt/preferences.d/limit-unstable
  156. _error_detect "apt-get update"
  157. _error_detect "apt-get -y install linux-headers-$(uname -r)"
  158. _error_detect "apt-get -y install qrencode"
  159. _error_detect "apt-get -y install iptables"
  160. _error_detect "apt-get -y install wireguard"
  161. ;;
  162. fedora)
  163. _error_detect "dnf -y copr enable jdoss/wireguard"
  164. _error_detect "dnf -y install kernel-devel"
  165. _error_detect "dnf -y install kernel-headers"
  166. _error_detect "dnf -y install qrencode"
  167. _error_detect "dnf -y install wireguard-dkms wireguard-tools"
  168. ;;
  169. centos)
  170. _error_detect "curl -Lso /etc/yum.repos.d/wireguard.repo https://copr.fedorainfracloud.org/coprs/jdoss/wireguard/repo/epel-7/jdoss-wireguard-epel-7.repo"
  171. _error_detect "yum -y install epel-release"
  172. _error_detect "yum -y install kernel-devel"
  173. _error_detect "yum -y install kernel-headers"
  174. _error_detect "yum -y install qrencode"
  175. _error_detect "yum -y install wireguard-dkms wireguard-tools"
  176. ;;
  177. *)
  178. ;; # do nothing
  179. esac
  180. }
  181. # Install from source
  182. install_wg_2() {
  183. _info "Install wireguard from source"
  184. wireguard_ver="$(wget --no-check-certificate -qO- https://api.github.com/repos/WireGuard/WireGuard/tags | grep 'name' | head -1 | cut -d\" -f4)"
  185. if [ -z "${wireguard_ver}" ]; then
  186. wireguard_ver="$(curl -Lso- https://api.github.com/repos/WireGuard/WireGuard/tags | grep 'name' | head -1 | cut -d\" -f4)"
  187. fi
  188. [ -z "${wireguard_ver}" ] && _error "Failed to get wireguard latest version from github."
  189. wireguard_name="WireGuard-${wireguard_ver}"
  190. wireguard_url="https://github.com/WireGuard/WireGuard/archive/${wireguard_ver}.tar.gz"
  191. case "$(_os)" in
  192. ubuntu|debian)
  193. _error_detect "apt-get update"
  194. [ ! -d "/usr/src/linux-headers-$(uname -r)" ] && _error_detect "apt-get -y install linux-headers-$(uname -r)"
  195. _error_detect "apt-get -y install qrencode"
  196. _error_detect "apt-get -y install iptables"
  197. _error_detect "apt-get -y install bc"
  198. _error_detect "apt-get -y install gcc"
  199. _error_detect "apt-get -y install make"
  200. _error_detect "apt-get -y install libmnl-dev"
  201. ;;
  202. fedora)
  203. [ ! -d "/usr/src/kernels/$(uname -r)" ] && _error_detect "dnf -y install kernel-headers" && _error_detect "dnf -y install kernel-devel"
  204. _error_detect "dnf -y install qrencode"
  205. _error_detect "dnf -y install bc"
  206. _error_detect "dnf -y install gcc"
  207. _error_detect "dnf -y install make"
  208. _error_detect "dnf -y install libmnl-devel"
  209. ;;
  210. centos)
  211. _error_detect "yum -y install epel-release"
  212. [ ! -d "/usr/src/kernels/$(uname -r)" ] && _error_detect "yum -y install kernel-headers" && _error_detect "yum -y install kernel-devel"
  213. _error_detect "yum -y install qrencode"
  214. _error_detect "yum -y install bc"
  215. _error_detect "yum -y install gcc"
  216. _error_detect "yum -y install make"
  217. _error_detect "yum -y install libmnl-devel"
  218. ;;
  219. *)
  220. ;; # do nothing
  221. esac
  222. _error_detect "wget --no-check-certificate -qO ${wireguard_name}.tar.gz ${wireguard_url}"
  223. _error_detect "tar zxf ${wireguard_name}.tar.gz"
  224. _error_detect "cd ${wireguard_name}/src"
  225. _error_detect "make tools"
  226. _error_detect "make module"
  227. _error_detect "make install"
  228. _error_detect "cd ${cur_dir} && rm -fr ${wireguard_name}.tar.gz ${wireguard_name}"
  229. }
  230. # Create server interface
  231. create_server_if() {
  232. SERVER_PRIVATE_KEY="$(wg genkey)"
  233. SERVER_PUBLIC_KEY="$(echo ${SERVER_PRIVATE_KEY} | wg pubkey)"
  234. CLIENT_PRIVATE_KEY="$(wg genkey)"
  235. CLIENT_PUBLIC_KEY="$(echo ${CLIENT_PRIVATE_KEY} | wg pubkey)"
  236. CLIENT_PRE_SHARED_KEY="$( wg genpsk )"
  237. _info "Create server interface: /etc/wireguard/${SERVER_WG_NIC}.conf"
  238. [ ! -d "/etc/wireguard" ] && mkdir -p "/etc/wireguard"
  239. if [ -n "${SERVER_PUB_IPV6}" ]; then
  240. cat > /etc/wireguard/${SERVER_WG_NIC}.conf <<EOF
  241. [Interface]
  242. Address = ${SERVER_WG_IPV4}/24,${SERVER_WG_IPV6}/64
  243. ListenPort = ${SERVER_WG_PORT}
  244. PrivateKey = ${SERVER_PRIVATE_KEY}
  245. [Peer]
  246. PublicKey = ${CLIENT_PUBLIC_KEY}
  247. AllowedIPs = ${CLIENT_WG_IPV4}/32,${CLIENT_WG_IPV6}/128
  248. PresharedKey = ${CLIENT_PRE_SHARED_KEY}
  249. EOF
  250. else
  251. cat > /etc/wireguard/${SERVER_WG_NIC}.conf <<EOF
  252. [Interface]
  253. Address = ${SERVER_WG_IPV4}/24
  254. ListenPort = ${SERVER_WG_PORT}
  255. PrivateKey = ${SERVER_PRIVATE_KEY}
  256. [Peer]
  257. PublicKey = ${CLIENT_PUBLIC_KEY}
  258. AllowedIPs = ${CLIENT_WG_IPV4}/32
  259. PresharedKey = ${CLIENT_PRE_SHARED_KEY}
  260. EOF
  261. fi
  262. chmod 600 /etc/wireguard/${SERVER_WG_NIC}.conf
  263. }
  264. # Create client interface
  265. create_client_if() {
  266. _info "Create client interface: /etc/wireguard/${SERVER_WG_NIC}_client"
  267. if [ -n "${SERVER_PUB_IPV6}" ]; then
  268. cat > /etc/wireguard/${SERVER_WG_NIC}_client <<EOF
  269. [Interface]
  270. Address = ${CLIENT_WG_IPV4}/24,${CLIENT_WG_IPV6}/64
  271. PrivateKey = ${CLIENT_PRIVATE_KEY}
  272. DNS = ${CLIENT_DNS_1},${CLIENT_DNS_2}
  273. [Peer]
  274. PublicKey = ${SERVER_PUBLIC_KEY}
  275. Endpoint = ${SERVER_PUB_IPV4}:${SERVER_WG_PORT}
  276. AllowedIPs = 0.0.0.0/0,::/0
  277. PresharedKey = ${CLIENT_PRE_SHARED_KEY}
  278. EOF
  279. else
  280. cat > /etc/wireguard/${SERVER_WG_NIC}_client <<EOF
  281. [Interface]
  282. Address = ${CLIENT_WG_IPV4}/24
  283. PrivateKey = ${CLIENT_PRIVATE_KEY}
  284. DNS = ${CLIENT_DNS_1},${CLIENT_DNS_2}
  285. [Peer]
  286. PublicKey = ${SERVER_PUBLIC_KEY}
  287. Endpoint = ${SERVER_PUB_IPV4}:${SERVER_WG_PORT}
  288. AllowedIPs = 0.0.0.0/0
  289. PresharedKey = ${CLIENT_PRE_SHARED_KEY}
  290. EOF
  291. fi
  292. chmod 600 /etc/wireguard/${SERVER_WG_NIC}_client
  293. }
  294. # Generate a QR Code picture with default client interface
  295. generate_qr() {
  296. _info "Generate a QR Code picture with client interface"
  297. _error_detect "qrencode -s8 -o /etc/wireguard/${SERVER_WG_NIC}_client.png < /etc/wireguard/${SERVER_WG_NIC}_client"
  298. }
  299. # Enable IP forwarding
  300. enable_ip_forward() {
  301. _info "Enable IP forward"
  302. sed -i '/net.ipv4.ip_forward/d' /etc/sysctl.conf
  303. [ -n "${SERVER_PUB_IPV6}" ] && sed -i '/net.ipv6.conf.all.forwarding/d' /etc/sysctl.conf
  304. echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
  305. [ -n "${SERVER_PUB_IPV6}" ] && echo "net.ipv6.conf.all.forwarding = 1" >> /etc/sysctl.conf
  306. sysctl -p >/dev/null 2>&1
  307. }
  308. # Set firewall rules
  309. set_firewall() {
  310. _info "Setting firewall rules"
  311. if _exists "firewall-cmd"; then
  312. if [ "$(firewall-cmd --state | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g")" = "running" ]; then
  313. default_zone="$(firewall-cmd --get-default-zone)"
  314. if [ "$(firewall-cmd --zone=${default_zone} --query-masquerade)" = "no" ]; then
  315. _error_detect "firewall-cmd --zone=${default_zone} --add-masquerade"
  316. fi
  317. if ! firewall-cmd --list-ports | grep -qw "${SERVER_WG_PORT}/udp"; then
  318. _error_detect "firewall-cmd --permanent --zone=${default_zone} --add-port=${SERVER_WG_PORT}/udp"
  319. fi
  320. _error_detect "firewall-cmd --reload"
  321. else
  322. _warn "Firewalld looks like not running, please start it and manually set"
  323. fi
  324. else
  325. if _exists "iptables"; then
  326. iptables -A INPUT -p udp --dport ${SERVER_WG_PORT} -j ACCEPT
  327. iptables -A FORWARD -i ${SERVER_WG_NIC} -j ACCEPT
  328. iptables -t nat -A POSTROUTING -o ${SERVER_PUB_NIC} -j MASQUERADE
  329. iptables-save > /etc/iptables.rules
  330. if [ -d "/etc/network/if-up.d" ]; then
  331. cat > /etc/network/if-up.d/iptables <<EOF
  332. #!/bin/sh
  333. /sbin/iptables-restore < /etc/iptables.rules
  334. EOF
  335. chmod +x /etc/network/if-up.d/iptables
  336. fi
  337. fi
  338. if _exists "ip6tables"; then
  339. ip6tables -A INPUT -p udp --dport ${SERVER_WG_PORT} -j ACCEPT
  340. ip6tables -A FORWARD -i ${SERVER_WG_NIC} -j ACCEPT
  341. ip6tables -t nat -A POSTROUTING -o ${SERVER_PUB_NIC} -j MASQUERADE
  342. ip6tables-save > /etc/ip6tables.rules
  343. if [ -d "/etc/network/if-up.d" ]; then
  344. cat > /etc/network/if-up.d/ip6tables <<EOF
  345. #!/bin/sh
  346. /sbin/ip6tables-restore < /etc/ip6tables.rules
  347. EOF
  348. chmod +x /etc/network/if-up.d/ip6tables
  349. fi
  350. fi
  351. fi
  352. }
  353. # WireGuard installation completed
  354. install_completed() {
  355. _info "Starting WireGuard via wg-quick for ${SERVER_WG_NIC}"
  356. _error_detect "systemctl daemon-reload"
  357. _error_detect "systemctl start wg-quick@${SERVER_WG_NIC}"
  358. _error_detect "systemctl enable wg-quick@${SERVER_WG_NIC}"
  359. _info "WireGuard VPN Server installation completed"
  360. _info "WireGuard VPN default client file is below:"
  361. _info "$(_green "/etc/wireguard/${SERVER_WG_NIC}_client")"
  362. _info "WireGuard VPN default client QR Code is below:"
  363. _info "$(_green "/etc/wireguard/${SERVER_WG_NIC}_client.png")"
  364. _info "Download and scan this QR Code with your phone, enjoy it"
  365. }
  366. add_client() {
  367. if ! _exists "wg" || ! _exists "wg-quick"; then
  368. _red "WireGuard looks like not installed, please installed it try again\n" && exit 1
  369. fi
  370. default_server_if="/etc/wireguard/${SERVER_WG_NIC}.conf"
  371. default_client_if="/etc/wireguard/${SERVER_WG_NIC}_client"
  372. [ ! -s "${default_server_if}" ] && echo "The default server interface ($(_red ${default_server_if})) does not exists" && exit 1
  373. [ ! -s "${default_client_if}" ] && echo "The default client interface ($(_red ${default_client_if})) does not exists" && exit 1
  374. while true
  375. do
  376. read -p "Please enter a client name (for example: wg1):" client
  377. if [ -z "${client}" ]; then
  378. _red "Client name can not be empty\n"
  379. else
  380. new_client_if="/etc/wireguard/${client}_client"
  381. if [ "${client}" = "${SERVER_WG_NIC}" ]; then
  382. echo "The default client ($(_yellow ${client})) already exists. Please re-enter it"
  383. elif [ -s "${new_client_if}" ]; then
  384. echo "The client ($(_yellow ${client})) already exists. Please re-enter it"
  385. else
  386. break
  387. fi
  388. fi
  389. done
  390. # Get information from default interface file
  391. client_files=($(find /etc/wireguard -name "*_client" | sort))
  392. client_ipv4=()
  393. client_ipv6=()
  394. for ((i=0; i<${#client_files[@]}; i++)); do
  395. tmp_ipv4="$(grep -w "Address" ${client_files[$i]} | awk '{print $3}' | cut -d\/ -f1 )"
  396. tmp_ipv6="$(grep -w "Address" ${client_files[$i]} | awk '{print $3}' | awk -F, '{print $2}' | cut -d\/ -f1 )"
  397. client_ipv4=(${client_ipv4[@]} ${tmp_ipv4})
  398. client_ipv6=(${client_ipv6[@]} ${tmp_ipv6})
  399. done
  400. # Sort array
  401. client_ipv4_sorted=($(printf '%s\n' "${client_ipv4[@]}" | sort))
  402. index=$(expr ${#client_ipv4[@]} - 1)
  403. last_ip=$(echo ${client_ipv4_sorted[$index]} | cut -d. -f4)
  404. issue_ip_last=$(expr ${last_ip} + 1)
  405. [ ${issue_ip_last} -gt 254 ] && _red "Too many client, IP addresses might not be enough\n" && exit 1
  406. ipv4_comm=$(echo ${client_ipv4[$index]} | cut -d. -f1-3)
  407. ipv6_comm=$(echo ${client_ipv6[$index]} | awk -F: '{print $1":"$2":"$3":"$4}')
  408. CLIENT_PRIVATE_KEY="$(wg genkey)"
  409. CLIENT_PUBLIC_KEY="$(echo ${CLIENT_PRIVATE_KEY} | wg pubkey)"
  410. SERVER_PUBLIC_KEY="$(grep -w "PublicKey" ${default_client_if} | awk '{print $3}')"
  411. CLIENT_ENDPOINT="$(grep -w "Endpoint" ${default_client_if} | awk '{print $3}')"
  412. CLIENT_PRE_SHARED_KEY="$(grep -w "PresharedKey" ${default_client_if} | awk '{print $3}')"
  413. CLIENT_WG_IPV4="${ipv4_comm}.${issue_ip_last}"
  414. CLIENT_WG_IPV6="${ipv6_comm}:${issue_ip_last}"
  415. # Create a new client interface
  416. if [ -n "${SERVER_PUB_IPV6}" ]; then
  417. cat > ${new_client_if} <<EOF
  418. [Interface]
  419. Address = ${CLIENT_WG_IPV4}/24,${CLIENT_WG_IPV6}/64
  420. PrivateKey = ${CLIENT_PRIVATE_KEY}
  421. DNS = ${CLIENT_DNS_1},${CLIENT_DNS_2}
  422. [Peer]
  423. PublicKey = ${SERVER_PUBLIC_KEY}
  424. Endpoint = ${CLIENT_ENDPOINT}
  425. AllowedIPs = 0.0.0.0/0,::/0
  426. PresharedKey = ${CLIENT_PRE_SHARED_KEY}
  427. EOF
  428. # Add a new client to default server interface
  429. cat >> ${default_server_if} <<EOF
  430. [Peer]
  431. PublicKey = ${CLIENT_PUBLIC_KEY}
  432. AllowedIPs = ${CLIENT_WG_IPV4}/32,${CLIENT_WG_IPV6}/128
  433. PresharedKey = ${CLIENT_PRE_SHARED_KEY}
  434. EOF
  435. else
  436. cat > ${new_client_if} <<EOF
  437. [Interface]
  438. Address = ${CLIENT_WG_IPV4}/24
  439. PrivateKey = ${CLIENT_PRIVATE_KEY}
  440. DNS = ${CLIENT_DNS_1},${CLIENT_DNS_2}
  441. [Peer]
  442. PublicKey = ${SERVER_PUBLIC_KEY}
  443. Endpoint = ${CLIENT_ENDPOINT}
  444. AllowedIPs = 0.0.0.0/0
  445. PresharedKey = ${CLIENT_PRE_SHARED_KEY}
  446. EOF
  447. cat >> ${default_server_if} <<EOF
  448. [Peer]
  449. PublicKey = ${CLIENT_PUBLIC_KEY}
  450. AllowedIPs = ${CLIENT_WG_IPV4}/32
  451. PresharedKey = ${CLIENT_PRE_SHARED_KEY}
  452. EOF
  453. fi
  454. chmod 600 ${new_client_if}
  455. echo "Add a WireGuard client ($(_green ${client})) completed"
  456. systemctl restart wg-quick@${SERVER_WG_NIC}
  457. # Generate a new QR Code picture
  458. qrencode -s8 -o ${new_client_if}.png < ${new_client_if}
  459. echo "Generate a QR Code picture with new client ($(_green ${client})) completed"
  460. echo
  461. echo "WireGuard VPN new client ($(_green ${client})) file is below:"
  462. _green "/etc/wireguard/${client}_client\n"
  463. echo
  464. echo "WireGuard VPN new client ($(_green ${client})) QR Code is below:"
  465. _green "/etc/wireguard/${client}_client.png\n"
  466. echo "Download and scan this QR Code with your phone, enjoy it"
  467. }
  468. remove_client() {
  469. default_server_if="/etc/wireguard/${SERVER_WG_NIC}.conf"
  470. [ ! -s "${default_server_if}" ] && echo "The default server interface ($(_red ${default_server_if})) does not exists" && exit 1
  471. while true
  472. do
  473. read -p "Please enter a client name you want to delete it (for example: wg1):" client
  474. if [ -z "${client}" ]; then
  475. _red "Client name can not be empty\n"
  476. else
  477. if [ "${client}" = "${SERVER_WG_NIC}" ]; then
  478. echo "The default client ($(_yellow ${client})) can not be delete"
  479. else
  480. break
  481. fi
  482. fi
  483. done
  484. client_if="/etc/wireguard/${client}_client"
  485. [ ! -s "${client_if}" ] && echo "The client file ($(_red ${client_if})) does not exists" && exit 1
  486. tmp_tag="$(grep -w "Address" ${client_if} | awk '{print $3}' | cut -d\/ -f1 )"
  487. [ -n "${tmp_tag}" ] && sed -i '/'"$tmp_tag"'/,+1d;:a;1,3!{P;$!N;D};N;ba' ${default_server_if}
  488. # Delete client interface file
  489. rm -f ${client_if}
  490. [ -s "/etc/wireguard/${client}_client.png" ] && rm -f /etc/wireguard/${client}_client.png
  491. systemctl restart wg-quick@${SERVER_WG_NIC}
  492. echo "The client name ($(_green ${client})) has been deleted"
  493. }
  494. list_clients() {
  495. default_server_if="/etc/wireguard/${SERVER_WG_NIC}.conf"
  496. [ ! -s "${default_server_if}" ] && echo "The default server interface ($(_red ${default_server_if})) does not exists" && exit 1
  497. local line="+-------------------------------------------------------------------------+\n"
  498. local string=%-35s
  499. printf "${line}|${string} |${string} |\n${line}" " Client Interface" " Client's IP"
  500. client_files=($(find /etc/wireguard -name "*_client" | sort))
  501. ips=($(grep -w "AllowedIPs" ${default_server_if} | awk '{print $3}'))
  502. [ ${#client_files[@]} -ne ${#ips[@]} ] && echo "One or more client interface file is missing in /etc/wireguard" && exit 1
  503. for ((i=0; i<${#ips[@]}; i++)); do
  504. tmp_ipv4="$(echo ${ips[$i]} | cut -d\/ -f1)"
  505. for ((j=0; j<${#client_files[@]}; j++)); do
  506. if grep -qw "${tmp_ipv4}" "${client_files[$j]}"; then
  507. printf "|${string} |${string} |\n" " ${client_files[$j]}" " ${ips[$i]}"
  508. break
  509. fi
  510. done
  511. done
  512. printf ${line}
  513. }
  514. version() {
  515. if _exists "wg" && _exists "wg-quick"; then
  516. if [ -s "/lib/modules/$(uname -r)/extra/wireguard.ko" ] || [ -s "/lib/modules/$(uname -r)/extra/wireguard.ko.xz" ] \
  517. || [ -s "/lib/modules/$(uname -r)/updates/dkms/" ]; then
  518. _exists "modinfo" && installed_wg_ver="$(modinfo -F version wireguard)"
  519. [ -n "${installed_wg_ver}" ] && echo "WireGuard version: $(_green ${installed_wg_ver})"
  520. else
  521. _red "WireGuard kernel module does not exists\n"
  522. fi
  523. else
  524. _red "WireGuard is not installed\n"
  525. fi
  526. }
  527. show_help() {
  528. printf "
  529. Usage: $0 [Options]
  530. Options:
  531. -h, --help Print this help text and exit
  532. -r, --repo Install WireGuard from repository
  533. -s, --source Install WireGuard from source
  534. -v, --version Print WireGuard version if installed
  535. -a, --add Add a WireGuard client
  536. -d, --del Delete a WireGuard client
  537. -l, --list List all WireGuard client's IP
  538. "
  539. }
  540. install_from_repo() {
  541. check_os
  542. install_wg_1
  543. create_server_if
  544. create_client_if
  545. generate_qr
  546. enable_ip_forward
  547. set_firewall
  548. install_completed
  549. }
  550. install_from_source() {
  551. check_os
  552. install_wg_2
  553. create_server_if
  554. create_client_if
  555. generate_qr
  556. enable_ip_forward
  557. set_firewall
  558. install_completed
  559. }
  560. cur_dir="$(pwd)"
  561. [ ${EUID} -ne 0 ] && _error "This script must be run as root"
  562. SERVER_PUB_IPV4="${VPN_SERVER_PUB_IPV4:-$(_ipv4)}"
  563. SERVER_PUB_IPV6="${VPN_SERVER_PUB_IPV6:-$(_ipv6)}"
  564. SERVER_PUB_NIC="${VPN_SERVER_PUB_NIC:-$(_nic)}"
  565. SERVER_WG_NIC="${VPN_SERVER_WG_NIC:-wg0}"
  566. SERVER_WG_IPV4="${VPN_SERVER_WG_IPV4:-10.88.88.1}"
  567. SERVER_WG_IPV6="${VPN_SERVER_WG_IPV6:-fd88:88:88::1}"
  568. SERVER_WG_PORT="${VPN_SERVER_WG_PORT:-$(_port)}"
  569. CLIENT_WG_IPV4="${VPN_CLIENT_WG_IPV4:-10.88.88.2}"
  570. CLIENT_WG_IPV6="${VPN_CLIENT_WG_IPV6:-fd88:88:88::2}"
  571. CLIENT_DNS_1="${VPN_CLIENT_DNS_1:-1.1.1.1}"
  572. CLIENT_DNS_2="${VPN_CLIENT_DNS_2:-8.8.8.8}"
  573. main() {
  574. action="$1"
  575. [ -z "${action}" ] && show_help && exit 0
  576. case "${action}" in
  577. -h|--help)
  578. show_help
  579. ;;
  580. -r|--repo)
  581. install_from_repo
  582. ;;
  583. -s|--source)
  584. install_from_source
  585. ;;
  586. -v|--version)
  587. version
  588. ;;
  589. -a|--add)
  590. add_client
  591. ;;
  592. -d|--del)
  593. remove_client
  594. ;;
  595. -l|--list)
  596. list_clients
  597. ;;
  598. *)
  599. show_help
  600. ;;
  601. esac
  602. }
  603. main "$@"