Advertisement
Guest User

Untitled

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