透过OpenVPN建立IPv4/IPv6隧道
whitebear
本文只是给自己的手记,内容散乱很难读懂。如需帮助,请留言。
最近Linode优惠活动很多,内存翻倍了,硬盘也翻倍了,比AWS啦,RackSpace啦便宜多了~
于是乎,直接付了一年的款,还优惠了10% 🙂
因为Linode是可以通过发ticket申请到/56的IPv6地址的,因此我就在Linode上搭了一个OpenVPN服务器,和实验室的OpenWRT路由连起来,提供IPv4/IPv6隧道。
OpenVPN有两种工作模式,tun和tap。tun工作在三层,tap在二层。tun模式对IPv6的支持是最近才完善的,不晓得能否可以用于这种环境(在路由器上配置隧道,通过路由向客户端提供类似于原生双栈接入的体验,而无需在客户端电脑上安装任何附加软件或进行特殊配置)。
tap模式的配置方法是我自己摸索出来的。由于tap是二层设备,所以隧道打通之后,可以认为OpenVPN服务器端的tap0和OpenVPN客户端的tap0设备是插在同一个交换机上的两张网卡。具体上面跑什么,自己弄就好了。不过,似乎OpenVPN存在某种限制(来源请求),必须在隧道双方的tap设备上配置一个IPv4地址,否则只配置IPv6地址会导致隧道打不通。
服务器端配置文件(/etc/openvpn/server.conf)如下(从/usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz抄的):
#################################################
# Sample OpenVPN 2.0 config file for #
# multi-client server. #
# #
# This file is for the server side #
# of a many-clients one-server #
# OpenVPN configuration. #
# #
# OpenVPN also supports #
# single-machine single-machine #
# configurations (See the Examples page #
# on the web site for more info). #
# #
# This config should work on Windows #
# or Linux/BSD systems. Remember on #
# Windows to quote pathnames and use #
# double backslashes, e.g.: #
# “C:\\Program Files\\OpenVPN\\config\\foo.key” #
# #
# Comments are preceded with ‘#’ or ‘;’ #
################################################## Which local IP address should OpenVPN
# listen on? (optional)
;local a.b.c.d# Which TCP/UDP port should OpenVPN listen on?
# If you want to run multiple OpenVPN instances
# on the same machine, use a different port
# number for each one. You will need to
# open up this port on your firewall.
port 11194 # 不要用默认端口……小心GFW 🙂# TCP or UDP server?
proto tcp # 默认的UDP在NAT环境中可能会因为NAT转换条目超时而导致隧道在一段时间后断开。TCP可以一定程度上避免这样的问题。
;proto udp# “dev tun” will create a routed IP tunnel,
# “dev tap” will create an ethernet tunnel.
# Use “dev tap0” if you are ethernet bridging
# and have precreated a tap0 virtual interface
# and bridged it with your ethernet interface.
# If you want to control access policies
# over the VPN, you must create firewall
# rules for the the TUN/TAP interface.
# On non-Windows systems, you can give
# an explicit unit number, such as tun0.
# On Windows, use “dev-node” for this.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
dev tap # 用tap设备
;dev tun# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel if you
# have more than one. On XP SP2 or higher,
# you may need to selectively disable the
# Windows firewall for the TAP adapter.
# Non-Windows systems usually don’t need this.
;dev-node MyTap # 可以考虑在这里指定tap设备的名称,如tap0# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key). Each client
# and the server must have their own cert and
# key file. The server and all clients will
# use the same ca file.
#
# See the “easy-rsa” directory for a series
# of scripts for generating RSA certificates
# and private keys. Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see “pkcs12” directive in man page).
ca ca.crt # 三个证书文件。后面会讲到如何生成。
cert server.crt
key server.key # This file should be kept secret# Diffie hellman parameters.
# Generate your own with:
# openssl dhparam -out dh1024.pem 1024
# Substitute 2048 for 1024 if you are using
# 2048 bit keys.
dh dh1024.pem # 秘钥。后面会讲到如何生成。# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
;server 10.8.0.0 255.255.255.0 # 对于tap设备来说,这句指令是无效的。需要用后面的server-bridge# Maintain a record of client virtual IP address
# associations in this file. If OpenVPN goes down or
# is restarted, reconnecting clients can be assigned
# the same virtual IP address from the pool that was
# previously assigned.
ifconfig-pool-persist ipp.txt # 记录IP地址分配关系。可有可无# Configure server mode for ethernet bridging.
# You must first use your OS’s bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface. Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume 10.8.0.4/255.255.255.0. Finally we
# must set aside an IP range in this subnet
# (start=10.8.0.50 end=10.8.0.100) to allocate
# to connecting clients. Leave this line commented
# out unless you are ethernet bridging.
server-bridge 10.99.0.1 255.255.255.0 10.99.0.50 10.99.0.100 # 对于tap设备来说,需要这一行以自动分配服务器和客户端的IPv4地址# Configure server mode for ethernet bridging
# using a DHCP-proxy, where clients talk
# to the OpenVPN server-side DHCP server
# to receive their IP address allocation
# and DNS server addresses. You must first use
# your OS’s bridging capability to bridge the TAP
# interface with the ethernet NIC interface.
# Note: this mode only works on clients (such as
# Windows), where the client-side TAP adapter is
# bound to a DHCP client.
;server-bridge # 如果不需要自动IP地址分配(隧道建立后,服务器和客户端的tap设备没有IPv4地址),那么就不要用上面那句而用这句。但是经过我的测试,如果不分配IPv4地址而只是配置IPv6地址的话,会不通。# Push routes to the client to allow it
# to reach other private subnets behind
# the server. Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
;push “route 192.168.10.0 255.255.255.0”
;push “route 192.168.20.0 255.255.255.0”# To assign specific IP addresses to specific
# clients or if a connecting client has a private
# subnet behind it that should also have VPN access,
# use the subdirectory “ccd” for client-specific
# configuration files (see man page for more info).# EXAMPLE: Suppose the client
# having the certificate common name “Thelonious”
# also has a small subnet behind his connecting
# machine, such as 192.168.40.128/255.255.255.248.
# First, uncomment out these lines:
;client-config-dir ccd
;route 192.168.40.128 255.255.255.248
# Then create a file ccd/Thelonious with this line:
# iroute 192.168.40.128 255.255.255.248
# This will allow Thelonious’ private subnet to
# access the VPN. This example will only work
# if you are routing, not bridging, i.e. you are
# using “dev tun” and “server” directives.# EXAMPLE: Suppose you want to give
# Thelonious a fixed VPN IP address of 10.9.0.1.
# First uncomment out these lines:
;client-config-dir ccd
;route 10.9.0.0 255.255.255.252
# Then add this line to ccd/Thelonious:
# ifconfig-push 10.9.0.1 10.9.0.2# Suppose that you want to enable different
# firewall access policies for different groups
# of clients. There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
# group, and firewall the TUN/TAP interface
# for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
# modify the firewall in response to access
# from different clients. See man
# page for more info on learn-address script.
;learn-address ./script# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
;push “redirect-gateway def1 bypass-dhcp” # 注释掉这句。防止客户端连接后自动将默认网关指向隧道,导致所有IPv4流量都从隧道出口。# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses. CAVEAT:
# http://openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
;push “dhcp-option DNS 208.67.222.222”
;push “dhcp-option DNS 208.67.220.220”# Uncomment this directive to allow different
# clients to be able to “see” each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server’s TUN/TAP interface.
;client-to-client# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names. This is recommended
# only for testing purposes. For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE “COMMON NAME”,
# UNCOMMENT THIS LINE OUT.
;duplicate-cn# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
keepalive 10 120# For extra security beyond that provided
# by SSL/TLS, create an “HMAC firewall”
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
# openvpn –genkey –secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be ‘0’
# on the server and ‘1’ on the clients.
tls-auth ta.key 0 # This file is secret # tls认证。最好打开,以保安全# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
;cipher BF-CBC # Blowfish (default)
;cipher AES-128-CBC # AES
;cipher DES-EDE3-CBC # Triple-DES# Enable compression on the VPN link.
# If you enable it here, you must also
# enable it in the client config file.
comp-lzo# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100# It’s a good idea to reduce the OpenVPN
# daemon’s privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
;user nobody
;group nogroup# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key
persist-tun# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status openvpn-status.log# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the “\Program Files\OpenVPN\log” directory).
# Use log or log-append to override this default.
# “log” will truncate the log file on OpenVPN startup,
# while “log-append” will append to it. Use one
# or the other (but not both).
;log openvpn.log
;log-append openvpn.log# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 3# Silence repeating messages. At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20
服务器端秘钥的生成:
- 在/etc/下建立openvpn目录
- 复制/usr/share/easy-rsa到刚建立的/etc/openvpn
- 修改/etc/openvpn/easy-rsa/vars文件,设定证书资讯,比如地址,省市等等
- 用source命令导入vars中定义的环境变量。source vars
- 清理环境 ./clean-all
- 生成CA ./build-ca
- 生成服务器端证书 ./build-key-server server 。参数server是服务器证书的文件名,可以任意起。但需要在openvpn配置文件里面跟着改
- 生成客户端证书 ./build-key client 。参数client同上。每个客户端一个证书。如果只有一个那么就保持用client做名字就好了,免得后面再修改配置文件。
- ./build-dh
- /etc/openvpn/easy-rsa/keys 目录下面的server.crt server.key ca.crt dh1024.pem 拷贝到 /etc/openvpn下
- 在 /etc/openvpn 下执行 openvpn –genkey –secret ta.key 生成ta.key
秘钥和配置文件都弄好之后,执行 service openvpn restart 应该可以看到openvpn启动成功。
客户端需要在OpenwRT上安装openvpn-openssl包。我这里使用的是OpenWRT trunk(BARRIER BREAKER (Bleeding Edge, r37349)),无luci,IPv6的配置方法和之前版本不同。
装好openvpn之后,配置文件在 /etc/config/openvpn
客户端配置文件:
config openvpn sample_client
Set to 1 to enable this instance:
option enabled 1 # 启动本配置节(OpenVPN客户端)
Specify that we are a client and that we
will be pulling certain config file directives
from the server.
option client 1
Use the same setting as you are using on
the server.
On most systems, the VPN will not function
unless you partially or fully disable
the firewall for the TUN/TAP interface.
option dev tap # tap设备
# option dev tunAre we connecting to a TCP or
UDP server? Use the same setting as
on the server.
option proto tcp # tcp协议
# option proto udpThe hostname/IP and port of the server.
You can have multiple remote entries
to load balance between the servers.
list remote “198.74.51.41 11194” # 服务器IP地址和端口
# list remote “my_server_2 1194”Choose a random host from the remote
list for load_balancing. Otherwise
try hosts in the order specified.
# option remote_random 1
Keep trying indefinitely to resolve the
host name of the OpenVPN server. Very useful
on machines which are not permanently connected
to the internet such as laptops.
option resolv_retry infinite
Most clients don’t need to bind to
a specific local port number.
option nobind 1
Try to preserve some state across restarts.
option persist_key 1
option persist_tun 1If you are connecting through an
HTTP proxy to reach the actual OpenVPN
server, put the proxy server/IP and
port number here. See the man page
if your proxy server requires
authentication.
retry on connection failures:
# option http_proxy_retry 1
specify http proxy address and port:
# option http_proxy “192.168.1.100 8080”
Wireless networks often produce a lot
of duplicate packets. Set this flag
to silence duplicate packet warnings.
# option mute_replay_warnings 1
SSL/TLS parms.
See the server config file for more
description. It’s best to use
a separate .crt/.key file pair
for each client. A single ca
file can be used for all clients.
option ca /etc/openvpn/ca.crt # 三个证书。所有的证书文件都从服务器的 /etc/openvpn/easy-rsa 下面拷回来
option cert /etc/openvpn/client.crt
option key /etc/openvpn/client.keyVerify server certificate by checking
that the certicate has the nsCertType
field set to “server”. This is an
important precaution to protect against
a potential attack discussed here:
http://openvpn.net/howto.html#mitm
To use this feature, you will need to generate
your server certificates with the nsCertType
field set to “server”. The build_key_server
script in the easy_rsa folder will do this.
option ns_cert_type server # 这里认证要开启
If a tls_auth key is used on the server
then every client must also have the key.
option tls_auth “/etc/openvpn/ta.key 1” # 也要开
Select a cryptographic cipher.
If the cipher option is used on the server
then you must also specify it here.
# option cipher x
Enable compression on the VPN link.
Don’t enable this unless it is also
enabled in the server config file.
option comp_lzo 1
Set log file verbosity.
option verb 3
Silence repeating messages
# option mute 20
执行
<br></br>uci commit openvpn<br></br>/etc/init.d/openvpn enable # 开机自动启动openvpn<br></br>/etc/init.d/openvpn restart # 重启openvpn<br></br>
启动刚才配置的openvpn客户端。 ifconfig 应该可以看到tap0设备。logread可以看到日志。
这时候,稍等一下,ping服务器端的IP应该是通的。需要等一下,刚连好的时候不通。
现在可以配置报文转发和IPv6支持了。
先发个Ticket找客服说申请一段/56的IPv6地址。Linode提供的最大地址块就是/56的,没有/48的(客服说的)。同时,RA通告发送大于/64的子网。因此,/64段的地址无法使用(也不是不能用,麻烦)。
假设申请到的地址是: 2600:3c01:xxxx:xx00::/56 ,那么我们这样规划:
- 2600:3c01:xxxx:xx01::/64 所有的路由器都在这
- 2600:3c01:xxxx:xx02::/64 网段1
- 2600:3c01:xxxx:xx03::/64 网段2
- 2600:3c01:xxxx:xx04::/64 网段3
其中,所有的路由器都位于第一个子网,每一个路由器连接到的网络则被称为子网1,子网2……
服务器端需要先改一下 /etc/sysctl.conf
#
# /etc/sysctl.conf – Configuration file for setting system variables
# See /etc/sysctl.d/ for additonal system variables
# See sysctl.conf (5) for information.
##kernel.domainname = example.com
# Uncomment the following to stop low-level messages on console
#kernel.printk = 3 4 1 3##############################################################3
# Functions previously found in netbase
## Uncomment the next two lines to enable Spoof protection (reverse-path filter)
# Turn on Source Address Verification in all interfaces to
# prevent some spoofing attacks
#net.ipv4.conf.default.rp_filter=1
#net.ipv4.conf.all.rp_filter=1# Uncomment the next line to enable TCP/IP SYN cookies
# See http://lwn.net/Articles/277146/
# Note: This may impact IPv6 TCP sessions too
#net.ipv4.tcp_syncookies=1# Uncomment the next line to enable packet forwarding for IPv4
net.ipv4.ip_forward=1 # IPv4报文转发# Uncomment the next line to enable packet forwarding for IPv6
# Enabling this option disables Stateless Address Autoconfiguration
# based on Router Advertisements for this host
net.ipv6.conf.all.forwarding=2 # 启用IPv6报文转发,同时保持接收RA。这是违规的。但Linode的IPv6配置要求主机接收RA,否则会导致主机自己丢失IPv6连接。###################################################################
# Additional settings – these settings can improve the network
# security of the host and prevent against some network attacks
# including spoofing attacks and man in the middle attacks through
# redirection. Some network environments, however, require that these
# settings are disabled so review and enable them as needed.
#
# Do not accept ICMP redirects (prevent MITM attacks)
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
# _or_
# Accept ICMP redirects only for gateways listed in our default
# gateway list (enabled by default)
# net.ipv4.conf.all.secure_redirects = 1
#
# Do not send ICMP redirects (we are not a router)
net.ipv4.conf.all.send_redirects = 0
#
# Do not accept IP source route packets (we are not a router)
#net.ipv4.conf.all.accept_source_route = 0
#net.ipv6.conf.all.accept_source_route = 0
#
# Log Martian Packets
#net.ipv4.conf.all.log_martians = 1
#net.ipv6.conf.eth0.accept_ra = 2 # 在eth0接口(公网出口)上允许接收RA。同时保持IPv6报文转发。
还有 /etc/network/interfaces 里面要加入tap0设备:
auto tap0
iface tap0 inet static
address 10.99.0.1 # IPv4地址
netmask 255.255.255.0iface tap0 inet6 static
address 2600:3c01:xxxx:xx01::1 # IPv6地址。这个网段全是路由
netmask 64
服务器端OpenVPN启动之后,tap0是未配置的。我们需要手动 ifup tap0 一下。
在OpenWRT上,配置 /etc/config/network :
config interface ‘wan6’
option ifname ‘tap0’
option proto ‘static’
option ip6addr ‘2600:3c01:xxxx:xx01::2/64’ # 路由器网段。每一个路由器一个IP
option ip6gw ‘2600:3c01:xxxx:xx01::1’ # 网关。OpenVPN服务器的IP
option ip6prefix ‘2600:3c01:xxxx:xx02::/64’ # 内网网段。就是上面的子网1,子网2……这里的IP是分配给每台电脑的config interface ‘lan’
option ip6assign 64 # 默认是60。需要改成64。符合上面写的掩码长度。
重启OpenWRT,待OpenVPN连上后,应该可以ping到服务器的IPv4和IPv6地址。同时,也应该可以ping到任何一个公网IPv6地址。另外,每一台连接到这个路由上的电脑应该可以获得一个IPv6地址。不过,在电脑上应当只能ping通路由器的IPv6地址而ping不到服务器或者公网。这是因为电脑分配到的IPv6地址所在的网段在服务器上并无路由。
在服务器上执行:
sudo route -A inet6 add 2600:3c01:xxxx:xx02::/64 gw 2600:3c01:xxxx:xx01::2
后,电脑上应该可以任意访问IPv6网络了。
对于DNS污染的问题,在OpenWRT上可以这样解决:
方法一: 使用IPv6的DNS服务器
方法二: 在境外架设非标准端口的DNS服务器(比如使用端口5353而不是默认的53)
/etc/config/dhcp 配置如下:
config dnsmasq
option domainneeded 1
option boguspriv 1
option filterwin2k 0 # enable for dial on demand
option localise_queries 1
option rebind_protection 1 # disable if upstream must serve RFC1918 addresses
option rebind_localhost 1 # enable for RBL checking and similar services
#list rebind_domain example.lan # whitelist RFC1918 responses for domains
option local ‘/whitebear.lan/’
option domain ‘whitebear.lan’
option expandhosts 1
option nonegcache 0
option authoritative 1
option readethers 1
option leasefile ‘/tmp/dhcp.leases’
option resolvfile ‘/tmp/resolv.conf.auto’
#list server ‘/mycompany.local/1.2.3.4’
#option nonwildcard 1
#list interface br-lan
#list notinterface lo
#list bogusnxdomain ‘64.94.110.11’
option noresolv 1 # 禁止读取resolv文件得到DNS服务器信息。设定这一行之后,可以防止OpenWRT不使用下面我们配置的DNS服务器。
list server ‘IP地址#端口’ # 方法二: 非标准端口的上游服务器。需要自己在境外架一台上游服务器。
list server ‘2001:4860:4860::8888’ # 方法一: IPv6的DNS服务器。这是Google Public DNS。
对于某些被路由黑洞的网站(如Twitter),可以通过配置静态路由的方法解决:
在OpenWRT上配置 /etc/config/network :
config ‘route’ ‘twitter’
option ‘interface’ ‘lan’
option ‘target’ ‘199.59.0.0’ # 目标网络
option ‘netmask’ ‘255.255.0.0’ # 掩码
option ‘gateway’ ‘10.99.0.1’ # 这里是OpenVPN服务器的内网IPv4地址。
不过服务器上需要配置一下NAT:
<br></br>sudo iptables -t nat -A POSTROUTING -s 10.99.0.0/24 -o eth0 -j MASQUERADE<br></br>