Advertisement
Guest User

Untitled

a guest
Jan 24th, 2019
429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.86 KB | None | 0 0
  1. #!/bin/sh
  2. #
  3. # Script for automatic setup of an IPsec VPN server on Ubuntu LTS and Debian.
  4. # Works on any dedicated server or virtual private server (VPS) except OpenVZ.
  5. #
  6. # DO NOT RUN THIS SCRIPT ON YOUR PC OR MAC!
  7. #
  8. # The latest version of this script is available at:
  9. # https://github.com/hwdsl2/setup-ipsec-vpn
  10. #
  11. # Copyright (C) 2014-2019 Lin Song <linsongui@gmail.com>
  12. # Based on the work of Thomas Sarlandie (Copyright 2012)
  13. #
  14. # This work is licensed under the Creative Commons Attribution-ShareAlike 3.0
  15. # Unported License: http://creativecommons.org/licenses/by-sa/3.0/
  16. #
  17. # Attribution required: please include my name in any derivative and let me
  18. # know how you have improved it!
  19. # =====================================================
  20. # Define your own values for these variables
  21. # - IPsec pre-shared key, VPN username and password
  22. # - All values MUST be placed inside 'single quotes'
  23. # - DO NOT use these special characters within values: \ " '
  24. YOUR_IPSEC_PSK=''
  25. YOUR_USERNAME=''
  26. YOUR_PASSWORD=''
  27. # Important notes: https://git.io/vpnnotes
  28. # Setup VPN clients: https://git.io/vpnclients
  29. # =====================================================
  30. export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  31. SYS_DT="2019-01-23 17:55:00"
  32. exiterr() { echo "Error: $1" >&2; exit 1; }
  33. exiterr2() { exiterr "'apt-get install' failed."; }
  34. conf_bk() { /bin/cp -f "$1" "$1.old-$SYS_DT" 2>/dev/null; }
  35. bigecho() { echo; echo "## $1"; echo; }
  36. check_ip() {
  37. IP_REGEX='^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'
  38. printf '%s' "$1" | tr -d '\n' | grep -Eq "$IP_REGEX"
  39. }
  40. vpnsetup() {
  41. os_type=$(lsb_release -si 2>/dev/null)
  42. if [ -z "$os_type" ]; then
  43. [ -f /etc/os-release ] && os_type=$(. /etc/os-release && printf '%s' "$ID")
  44. [ -f /etc/lsb-release ] && os_type=$(. /etc/lsb-release && printf '%s' "$DISTRIB_ID")
  45. fi
  46. if ! printf '%s' "$os_type" | head -n 1 | grep -qiF -e ubuntu -e debian -e raspbian; then
  47. exiterr "This script only supports Ubuntu and Debian."
  48. fi
  49. if [ "$(sed 's/\..*//' /etc/debian_version)" = "7" ]; then
  50. exiterr "Debian 7 is not supported."
  51. fi
  52. if [ -f /proc/user_beancounters ]; then
  53. exiterr "OpenVZ VPS is not supported. Try OpenVPN: github.com/Nyr/openvpn-install"
  54. fi
  55. if [ "$(id -u)" != 0 ]; then
  56. exiterr "Script must be run as root. Try 'sudo sh $0'"
  57. fi
  58. def_iface=$(route 2>/dev/null | grep '^default' | grep -o '[^ ]*$')
  59. [ -z "$def_iface" ] && def_iface=$(ip -4 route list 0/0 2>/dev/null | grep -Po '(?<=dev )(\S+)')
  60. def_state=$(cat "/sys/class/net/$def_iface/operstate" 2>/dev/null)
  61. if [ -n "$def_state" ] && [ "$def_state" != "down" ]; then
  62. NET_IFACE="$def_iface"
  63. else
  64. eth0_state=$(cat "/sys/class/net/eth0/operstate" 2>/dev/null)
  65. if [ -z "$eth0_state" ] || [ "$eth0_state" = "down" ]; then
  66. exiterr "Could not detect the default network interface."
  67. fi
  68. NET_IFACE=eth0
  69. fi
  70. [ -n "$YOUR_IPSEC_PSK" ] && VPN_IPSEC_PSK="$YOUR_IPSEC_PSK"
  71. [ -n "$YOUR_USERNAME" ] && VPN_USER="$YOUR_USERNAME"
  72. [ -n "$YOUR_PASSWORD" ] && VPN_PASSWORD="$YOUR_PASSWORD"
  73. if [ -z "$VPN_IPSEC_PSK" ] && [ -z "$VPN_USER" ] && [ -z "$VPN_PASSWORD" ]; then
  74. bigecho "VPN credentials not set by user. Generating random PSK and password..."
  75. VPN_IPSEC_PSK=$(LC_CTYPE=C tr -dc 'A-HJ-NPR-Za-km-z2-9' < /dev/urandom | head -c 20)
  76. VPN_USER=vpnuser
  77. VPN_PASSWORD=$(LC_CTYPE=C tr -dc 'A-HJ-NPR-Za-km-z2-9' < /dev/urandom | head -c 16)
  78. fi
  79. if [ -z "$VPN_IPSEC_PSK" ] || [ -z "$VPN_USER" ] || [ -z "$VPN_PASSWORD" ]; then
  80. exiterr "All VPN credentials must be specified. Edit the script and re-enter them."
  81. fi
  82. if printf '%s' "$VPN_IPSEC_PSK $VPN_USER $VPN_PASSWORD" | LC_ALL=C grep -q '[^ -~]\+'; then
  83. exiterr "VPN credentials must not contain non-ASCII characters."
  84. fi
  85. bigecho "VPN setup in progress... Please be patient."
  86. # Create and change to working dir
  87. mkdir -p /opt/src
  88. cd /opt/src || exit 1
  89. count=0
  90. APT_LK=/var/lib/apt/lists/lock
  91. PKG_LK=/var/lib/dpkg/lock
  92. while fuser "$APT_LK" "$PKG_LK" >/dev/null 2>&1 \ || lsof "$APT_LK" >/dev/null 2>&1 || lsof "$PKG_LK" >/dev/null 2>&1; do
  93. [ "$count" = "0" ] && bigecho "Waiting for apt to be available..."
  94. [ "$count" -ge "60" ] && exiterr "Could not get apt/dpkg lock."
  95. count=$((count+1))
  96. printf '%s' '.'
  97. sleep 3
  98. done
  99. bigecho "Populating apt-get cache..."
  100. export DEBIAN_FRONTEND=noninteractive
  101. apt-get -yq update || exiterr "'apt-get update' failed."
  102. bigecho "Installing packages required for setup..."
  103. apt-get -yq install wget dnsutils openssl \
  104. iptables iproute2 gawk grep sed net-tools || exiterr2
  105. bigecho "Trying to auto discover IP of this server..."
  106. cat <<'EOF'
  107. In case the script hangs here for more than a few minutes,
  108. press Ctrl-C to abort. Then edit it and manually enter IP.
  109. EOF
  110. # In case auto IP discovery fails, enter server's public IP here.
  111. PUBLIC_IP=${VPN_PUBLIC_IP:-''}
  112. [ -z "$PUBLIC_IP" ] && PUBLIC_IP=$(dig @resolver1.opendns.com -t A -4 myip.opendns.com +short)
  113. check_ip "$PUBLIC_IP" || PUBLIC_IP=$(wget -t 3 -T 15 -qO- http://ipv4.icanhazip.com)
  114. check_ip "$PUBLIC_IP" || exiterr "Cannot detect this server's public IP. Edit the script and manually enter it."
  115. bigecho "Installing packages required for the VPN..."
  116. apt-get -yq install libnss3-dev libnspr4-dev pkg-config \
  117. libpam0g-dev libcap-ng-dev libcap-ng-utils libselinux1-dev \
  118. libcurl4-nss-dev flex bison gcc make libnss3-tools \
  119. libevent-dev ppp xl2tpd || exiterr2
  120. bigecho "Installing Fail2Ban to protect SSH..."
  121. apt-get -yq install fail2ban || exiterr2
  122. bigecho "Compiling and installing Libreswan..."
  123. SWAN_VER=3.27
  124. swan_file="libreswan-$SWAN_VER.tar.gz"
  125. swan_url1="https://github.com/libreswan/libreswan/archive/v$SWAN_VER.tar.gz"
  126. swan_url2="https://download.libreswan.org/$swan_file"
  127. if ! { wget -t 3 -T 30 -nv -O "$swan_file" "$swan_url1" || wget -t 3 -T 30 -nv -O "$swan_file" "$swan_url2"; }; then
  128. exit 1
  129. fi
  130. /bin/rm -rf "/opt/src/libreswan-$SWAN_VER"
  131. tar xzf "$swan_file" && /bin/rm -f "$swan_file"
  132. cd "libreswan-$SWAN_VER" || exit 1
  133. cat > Makefile.inc.local <<'EOF'
  134. WERROR_CFLAGS =
  135. USE_DNSSEC = false
  136. USE_DH31 = false
  137. USE_GLIBC_KERN_FLIP_HEADERS = true
  138. EOF
  139. if [ "$(packaging/utils/lswan_detect.sh init)" = "systemd" ]; then
  140. apt-get -yq install libsystemd-dev || exiterr2
  141. fi
  142. NPROCS=$(grep -c ^processor /proc/cpuinfo)
  143. [ -z "$NPROCS" ] && NPROCS=1
  144. make "-j$((NPROCS+1))" -s base && make -s install-base
  145. cd /opt/src || exit 1
  146. /bin/rm -rf "/opt/src/libreswan-$SWAN_VER"
  147. if ! /usr/local/sbin/ipsec --version 2>/dev/null | grep -qF "$SWAN_VER"; then
  148. exiterr "Libreswan $SWAN_VER failed to build."
  149. fi
  150. bigecho "Creating VPN configuration..."
  151. L2TP_NET=${VPN_L2TP_NET:-'192.168.42.0/24'}
  152. L2TP_LOCAL=${VPN_L2TP_LOCAL:-'192.168.42.1'}
  153. L2TP_POOL=${VPN_L2TP_POOL:-'192.168.42.10-192.168.42.250'}
  154. XAUTH_NET=${VPN_XAUTH_NET:-'192.168.43.0/24'}
  155. XAUTH_POOL=${VPN_XAUTH_POOL:-'192.168.43.10-192.168.43.250'}
  156. DNS_SRV1=${VPN_DNS_SRV1:-'8.8.8.8'}
  157. DNS_SRV2=${VPN_DNS_SRV2:-'8.8.4.4'}
  158. DNS_SRVS="\"$DNS_SRV1 $DNS_SRV2\""
  159. [ -n "$VPN_DNS_SRV1" ] && [ -z "$VPN_DNS_SRV2" ] && DNS_SRVS="$DNS_SRV1"
  160. # Create IPsec config
  161. conf_bk "/etc/ipsec.conf"
  162. cat > /etc/ipsec.conf <<EOF
  163. version 2.0
  164. config setup
  165. virtual-private=%v4:10.0.0.0/8,%v4:192.168.0.0/16,%v4:172.16.0.0/12,%v4:!$L2TP_NET,%v4:!$XAUTH_NET
  166. protostack=netkey
  167. interfaces=%defaultroute
  168. uniqueids=no
  169. conn shared
  170. left=%defaultroute
  171. leftid=$PUBLIC_IP
  172. right=%any
  173. encapsulation=yes
  174. authby=secret
  175. pfs=no
  176. rekey=no
  177. keyingtries=5
  178. dpddelay=30
  179. dpdtimeout=120
  180. dpdaction=clear
  181. ike=aes256-sha2,aes128-sha2,aes256-sha1,aes128-sha1,aes256-sha2;modp1024,aes128-sha1;modp1024
  182. phase2alg=aes_gcm-null,aes128-sha1,aes256-sha1,aes256-sha2_512,aes128-sha2,aes256-sha2
  183. sha2-truncbug=yes
  184. conn l2tp-psk
  185. auto=add
  186. leftprotoport=17/1701
  187. rightprotoport=17/%any
  188. type=transport
  189. phase2=esp
  190. also=shared
  191. conn xauth-psk
  192. auto=add
  193. leftsubnet=0.0.0.0/0
  194. rightaddresspool=$XAUTH_POOL
  195. modecfgdns=$DNS_SRVS
  196. leftxauthserver=yes
  197. rightxauthclient=yes
  198. leftmodecfgserver=yes
  199. rightmodecfgclient=yes
  200. modecfgpull=yes
  201. xauthby=file
  202. ike-frag=yes
  203. ikev2=never
  204. cisco-unity=yes
  205. also=shared
  206. EOF
  207. if uname -m | grep -qi '^arm'; then
  208. sed -i '/phase2alg/s/,aes256-sha2_512//' /etc/ipsec.conf
  209. fi
  210. # Specify IPsec PSK
  211. conf_bk "/etc/ipsec.secrets"
  212. cat > /etc/ipsec.secrets <<EOF
  213. %any %any : PSK "$VPN_IPSEC_PSK"
  214. EOF
  215. # Create xl2tpd config
  216. conf_bk "/etc/xl2tpd/xl2tpd.conf"
  217. cat > /etc/xl2tpd/xl2tpd.conf <<EOF
  218. [global]
  219. port = 1701
  220. [lns default]
  221. ip range = $L2TP_POOL
  222. local ip = $L2TP_LOCAL
  223. require chap = yes
  224. refuse pap = yes
  225. require authentication = yes
  226. name = l2tpd
  227. pppoptfile = /etc/ppp/options.xl2tpd
  228. length bit = yes
  229. EOF
  230. # Set xl2tpd options
  231. conf_bk "/etc/ppp/options.xl2tpd"
  232. cat > /etc/ppp/options.xl2tpd <<EOF
  233. +mschap-v2
  234. ipcp-accept-local
  235. ipcp-accept-remote
  236. noccp
  237. auth
  238. mtu 1280
  239. mru 1280
  240. proxyarp
  241. lcp-echo-failure 4
  242. lcp-echo-interval 30
  243. connect-delay 5000
  244. ms-dns $DNS_SRV1
  245. EOF
  246. if [ -z "$VPN_DNS_SRV1" ] || [ -n "$VPN_DNS_SRV2" ]; then
  247. cat >> /etc/ppp/options.xl2tpd <<EOF
  248. ms-dns $DNS_SRV2
  249. EOF
  250. fi
  251. # Create VPN credentials
  252. conf_bk "/etc/ppp/chap-secrets"
  253. cat > /etc/ppp/chap-secrets <<EOF
  254. "$VPN_USER" l2tpd "$VPN_PASSWORD" *
  255. EOF
  256. conf_bk "/etc/ipsec.d/passwd"
  257. VPN_PASSWORD_ENC=$(openssl passwd -1 "$VPN_PASSWORD")
  258. cat > /etc/ipsec.d/passwd <<EOF
  259. $VPN_USER:$VPN_PASSWORD_ENC:xauth-psk
  260. EOF
  261. bigecho "Updating sysctl settings..."
  262. if ! grep -qs "hwdsl2 VPN script" /etc/sysctl.conf; then
  263. conf_bk "/etc/sysctl.conf"
  264. if [ "$(getconf LONG_BIT)" = "64" ]; then
  265. SHM_MAX=68719476736
  266. SHM_ALL=4294967296
  267. else
  268. SHM_MAX=4294967295
  269. SHM_ALL=268435456
  270. fi
  271. cat >> /etc/sysctl.conf <<EOF
  272. # Added by hwdsl2 VPN script
  273. kernel.msgmnb = 65536
  274. kernel.msgmax = 65536
  275. kernel.shmmax = $SHM_MAX
  276. kernel.shmall = $SHM_ALL
  277. net.ipv4.ip_forward = 1
  278. net.ipv4.conf.all.accept_source_route = 0
  279. net.ipv4.conf.all.accept_redirects = 0
  280. net.ipv4.conf.all.send_redirects = 0
  281. net.ipv4.conf.all.rp_filter = 0
  282. net.ipv4.conf.default.accept_source_route = 0
  283. net.ipv4.conf.default.accept_redirects = 0
  284. net.ipv4.conf.default.send_redirects = 0
  285. net.ipv4.conf.default.rp_filter = 0
  286. net.ipv4.conf.$NET_IFACE.send_redirects = 0
  287. net.ipv4.conf.$NET_IFACE.rp_filter = 0
  288. net.core.wmem_max = 12582912
  289. net.core.rmem_max = 12582912
  290. net.ipv4.tcp_rmem = 10240 87380 12582912
  291. net.ipv4.tcp_wmem = 10240 87380 12582912
  292. EOF
  293. fi
  294. bigecho "Updating IPTables rules..."
  295. # Check if rules need updating
  296. ipt_flag=0
  297. IPT_FILE="/etc/iptables.rules"
  298. IPT_FILE2="/etc/iptables/rules.v4"
  299. if ! grep -qs "hwdsl2 VPN script" "$IPT_FILE" \ || ! iptables -t nat -C POSTROUTING -s "$L2TP_NET" -o "$NET_IFACE" -j MASQUERADE 2>/dev/null \ || ! iptables -t nat -C POSTROUTING -s "$XAUTH_NET" -o "$NET_IFACE" -m policy --dir out --pol none -j MASQUERADE 2>/dev/null; then
  300. ipt_flag=1
  301. fi
  302. # Add IPTables rules for VPN
  303. if [ "$ipt_flag" = "1" ]; then
  304. service fail2ban stop >/dev/null 2>&1
  305. iptables-save > "$IPT_FILE.old-$SYS_DT"
  306. iptables -I INPUT 1 -p udp --dport 1701 -m policy --dir in --pol none -j DROP
  307. iptables -I INPUT 2 -m conntrack --ctstate INVALID -j DROP
  308. iptables -I INPUT 3 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  309. iptables -I INPUT 4 -p udp -m multiport --dports 500,4500 -j ACCEPT
  310. iptables -I INPUT 5 -p udp --dport 1701 -m policy --dir in --pol ipsec -j ACCEPT
  311. iptables -I INPUT 6 -p udp --dport 1701 -j DROP
  312. iptables -I FORWARD 1 -m conntrack --ctstate INVALID -j DROP
  313. iptables -I FORWARD 2 -i "$NET_IFACE" -o ppp+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  314. iptables -I FORWARD 3 -i ppp+ -o "$NET_IFACE" -j ACCEPT
  315. iptables -I FORWARD 4 -i ppp+ -o ppp+ -s "$L2TP_NET" -d "$L2TP_NET" -j ACCEPT
  316. iptables -I FORWARD 5 -i "$NET_IFACE" -d "$XAUTH_NET" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  317. iptables -I FORWARD 6 -s "$XAUTH_NET" -o "$NET_IFACE" -j ACCEPT
  318. # Uncomment if you wish to disallow traffic between VPN clients themselves
  319. # iptables -I FORWARD 2 -i ppp+ -o ppp+ -s "$L2TP_NET" -d "$L2TP_NET" -j DROP
  320. # iptables -I FORWARD 3 -s "$XAUTH_NET" -d "$XAUTH_NET" -j DROP
  321. iptables -A FORWARD -j DROP
  322. iptables -t nat -I POSTROUTING -s "$XAUTH_NET" -o "$NET_IFACE" -m policy --dir out --pol none -j MASQUERADE
  323. iptables -t nat -I POSTROUTING -s "$L2TP_NET" -o "$NET_IFACE" -j MASQUERADE
  324. echo "# Modified by hwdsl2 VPN script" > "$IPT_FILE"
  325. iptables-save >> "$IPT_FILE"
  326. if [ -f "$IPT_FILE2" ]; then
  327. conf_bk "$IPT_FILE2"
  328. /bin/cp -f "$IPT_FILE" "$IPT_FILE2"
  329. fi
  330. fi
  331. bigecho "Enabling services on boot..."
  332. # Check for iptables-persistent
  333. IPT_PST="/etc/init.d/iptables-persistent"
  334. IPT_PST2="/usr/share/netfilter-persistent/plugins.d/15-ip4tables"
  335. ipt_load=1
  336. if [ -f "$IPT_FILE2" ] && { [ -f "$IPT_PST" ] || [ -f "$IPT_PST2" ]; }; then
  337. ipt_load=0
  338. fi
  339. if [ "$ipt_load" = "1" ]; then
  340. mkdir -p /etc/network/if-pre-up.d
  341. cat > /etc/network/if-pre-up.d/iptablesload <<'EOF'
  342. #!/bin/sh
  343. iptables-restore < /etc/iptables.rules
  344. exit 0
  345. EOF
  346. chmod +x /etc/network/if-pre-up.d/iptablesload
  347. if [ -f /usr/sbin/netplan ]; then
  348. mkdir -p /etc/systemd/system
  349. cat > /etc/systemd/system/load-iptables-rules.service <<'EOF'
  350. [Unit]
  351. Description = Load /etc/iptables.rules
  352. DefaultDependencies=no
  353. Before=network-pre.target
  354. Wants=network-pre.target
  355. Wants=systemd-modules-load.service local-fs.target
  356. After=systemd-modules-load.service local-fs.target
  357. [Service]
  358. Type=oneshot
  359. ExecStart=/etc/network/if-pre-up.d/iptablesload
  360. [Install]
  361. WantedBy=multi-user.target
  362. EOF
  363. systemctl enable load-iptables-rules 2>/dev/null
  364. fi
  365. fi
  366. for svc in (fail2ban ipsec xl2tpd); do
  367. update-rc.d "$svc" enable >/dev/null 2>&1
  368. systemctl enable "$svc" 2>/dev/null
  369. done
  370. if ! grep -qs "hwdsl2 VPN script" /etc/rc.local; then
  371. if [ -f /etc/rc.local ]; then
  372. conf_bk "/etc/rc.local"
  373. sed --follow-symlinks -i '/^exit 0/d' /etc/rc.local
  374. else
  375. echo '#!/bin/sh' > /etc/rc.local
  376. fi
  377. cat >> /etc/rc.local <<'EOF'
  378. # Added by hwdsl2 VPN script
  379. (sleep 15
  380. service ipsec restart
  381. service xl2tpd restart
  382. echo 1 > /proc/sys/net/ipv4/ip_forward)&
  383. exit 0
  384. EOF
  385. fi
  386. bigecho "Starting services..."
  387. # Reload sysctl.conf
  388. sysctl -e -q -p
  389. # Update file attributes
  390. chmod +x /etc/rc.local
  391. chmod 600 /etc/ipsec.secrets* /etc/ppp/chap-secrets* /etc/ipsec.d/passwd*
  392. # Apply new IPTables rules
  393. iptables-restore < "$IPT_FILE"
  394. # Restart services
  395. mkdir -p /run/pluto
  396. service fail2ban restart 2>/dev/null
  397. service ipsec restart 2>/dev/null
  398. service xl2tpd restart 2>/dev/null
  399. cat <<EOF
  400. ================================================
  401. IPsec VPN server is now ready for use!
  402. Connect to your new VPN with these details:
  403. Server IP: $PUBLIC_IP
  404. IPsec PSK: $VPN_IPSEC_PSK
  405. Username: $VPN_USER
  406. Password: $VPN_PASSWORD
  407. Write these down. You'll need them to connect!
  408. Important notes: https://git.io/vpnnotes
  409. Setup VPN clients: https://git.io/vpnclients
  410. ================================================
  411. EOF
  412. }
  413. ## Defer setup until we have the complete script
  414. vpnsetup "$@"
  415. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement