Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2019
461
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.54 KB | None | 0 0
  1. #!/bin/sh
  2. #
  3. # Script for automatic setup of an IPsec VPN server on CentOS/RHEL 6 and 7.
  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) 2015-2017 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='|h[;yqfrP8vc8<yRK$1HU%mE'
  25. YOUR_USERNAME='VPNUser'
  26. YOUR_PASSWORD='gs1DGV6i'
  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="$(date +%F-%T)"
  32. exiterr() { echo "Error: $1" >&2; exit 1; }
  33. exiterr2() { exiterr "'yum 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. if ! grep -qs -e "release 6" -e "release 7" /etc/redhat-release; then
  42. exiterr "This script only supports CentOS/RHEL 6 and 7."
  43. fi
  44. if [ -f /proc/user_beancounters ]; then
  45. exiterr "OpenVZ VPS is not supported. Try OpenVPN: github.com/Nyr/openvpn-install"
  46. fi
  47. if [ "$(id -u)" != 0 ]; then
  48. exiterr "Script must be run as root. Try 'sudo sh $0'"
  49. fi
  50. net_iface=${VPN_NET_IFACE:-'eth0'}
  51. def_iface="$(route 2>/dev/null | grep '^default' | grep -o '[^ ]*$')"
  52. [ -z "$def_iface" ] && def_iface="$(ip -4 route list 0/0 2>/dev/null | grep -Po '(?<=dev )(\S+)')"
  53. def_iface_state=$(cat "/sys/class/net/$def_iface/operstate" 2>/dev/null)
  54. if [ -n "$def_iface_state" ] && [ "$def_iface_state" != "down" ]; then
  55. case "$def_iface" in
  56. wl*)
  57. exiterr "Wireless interface '$def_iface' detected. DO NOT run this script on your PC or Mac!"
  58. ;;
  59. esac
  60. net_iface="$def_iface"
  61. fi
  62. net_iface_state=$(cat "/sys/class/net/$net_iface/operstate" 2>/dev/null)
  63. if [ -z "$net_iface_state" ] || [ "$net_iface_state" = "down" ] || [ "$net_iface" = "lo" ]; then
  64. printf "Error: Network interface '%s' is not available.\n" "$net_iface" >&2
  65. if [ -z "$VPN_NET_IFACE" ]; then
  66. cat 1>&2 <<EOF
  67. Unable to detect the default network interface. Manually re-run this script with:
  68. sudo VPN_NET_IFACE="your_default_interface_name" sh "$0"
  69. EOF
  70. fi
  71. exit 1
  72. fi
  73. [ -n "$YOUR_IPSEC_PSK" ] && VPN_IPSEC_PSK="$YOUR_IPSEC_PSK"
  74. [ -n "$YOUR_USERNAME" ] && VPN_USER="$YOUR_USERNAME"
  75. [ -n "$YOUR_PASSWORD" ] && VPN_PASSWORD="$YOUR_PASSWORD"
  76. if [ -z "$VPN_IPSEC_PSK" ] && [ -z "$VPN_USER" ] && [ -z "$VPN_PASSWORD" ]; then
  77. bigecho "VPN credentials not set by user. Generating random PSK and password..."
  78. VPN_IPSEC_PSK="$(LC_CTYPE=C tr -dc 'A-HJ-NPR-Za-km-z2-9' < /dev/urandom | head -c 16)"
  79. VPN_USER=vpnuser
  80. VPN_PASSWORD="$(LC_CTYPE=C tr -dc 'A-HJ-NPR-Za-km-z2-9' < /dev/urandom | head -c 16)"
  81. fi
  82.  
  83. if [ -z "$VPN_IPSEC_PSK" ] || [ -z "$VPN_USER" ] || [ -z "$VPN_PASSWORD" ]; then
  84. exiterr "All VPN credentials must be specified. Edit the script and re-enter them."
  85. fi
  86.  
  87. if printf '%s' "$VPN_IPSEC_PSK $VPN_USER $VPN_PASSWORD" | LC_ALL=C grep -q '[^ -~]\+'; then
  88. exiterr "VPN credentials must not contain non-ASCII characters."
  89. fi
  90. case "$VPN_IPSEC_PSK $VPN_USER $VPN_PASSWORD" in
  91. *[\\\"\']*)
  92. exiterr "VPN credentials must not contain these special characters: \\ \" '"
  93. ;;
  94. esac
  95. bigecho "VPN setup in progress... Please be patient."
  96. # Create and change to working dir
  97. mkdir -p /opt/src
  98. cd /opt/src || exiterr "Cannot enter /opt/src."
  99. bigecho "Installing packages required for setup..."
  100. yum -y install wget bind-utils openssl \
  101. iproute gawk grep sed net-tools || exiterr2
  102. bigecho "Trying to auto discover IP of this server..."
  103. cat <<'EOF'
  104. In case the script hangs here for more than a few minutes,
  105. press Ctrl-C to abort. Then edit it and manually enter IP.
  106. EOF
  107. # In case auto IP discovery fails, enter server's public IP here.
  108. PUBLIC_IP=${VPN_PUBLIC_IP:-''}
  109. # Try to auto discover IP of this server
  110. [ -z "$PUBLIC_IP" ] && PUBLIC_IP=$(dig @resolver1.opendns.com -t A -4 myip.opendns.com +short)
  111. # Check IP for correct format
  112. check_ip "$PUBLIC_IP" || PUBLIC_IP=$(wget -t 3 -T 15 -qO- http://ipv4.icanhazip.com)
  113. check_ip "$PUBLIC_IP" || exiterr "Cannot detect this server's public IP. Edit the script and manually enter it."
  114. bigecho "Adding the EPEL repository..."
  115. epel_url="https://dl.fedoraproject.org/pub/epel/epel-release-latest-$(rpm -E '%{rhel}').noarch.rpm"
  116. yum -y install epel-release || yum -y install "$epel_url" || exiterr2
  117. bigecho "Installing packages required for the VPN..."
  118. yum -y install nss-devel nspr-devel pkgconfig pam-devel \
  119. libcap-ng-devel libselinux-devel curl-devel \
  120. flex bison gcc make ppp xl2tpd || exiterr2
  121. OPT1='--enablerepo=*server-optional*'
  122. OPT2='--enablerepo=*releases-optional*'
  123. if grep -qs "release 6" /etc/redhat-release; then
  124. yum -y remove libevent-devel
  125. yum "$OPT1" "$OPT2" -y install libevent2-devel fipscheck-devel || exiterr2
  126. else
  127. yum -y install systemd-devel iptables-services || exiterr2
  128. yum "$OPT1" "$OPT2" -y install libevent-devel fipscheck-devel || exiterr2
  129. fi
  130. bigecho "Installing Fail2Ban to protect SSH..."
  131. yum -y install fail2ban || exiterr2
  132. bigecho "Compiling and installing Libreswan..."
  133. SWAN_VER=3.23
  134. swan_file="libreswan-$SWAN_VER.tar.gz"
  135. swan_url1="https://github.com/libreswan/libreswan/archive/v$SWAN_VER.tar.gz"
  136. swan_url2="https://download.libreswan.org/$swan_file"
  137. if ! { wget -t 3 -T 30 -nv -O "$swan_file" "$swan_url1" || wget -t 3 -T 30 -nv -O "$swan_file" "$swan_url2"; }; then
  138. exiterr "Cannot download Libreswan source."
  139. fi
  140. /bin/rm -rf "/opt/src/libreswan-$SWAN_VER"
  141. tar xzf "$swan_file" && /bin/rm -f "$swan_file"
  142. cd "libreswan-$SWAN_VER" || exiterr "Cannot enter Libreswan source dir."
  143. sed -i '/docker-targets\.mk/d' Makefile
  144. cat > Makefile.inc.local <<'EOF'
  145. WERROR_CFLAGS =
  146. USE_DNSSEC = false
  147. EOF
  148. NPROCS="$(grep -c ^processor /proc/cpuinfo)"
  149. [ -z "$NPROCS" ] && NPROCS=1
  150. make "-j$((NPROCS+1))" -s base && make -s install-base
  151. # Verify the install and clean up
  152. cd /opt/src || exiterr "Cannot enter /opt/src."
  153. /bin/rm -rf "/opt/src/libreswan-$SWAN_VER"
  154. if ! /usr/local/sbin/ipsec --version 2>/dev/null | grep -qF "$SWAN_VER"; then
  155. exiterr "Libreswan $SWAN_VER failed to build."
  156. fi
  157. bigecho "Creating VPN configuration..."
  158. L2TP_NET=${VPN_L2TP_NET:-'192.168.42.0/24'}
  159. L2TP_LOCAL=${VPN_L2TP_LOCAL:-'192.168.42.1'}
  160. L2TP_POOL=${VPN_L2TP_POOL:-'192.168.42.10-192.168.42.250'}
  161. XAUTH_NET=${VPN_XAUTH_NET:-'192.168.43.0/24'}
  162. XAUTH_POOL=${VPN_XAUTH_POOL:-'192.168.43.10-192.168.43.250'}
  163. DNS_SRV1=${VPN_DNS_SRV1:-'8.8.8.8'}
  164. DNS_SRV2=${VPN_DNS_SRV2:-'8.8.4.4'}
  165. # Create IPsec (Libreswan) config
  166. conf_bk "/etc/ipsec.conf"
  167. cat > /etc/ipsec.conf <<EOF
  168. version 2.0
  169. config setup
  170. 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
  171. protostack=netkey
  172. interfaces=%defaultroute
  173. uniqueids=no
  174. conn shared
  175. left=%defaultroute
  176. leftid=$PUBLIC_IP
  177. right=%any
  178. encapsulation=yes
  179. authby=secret
  180. pfs=no
  181. rekey=no
  182. keyingtries=5
  183. dpddelay=30
  184. dpdtimeout=120
  185. dpdaction=clear
  186. ike=3des-sha1,3des-sha2,aes-sha1,aes-sha1;modp1024,aes-sha2,aes-sha2;modp1024,aes256-sha2_512
  187. phase2alg=3des-sha1,3des-sha2,aes-sha1,aes-sha2,aes256-sha2_512
  188. sha2-truncbug=yes
  189. conn l2tp-psk
  190. auto=add
  191. leftprotoport=17/1701
  192. rightprotoport=17/%any
  193. type=transport
  194. phase2=esp
  195. also=shared
  196. conn xauth-psk
  197. auto=add
  198. leftsubnet=0.0.0.0/0
  199. rightaddresspool=$XAUTH_POOL
  200. modecfgdns="$DNS_SRV1, $DNS_SRV2"
  201. leftxauthserver=yes
  202. rightxauthclient=yes
  203. leftmodecfgserver=yes
  204. rightmodecfgclient=yes
  205. modecfgpull=yes
  206. xauthby=file
  207. ike-frag=yes
  208. ikev2=never
  209. cisco-unity=yes
  210. also=shared
  211. EOF
  212. # Specify IPsec PSK
  213. conf_bk "/etc/ipsec.secrets"
  214. cat > /etc/ipsec.secrets <<EOF
  215. %any %any : PSK "$VPN_IPSEC_PSK"
  216. EOF
  217. # Create xl2tpd config
  218. conf_bk "/etc/xl2tpd/xl2tpd.conf"
  219. cat > /etc/xl2tpd/xl2tpd.conf <<EOF
  220. [global]
  221. port = 1701
  222. [lns default]
  223. ip range = $L2TP_POOL
  224. local ip = $L2TP_LOCAL
  225. require chap = yes
  226. refuse pap = yes
  227. require authentication = yes
  228. name = l2tpd
  229. pppoptfile = /etc/ppp/options.xl2tpd
  230. length bit = yes
  231. EOF
  232. # Set xl2tpd options
  233. conf_bk "/etc/ppp/options.xl2tpd"
  234. cat > /etc/ppp/options.xl2tpd <<EOF
  235. +mschap-v2
  236. ipcp-accept-local
  237. ipcp-accept-remote
  238. ms-dns $DNS_SRV1
  239. ms-dns $DNS_SRV2
  240. noccp
  241. auth
  242. mtu 1280
  243. mru 1280
  244. proxyarp
  245. lcp-echo-failure 4
  246. lcp-echo-interval 30
  247. connect-delay 5000
  248. EOF
  249. # Create VPN credentials
  250. conf_bk "/etc/ppp/chap-secrets"
  251. cat > /etc/ppp/chap-secrets <<EOF
  252. "$VPN_USER" l2tpd "$VPN_PASSWORD" *
  253. EOF
  254. conf_bk "/etc/ipsec.d/passwd"
  255. VPN_PASSWORD_ENC=$(openssl passwd -1 "$VPN_PASSWORD")
  256. cat > /etc/ipsec.d/passwd <<EOF
  257. $VPN_USER:$VPN_PASSWORD_ENC:xauth-psk
  258. EOF
  259. bigecho "Updating sysctl settings..."
  260. if ! grep -qs "hwdsl2 VPN script" /etc/sysctl.conf; then
  261. conf_bk "/etc/sysctl.conf"
  262. if [ "$(getconf LONG_BIT)" = "64" ]; then
  263. SHM_MAX=68719476736
  264. SHM_ALL=4294967296
  265. else
  266. SHM_MAX=4294967295
  267. SHM_ALL=268435456
  268. fi
  269. cat >> /etc/sysctl.conf <<EOF
  270. # Added by hwdsl2 VPN script
  271. kernel.msgmnb = 65536
  272. kernel.msgmax = 65536
  273. kernel.shmmax = $SHM_MAX
  274. kernel.shmall = $SHM_ALL
  275. net.ipv4.ip_forward = 1
  276. net.ipv4.conf.all.accept_source_route = 0
  277. net.ipv4.conf.all.accept_redirects = 0
  278. net.ipv4.conf.all.send_redirects = 0
  279. net.ipv4.conf.all.rp_filter = 0
  280. net.ipv4.conf.default.accept_source_route = 0
  281. net.ipv4.conf.default.accept_redirects = 0
  282. net.ipv4.conf.default.send_redirects = 0
  283. net.ipv4.conf.default.rp_filter = 0
  284. net.ipv4.conf.$net_iface.send_redirects = 0
  285. net.ipv4.conf.$net_iface.rp_filter = 0
  286. net.core.wmem_max = 12582912
  287. net.core.rmem_max = 12582912
  288. net.ipv4.tcp_rmem = 10240 87380 12582912
  289. net.ipv4.tcp_wmem = 10240 87380 12582912
  290. EOF
  291. fi
  292. bigecho "Updating IPTables rules..."
  293. # Check if IPTables rules need updating
  294. ipt_flag=0
  295. IPT_FILE="/etc/sysconfig/iptables"
  296. if ! grep -qs "hwdsl2 VPN script" "$IPT_FILE" \
  297. || ! iptables -t nat -C POSTROUTING -s "$L2TP_NET" -o "$net_iface" -j MASQUERADE 2>/dev/null \
  298. || ! iptables -t nat -C POSTROUTING -s "$XAUTH_NET" -o "$net_iface" -m policy --dir out --pol none -j MASQUERADE 2>/dev/null; then
  299. ipt_flag=1
  300. fi
  301. # Add IPTables rules for VPN
  302. if [ "$ipt_flag" = "1" ]; then
  303. service fail2ban stop >/dev/null 2>&1
  304. iptables-save > "$IPT_FILE.old-$SYS_DT"
  305. iptables -I INPUT 1 -p udp --dport 1701 -m policy --dir in --pol none -j DROP
  306. iptables -I INPUT 2 -m conntrack --ctstate INVALID -j DROP
  307. iptables -I INPUT 3 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  308. iptables -I INPUT 4 -p udp -m multiport --dports 500,4500 -j ACCEPT
  309. iptables -I INPUT 5 -p udp --dport 1701 -m policy --dir in --pol ipsec -j ACCEPT
  310. iptables -I INPUT 6 -p udp --dport 1701 -j DROP
  311. iptables -I FORWARD 1 -m conntrack --ctstate INVALID -j DROP
  312. iptables -I FORWARD 2 -i "$net_iface" -o ppp+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  313. iptables -I FORWARD 3 -i ppp+ -o "$net_iface" -j ACCEPT
  314. iptables -I FORWARD 4 -i ppp+ -o ppp+ -s "$L2TP_NET" -d "$L2TP_NET" -j ACCEPT
  315. iptables -I FORWARD 5 -i "$net_iface" -d "$XAUTH_NET" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  316. iptables -I FORWARD 6 -s "$XAUTH_NET" -o "$net_iface" -j ACCEPT
  317. # Uncomment if you wish to disallow traffic between VPN clients themselves
  318. # iptables -I FORWARD 2 -i ppp+ -o ppp+ -s "$L2TP_NET" -d "$L2TP_NET" -j DROP
  319. # iptables -I FORWARD 3 -s "$XAUTH_NET" -d "$XAUTH_NET" -j DROP
  320. iptables -A FORWARD -j DROP
  321. iptables -t nat -I POSTROUTING -s "$XAUTH_NET" -o "$net_iface" -m policy --dir out --pol none -j MASQUERADE
  322. iptables -t nat -I POSTROUTING -s "$L2TP_NET" -o "$net_iface" -j MASQUERADE
  323. echo "# Modified by hwdsl2 VPN script" > "$IPT_FILE"
  324. iptables-save >> "$IPT_FILE"
  325. fi
  326. bigecho "Creating basic Fail2Ban rules..."
  327. if [ ! -f /etc/fail2ban/jail.local ] ; then
  328. cat > /etc/fail2ban/jail.local <<'EOF'
  329. [ssh-iptables]
  330. enabled = true
  331. filter = sshd
  332. action = iptables[name=SSH, port=ssh, protocol=tcp]
  333. logpath = /var/log/secure
  334. EOF
  335. fi
  336. bigecho "Enabling services on boot..."
  337. if grep -qs "release 6" /etc/redhat-release; then
  338. chkconfig iptables on
  339. chkconfig fail2ban on
  340. else
  341. systemctl --now mask firewalld 2>/dev/null
  342. systemctl enable iptables fail2ban 2>/dev/null
  343. fi
  344. if ! grep -qs "hwdsl2 VPN script" /etc/rc.local; then
  345. if [ -f /etc/rc.local ]; then
  346. conf_bk "/etc/rc.local"
  347. else
  348. echo '#!/bin/sh' > /etc/rc.local
  349. fi
  350. cat >> /etc/rc.local <<'EOF'
  351. # Added by hwdsl2 VPN script
  352. (sleep 15
  353. modprobe -q pppol2tp
  354. service ipsec restart
  355. service xl2tpd restart
  356. echo 1 > /proc/sys/net/ipv4/ip_forward)&
  357. EOF
  358. fi
  359. bigecho "Starting services..."
  360. # Restore SELinux contexts
  361. restorecon /etc/ipsec.d/*db 2>/dev/null
  362. restorecon /usr/local/sbin -Rv 2>/dev/null
  363. restorecon /usr/local/libexec/ipsec -Rv 2>/dev/null
  364. # Reload sysctl.conf
  365. sysctl -e -q -p
  366. # Update file attributes
  367. chmod +x /etc/rc.local
  368. chmod 600 /etc/ipsec.secrets* /etc/ppp/chap-secrets* /etc/ipsec.d/passwd*
  369. # Apply new IPTables rules
  370. iptables-restore < "$IPT_FILE"
  371. # Fix xl2tpd on CentOS 7, if kernel module "l2tp_ppp" is unavailable
  372. if grep -qs "release 7" /etc/redhat-release; then
  373. if ! modprobe -q l2tp_ppp; then
  374. sed -i '/^ExecStartPre/s/^/#/' /usr/lib/systemd/system/xl2tpd.service
  375. systemctl daemon-reload
  376. fi
  377. fi
  378. # Restart services
  379. modprobe -q pppol2tp
  380. service fail2ban restart 2>/dev/null
  381. service ipsec restart 2>/dev/null
  382. service xl2tpd restart 2>/dev/null
  383. cat <<EOF
  384. ================================================
  385. IPsec VPN server is now ready for use!
  386. Connect to your new VPN with these details:
  387. Server IP: $PUBLIC_IP
  388. IPsec PSK: $VPN_IPSEC_PSK
  389. Username: $VPN_USER
  390. Password: $VPN_PASSWORD
  391. Write these down. You'll need them to connect!
  392. Important notes: https://git.io/vpnnotes
  393. Setup VPN clients: https://git.io/vpnclients
  394. ================================================
  395. EOF
  396. }
  397. ## Defer setup until we have the complete script
  398. vpnsetup "$@"
  399. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement