Advertisement
Guest User

Untitled

a guest
Nov 29th, 2016
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.76 KB | None | 0 0
  1. #!/bin/sh
  2. #
  3. # Script for automatic setup of an IPsec VPN server on Ubuntu LTS and Debian 8.
  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-2016 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. # =====================================================
  21.  
  22. # Define your own values for these variables
  23. # - IPsec pre-shared key, VPN username and password
  24. # - All values MUST be placed inside 'single quotes'
  25. # - DO NOT use these characters within values: \ " '
  26.  
  27. YOUR_IPSEC_PSK=''
  28. YOUR_USERNAME=''
  29. YOUR_PASSWORD=''
  30.  
  31. # Important notes: https://git.io/vpnnotes
  32. # Setup VPN clients: https://git.io/vpnclients
  33.  
  34. # =====================================================
  35.  
  36. export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  37. SYS_DT="$(date +%Y-%m-%d-%H:%M:%S)"; export SYS_DT
  38.  
  39. exiterr() { echo "Error: $1" >&2; exit 1; }
  40. exiterr2() { echo "Error: 'apt-get install' failed." >&2; exit 1; }
  41. conf_bk() { /bin/cp -f "$1" "$1.old-$SYS_DT" 2>/dev/null; }
  42.  
  43. check_ip() {
  44. 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])$"
  45. printf %s "$1" | tr -d '\n' | grep -Eq "$IP_REGEX"
  46. }
  47.  
  48. os_type="$(lsb_release -si 2>/dev/null)"
  49. if [ "$os_type" != "Ubuntu" ] && [ "$os_type" != "Debian" ] && [ "$os_type" != "Raspbian" ]; then
  50. exiterr "This script only supports Ubuntu/Debian."
  51. fi
  52.  
  53. if [ -f /proc/user_beancounters ]; then
  54. echo "Error: This script does not support OpenVZ VPS." >&2
  55. echo "Try OpenVPN: https://github.com/Nyr/openvpn-install" >&2
  56. exit 1
  57. fi
  58.  
  59. if [ "$(id -u)" != 0 ]; then
  60. exiterr "Script must be run as root. Try 'sudo sh $0'"
  61. fi
  62.  
  63. NET_IF0=${VPN_IFACE:-'ens3'}
  64. NET_IFS=${VPN_IFACE:-'ens+'}
  65.  
  66. if_state=$(cat "/sys/class/net/$NET_IF0/operstate" 2>/dev/null)
  67. if [ -z "$if_state" ] || [ "$if_state" = "down" ] || [ "$NET_IF0" = "lo" ]; then
  68. echo "Error: Network interface '$NET_IF0' is not available." >&2
  69. cat 1>&2 <<'EOF'
  70.  
  71. DO NOT RUN THIS SCRIPT ON YOUR PC OR MAC!
  72.  
  73. If running on a server, try this workaround:
  74.  
  75. VPN_IFACE="$(route | grep '^default' | grep -o '[^ ]*$')"
  76. EOF
  77. cat 1>&2 <<EOF
  78. sudo VPN_IFACE="\$VPN_IFACE" sh "$0"
  79. EOF
  80. exit 1
  81. fi
  82.  
  83. [ -n "$YOUR_IPSEC_PSK" ] && VPN_IPSEC_PSK="$YOUR_IPSEC_PSK"
  84. [ -n "$YOUR_USERNAME" ] && VPN_USER="$YOUR_USERNAME"
  85. [ -n "$YOUR_PASSWORD" ] && VPN_PASSWORD="$YOUR_PASSWORD"
  86.  
  87. if [ -z "$VPN_IPSEC_PSK" ] && [ -z "$VPN_USER" ] && [ -z "$VPN_PASSWORD" ]; then
  88. echo "VPN credentials not set by user. Generating random PSK and password..."
  89. echo
  90. VPN_IPSEC_PSK="$(LC_CTYPE=C tr -dc 'A-HJ-NPR-Za-km-z2-9' < /dev/urandom | head -c 16)"
  91. VPN_USER=vpnuser
  92. VPN_PASSWORD="$(LC_CTYPE=C tr -dc 'A-HJ-NPR-Za-km-z2-9' < /dev/urandom | head -c 16)"
  93. fi
  94.  
  95. if [ -z "$VPN_IPSEC_PSK" ] || [ -z "$VPN_USER" ] || [ -z "$VPN_PASSWORD" ]; then
  96. exiterr "All VPN credentials must be specified. Edit the script and re-enter them."
  97. fi
  98.  
  99. case "$VPN_IPSEC_PSK $VPN_USER $VPN_PASSWORD" in
  100. *[\\\"\']*)
  101. exiterr "VPN credentials must not contain any of these characters: \\ \" '"
  102. ;;
  103. esac
  104.  
  105. if [ "$(sed 's/\..*//' /etc/debian_version 2>/dev/null)" = "7" ]; then
  106. cat <<'EOF'
  107. IMPORTANT: Workaround required for Debian 7 (Wheezy).
  108. You must first run the script at: https://git.io/vpndeb7
  109. If not already done so, press Ctrl-C to interrupt now.
  110.  
  111. Continuing in 30 seconds ...
  112.  
  113. EOF
  114. sleep 30
  115. fi
  116.  
  117. echo "VPN setup in progress... Please be patient."
  118. echo
  119.  
  120. # Create and change to working dir
  121. mkdir -p /opt/src
  122. cd /opt/src || exiterr "Cannot enter /opt/src."
  123.  
  124. # Update package index
  125. export DEBIAN_FRONTEND=noninteractive
  126. apt-get -yq update || exiterr "'apt-get update' failed."
  127.  
  128. # Make sure basic commands exist
  129. apt-get -yq install wget dnsutils openssl || exiterr2
  130. apt-get -yq install iproute gawk grep sed net-tools || exiterr2
  131.  
  132. cat <<'EOF'
  133.  
  134. Trying to auto discover IPs of this server...
  135.  
  136. In case the script hangs here for more than a few minutes,
  137. use Ctrl-C to interrupt. Then edit it and manually enter IPs.
  138.  
  139. EOF
  140.  
  141. # In case auto IP discovery fails, you may manually enter server IPs here.
  142. # If your server only has a public IP, put that public IP on both lines.
  143. PUBLIC_IP=${VPN_PUBLIC_IP:-''}
  144. PRIVATE_IP=${VPN_PRIVATE_IP:-''}
  145.  
  146. # Try to auto discover IPs of this server
  147. [ -z "$PUBLIC_IP" ] && PUBLIC_IP=$(dig @resolver1.opendns.com -t A -4 myip.opendns.com +short)
  148. [ -z "$PRIVATE_IP" ] && PRIVATE_IP=$(ip -4 route get 1 | awk '{print $NF;exit}')
  149.  
  150. # Check IPs for correct format
  151. check_ip "$PUBLIC_IP" || PUBLIC_IP=$(wget -t 3 -T 15 -qO- http://ipv4.icanhazip.com)
  152. check_ip "$PUBLIC_IP" || exiterr "Cannot find valid public IP. Edit the script and manually enter IPs."
  153. check_ip "$PRIVATE_IP" || PRIVATE_IP=$(ifconfig "$NET_IF0" | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*')
  154. check_ip "$PRIVATE_IP" || exiterr "Cannot find valid private IP. Edit the script and manually enter IPs."
  155.  
  156. # Install necessary packages
  157. apt-get -yq install libnss3-dev libnspr4-dev pkg-config libpam0g-dev \
  158. libcap-ng-dev libcap-ng-utils libselinux1-dev \
  159. libcurl4-nss-dev flex bison gcc make \
  160. libunbound-dev libnss3-tools libevent-dev || exiterr2
  161. apt-get -yq --no-install-recommends install xmlto || exiterr2
  162. apt-get -yq install ppp xl2tpd || exiterr2
  163.  
  164. # Install Fail2Ban to protect SSH server
  165. apt-get -yq install fail2ban || exiterr2
  166.  
  167. # Compile and install Libreswan
  168. swan_ver=3.18
  169. swan_file="libreswan-$swan_ver.tar.gz"
  170. swan_url1="https://download.libreswan.org/$swan_file"
  171. swan_url2="https://github.com/libreswan/libreswan/archive/v$swan_ver.tar.gz"
  172. if ! { wget -t 3 -T 30 -nv -O "$swan_file" "$swan_url1" || wget -t 3 -T 30 -nv -O "$swan_file" "$swan_url2"; }; then
  173. exiterr "Cannot download Libreswan source."
  174. fi
  175. /bin/rm -rf "/opt/src/libreswan-$swan_ver"
  176. tar xzf "$swan_file" && /bin/rm -f "$swan_file"
  177. cd "libreswan-$swan_ver" || exiterr "Cannot enter Libreswan source dir."
  178. echo "WERROR_CFLAGS =" > Makefile.inc.local
  179. if [ "$(packaging/utils/lswan_detect.sh init)" = "systemd" ]; then
  180. apt-get -yq install libsystemd-dev || exiterr2
  181. fi
  182. make -s programs && make -s install
  183.  
  184. # Verify the install and clean up
  185. cd /opt/src || exiterr "Cannot enter /opt/src."
  186. /bin/rm -rf "/opt/src/libreswan-$swan_ver"
  187. if ! /usr/local/sbin/ipsec --version 2>/dev/null | grep -qs "$swan_ver"; then
  188. exiterr "Libreswan $swan_ver failed to build."
  189. fi
  190.  
  191. # Create IPsec (Libreswan) config
  192. conf_bk "/etc/ipsec.conf"
  193. cat > /etc/ipsec.conf <<EOF
  194. version 2.0
  195.  
  196. config setup
  197. nat_traversal=yes
  198. virtual_private=%v4:10.0.0.0/8,%v4:192.168.0.0/16,%v4:172.16.0.0/12,%v4:!192.168.42.0/23
  199. protostack=netkey
  200. nhelpers=0
  201. interfaces=%defaultroute
  202. uniqueids=no
  203.  
  204. conn shared
  205. left=$PRIVATE_IP
  206. leftid=$PUBLIC_IP
  207. right=%any
  208. forceencaps=yes
  209. authby=secret
  210. pfs=no
  211. rekey=no
  212. keyingtries=5
  213. dpddelay=30
  214. dpdtimeout=120
  215. dpdaction=clear
  216. ike=3des-sha1,aes-sha1,aes256-sha2_512,aes256-sha2_256
  217. phase2alg=3des-sha1,aes-sha1,aes256-sha2_512,aes256-sha2_256
  218.  
  219. conn l2tp-psk
  220. auto=add
  221. leftsubnet=$PRIVATE_IP/32
  222. leftnexthop=%defaultroute
  223. leftprotoport=17/1701
  224. rightprotoport=17/%any
  225. type=transport
  226. auth=esp
  227. also=shared
  228.  
  229. conn xauth-psk
  230. auto=add
  231. leftsubnet=0.0.0.0/0
  232. rightaddresspool=192.168.43.10-192.168.43.250
  233. modecfgdns1=8.8.8.8
  234. modecfgdns2=8.8.4.4
  235. leftxauthserver=yes
  236. rightxauthclient=yes
  237. leftmodecfgserver=yes
  238. rightmodecfgclient=yes
  239. modecfgpull=yes
  240. xauthby=file
  241. ike-frag=yes
  242. ikev2=never
  243. cisco-unity=yes
  244. also=shared
  245. EOF
  246.  
  247. # Specify IPsec PSK
  248. conf_bk "/etc/ipsec.secrets"
  249. cat > /etc/ipsec.secrets <<EOF
  250. $PUBLIC_IP %any : PSK "$VPN_IPSEC_PSK"
  251. EOF
  252.  
  253. # Create xl2tpd config
  254. conf_bk "/etc/xl2tpd/xl2tpd.conf"
  255. cat > /etc/xl2tpd/xl2tpd.conf <<'EOF'
  256. [global]
  257. port = 1701
  258.  
  259. [lns default]
  260. ip range = 192.168.42.10-192.168.42.250
  261. local ip = 192.168.42.1
  262. require chap = yes
  263. refuse pap = yes
  264. require authentication = yes
  265. name = l2tpd
  266. pppoptfile = /etc/ppp/options.xl2tpd
  267. length bit = yes
  268. EOF
  269.  
  270. # Set xl2tpd options
  271. conf_bk "/etc/ppp/options.xl2tpd"
  272. cat > /etc/ppp/options.xl2tpd <<'EOF'
  273. ipcp-accept-local
  274. ipcp-accept-remote
  275. ms-dns 8.8.8.8
  276. ms-dns 8.8.4.4
  277. noccp
  278. auth
  279. crtscts
  280. mtu 1280
  281. mru 1280
  282. lock
  283. proxyarp
  284. lcp-echo-failure 4
  285. lcp-echo-interval 30
  286. connect-delay 5000
  287. EOF
  288.  
  289. # Create VPN credentials
  290. conf_bk "/etc/ppp/chap-secrets"
  291. cat > /etc/ppp/chap-secrets <<EOF
  292. # Secrets for authentication using CHAP
  293. # client server secret IP addresses
  294. "$VPN_USER" l2tpd "$VPN_PASSWORD" *
  295. EOF
  296.  
  297. conf_bk "/etc/ipsec.d/passwd"
  298. VPN_PASSWORD_ENC=$(openssl passwd -1 "$VPN_PASSWORD")
  299. cat > /etc/ipsec.d/passwd <<EOF
  300. $VPN_USER:$VPN_PASSWORD_ENC:xauth-psk
  301. EOF
  302.  
  303. # Update sysctl settings
  304. if ! grep -qs "hwdsl2 VPN script" /etc/sysctl.conf; then
  305. conf_bk "/etc/sysctl.conf"
  306. cat >> /etc/sysctl.conf <<EOF
  307.  
  308. # Added by hwdsl2 VPN script
  309. kernel.msgmnb = 65536
  310. kernel.msgmax = 65536
  311. kernel.shmmax = 68719476736
  312. kernel.shmall = 4294967296
  313.  
  314. net.ipv4.ip_forward = 1
  315. net.ipv4.tcp_syncookies = 1
  316. net.ipv4.conf.all.accept_source_route = 0
  317. net.ipv4.conf.default.accept_source_route = 0
  318. net.ipv4.conf.all.accept_redirects = 0
  319. net.ipv4.conf.default.accept_redirects = 0
  320. net.ipv4.conf.all.send_redirects = 0
  321. net.ipv4.conf.default.send_redirects = 0
  322. net.ipv4.conf.lo.send_redirects = 0
  323. net.ipv4.conf.$NET_IF0.send_redirects = 0
  324. net.ipv4.conf.all.rp_filter = 0
  325. net.ipv4.conf.default.rp_filter = 0
  326. net.ipv4.conf.lo.rp_filter = 0
  327. net.ipv4.conf.$NET_IF0.rp_filter = 0
  328. net.ipv4.icmp_echo_ignore_broadcasts = 1
  329. net.ipv4.icmp_ignore_bogus_error_responses = 1
  330.  
  331. net.core.wmem_max = 12582912
  332. net.core.rmem_max = 12582912
  333. net.ipv4.tcp_rmem = 10240 87380 12582912
  334. net.ipv4.tcp_wmem = 10240 87380 12582912
  335. EOF
  336. fi
  337.  
  338. # Check if IPTables rules need updating
  339. ipt_flag=0
  340. IPT_FILE="/etc/iptables.rules"
  341. if ! grep -qs "hwdsl2 VPN script" "$IPT_FILE" \
  342. || ! iptables -t nat -C POSTROUTING -s 192.168.42.0/24 -o "$NET_IFS" -j SNAT --to-source "$PRIVATE_IP" 2>/dev/null \
  343. || ! iptables -t nat -C POSTROUTING -s 192.168.43.0/24 -o "$NET_IFS" -m policy --dir out --pol none -j SNAT --to-source "$PRIVATE_IP" 2>/dev/null; then
  344. ipt_flag=1
  345. fi
  346.  
  347. # Add IPTables rules for VPN
  348. if [ "$ipt_flag" = "1" ]; then
  349. service fail2ban stop >/dev/null 2>&1
  350. iptables-save > "$IPT_FILE.old-$SYS_DT"
  351. iptables -I INPUT 1 -m conntrack --ctstate INVALID -j DROP
  352. iptables -I INPUT 2 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  353. iptables -I INPUT 3 -p udp -m multiport --dports 500,4500 -j ACCEPT
  354. iptables -I INPUT 4 -p udp --dport 1701 -m policy --dir in --pol ipsec -j ACCEPT
  355. iptables -I INPUT 5 -p udp --dport 1701 -j DROP
  356. iptables -I FORWARD 1 -m conntrack --ctstate INVALID -j DROP
  357. iptables -I FORWARD 2 -i "$NET_IFS" -o ppp+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  358. iptables -I FORWARD 3 -i ppp+ -o "$NET_IFS" -j ACCEPT
  359. iptables -I FORWARD 4 -i ppp+ -o ppp+ -s 192.168.42.0/24 -d 192.168.42.0/24 -j ACCEPT
  360. iptables -I FORWARD 5 -i "$NET_IFS" -d 192.168.43.0/24 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  361. iptables -I FORWARD 6 -s 192.168.43.0/24 -o "$NET_IFS" -j ACCEPT
  362. # Uncomment if you wish to disallow traffic between VPN clients themselves
  363. # iptables -I FORWARD 2 -i ppp+ -o ppp+ -s 192.168.42.0/24 -d 192.168.42.0/24 -j DROP
  364. # iptables -I FORWARD 3 -s 192.168.43.0/24 -d 192.168.43.0/24 -j DROP
  365. iptables -A FORWARD -j DROP
  366. iptables -t nat -I POSTROUTING -s 192.168.43.0/24 -o "$NET_IFS" -m policy --dir out --pol none -j SNAT --to-source "$PRIVATE_IP"
  367. iptables -t nat -I POSTROUTING -s 192.168.42.0/24 -o "$NET_IFS" -j SNAT --to-source "$PRIVATE_IP"
  368. echo "# Modified by hwdsl2 VPN script" > "$IPT_FILE"
  369. iptables-save >> "$IPT_FILE"
  370.  
  371. # Update rules for iptables-persistent
  372. IPT_FILE2="/etc/iptables/rules.v4"
  373. if [ -f "$IPT_FILE2" ]; then
  374. conf_bk "$IPT_FILE2"
  375. /bin/cp -f "$IPT_FILE" "$IPT_FILE2"
  376. fi
  377. fi
  378.  
  379. # Load IPTables rules at boot
  380. mkdir -p /etc/network/if-pre-up.d
  381. cat > /etc/network/if-pre-up.d/iptablesload <<'EOF'
  382. #!/bin/sh
  383. iptables-restore < /etc/iptables.rules
  384. exit 0
  385. EOF
  386.  
  387. # Start services at boot
  388. update-rc.d fail2ban enable >/dev/null 2>&1
  389. systemctl enable fail2ban >/dev/null 2>&1
  390. if ! grep -qs "hwdsl2 VPN script" /etc/rc.local; then
  391. conf_bk "/etc/rc.local"
  392. sed --follow-symlinks -i '/^exit 0/d' /etc/rc.local
  393. cat >> /etc/rc.local <<'EOF'
  394.  
  395. # Added by hwdsl2 VPN script
  396. service ipsec start
  397. service xl2tpd start
  398. echo 1 > /proc/sys/net/ipv4/ip_forward
  399. exit 0
  400. EOF
  401. if grep -qs raspbian /etc/os-release; then
  402. sed --follow-symlinks -i '/hwdsl2 VPN script/a sleep 15' /etc/rc.local
  403. fi
  404. fi
  405.  
  406. # Reload sysctl.conf
  407. sysctl -e -q -p
  408.  
  409. # Update file attributes
  410. chmod +x /etc/rc.local /etc/network/if-pre-up.d/iptablesload
  411. chmod 600 /etc/ipsec.secrets* /etc/ppp/chap-secrets* /etc/ipsec.d/passwd*
  412.  
  413. # Apply new IPTables rules
  414. iptables-restore < "$IPT_FILE"
  415.  
  416. # Restart services
  417. service fail2ban restart 2>/dev/null
  418. service ipsec restart 2>/dev/null
  419. service xl2tpd restart 2>/dev/null
  420.  
  421. cat <<EOF
  422.  
  423. ================================================
  424.  
  425. IPsec VPN server is now ready for use!
  426.  
  427. Connect to your new VPN with these details:
  428.  
  429. Server IP: $PUBLIC_IP
  430. IPsec PSK: $VPN_IPSEC_PSK
  431. Username: $VPN_USER
  432. Password: $VPN_PASSWORD
  433.  
  434. Write these down. You'll need them to connect!
  435.  
  436. Important notes: https://git.io/vpnnotes
  437. Setup VPN clients: https://git.io/vpnclients
  438.  
  439. ================================================
  440.  
  441. EOF
  442.  
  443. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement