tun_linux.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. /*
  2. * Copyright (c) 2017, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package tun
  20. import (
  21. "fmt"
  22. "net"
  23. "os"
  24. "strconv"
  25. "strings"
  26. "syscall"
  27. "unsafe"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  30. )
  31. const (
  32. DEFAULT_PUBLIC_INTERFACE_NAME = "eth0"
  33. )
  34. func IsSupported() bool {
  35. return true
  36. }
  37. func makeDeviceInboundBuffer(MTU int) []byte {
  38. return make([]byte, MTU)
  39. }
  40. func makeDeviceOutboundBuffer(MTU int) []byte {
  41. // On Linux, no outbound buffer is used
  42. return nil
  43. }
  44. // OpenTunDevice opens a file for performing device I/O with
  45. // either a specified tun device, or a new tun device (when
  46. // name is "").
  47. func OpenTunDevice(name string) (*os.File, string, error) {
  48. // Prevent fork between creating fd and setting CLOEXEC
  49. syscall.ForkLock.RLock()
  50. defer syscall.ForkLock.RUnlock()
  51. // Requires process to run as root or have CAP_NET_ADMIN
  52. // This code follows snippets in this thread:
  53. // https://groups.google.com/forum/#!msg/golang-nuts/x_c_pZ6p95c/8T0JBZLpTwAJ
  54. file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
  55. if err != nil {
  56. return nil, "", errors.Trace(err)
  57. }
  58. // Set CLOEXEC so file descriptor not leaked to network config command subprocesses
  59. syscall.CloseOnExec(int(file.Fd()))
  60. // Definitions from <linux/if.h>, <linux/if_tun.h>
  61. // Note: using IFF_NO_PI, so packets have no size/flags header. This does mean
  62. // that if the MTU is changed after the tun device is initialized, packets could
  63. // be truncated when read.
  64. const (
  65. IFNAMSIZ = 16
  66. IF_REQ_PAD_SIZE = 40 - 18
  67. IFF_TUN = 0x0001
  68. IFF_NO_PI = 0x1000
  69. )
  70. var ifName [IFNAMSIZ]byte
  71. if name == "" {
  72. copy(ifName[:], []byte("tun%d"))
  73. } else {
  74. copy(ifName[:], []byte(name))
  75. }
  76. ifReq := struct {
  77. name [IFNAMSIZ]byte
  78. flags uint16
  79. pad [IF_REQ_PAD_SIZE]byte
  80. }{
  81. ifName,
  82. uint16(IFF_TUN | IFF_NO_PI),
  83. [IF_REQ_PAD_SIZE]byte{},
  84. }
  85. _, _, errno := syscall.Syscall(
  86. syscall.SYS_IOCTL,
  87. file.Fd(),
  88. uintptr(syscall.TUNSETIFF),
  89. uintptr(unsafe.Pointer(&ifReq)))
  90. if errno != 0 {
  91. file.Close()
  92. return nil, "", errors.Trace(errno)
  93. }
  94. deviceName := strings.Trim(string(ifReq.name[:]), "\x00")
  95. return file, deviceName, nil
  96. }
  97. func (device *Device) readTunPacket() (int, int, error) {
  98. // Assumes MTU passed to makeDeviceInboundBuffer is actual MTU and
  99. // so buffer is sufficiently large to always read a complete packet.
  100. n, err := device.deviceIO.Read(device.inboundBuffer)
  101. if err != nil {
  102. return 0, 0, errors.Trace(err)
  103. }
  104. return 0, n, nil
  105. }
  106. func (device *Device) writeTunPacket(packet []byte) error {
  107. // Doesn't need outboundBuffer since there's no header; write directly to device.
  108. _, err := device.deviceIO.Write(packet)
  109. if err != nil {
  110. return errors.Trace(err)
  111. }
  112. return nil
  113. }
  114. func resetNATTables(
  115. config *ServerConfig,
  116. IPAddress net.IP) error {
  117. // Uses the "conntrack" command, which is often not installed by default.
  118. // conntrack --delete -src-nat --orig-src <address> will clear NAT tables of existing
  119. // connections, making it less likely that traffic for a previous client using the
  120. // specified address will be forwarded to a new client using this address. This is in
  121. // the already unlikely event that there's still in-flight traffic when the address is
  122. // recycled.
  123. err := common.RunNetworkConfigCommand(
  124. config.Logger,
  125. config.SudoNetworkConfigCommands,
  126. "conntrack",
  127. "--delete",
  128. "--src-nat",
  129. "--orig-src",
  130. IPAddress.String())
  131. if err != nil {
  132. // conntrack exits with this error message when there are no flows
  133. // to delete, which is not a failure condition.
  134. if strings.Contains(err.Error(), "0 flow entries have been deleted") {
  135. return nil
  136. }
  137. return errors.Trace(err)
  138. }
  139. return nil
  140. }
  141. func configureServerInterface(
  142. config *ServerConfig,
  143. tunDeviceName string) error {
  144. // Set tun device network addresses and MTU
  145. IPv4Address, IPv4Netmask, err := splitIPMask(serverIPv4AddressCIDR)
  146. if err != nil {
  147. return errors.Trace(err)
  148. }
  149. err = common.RunNetworkConfigCommand(
  150. config.Logger,
  151. config.SudoNetworkConfigCommands,
  152. "ifconfig",
  153. tunDeviceName,
  154. IPv4Address, "netmask", IPv4Netmask,
  155. "mtu", strconv.Itoa(getMTU(config.MTU)),
  156. "up")
  157. if err != nil {
  158. return errors.Trace(err)
  159. }
  160. err = common.RunNetworkConfigCommand(
  161. config.Logger,
  162. config.SudoNetworkConfigCommands,
  163. "ifconfig",
  164. tunDeviceName,
  165. "add", serverIPv6AddressCIDR)
  166. if err != nil {
  167. if config.AllowNoIPv6NetworkConfiguration {
  168. config.Logger.WithTraceFields(
  169. common.LogFields{
  170. "error": err}).Warning(
  171. "assign IPv6 address failed")
  172. } else {
  173. return errors.Trace(err)
  174. }
  175. }
  176. egressInterface := config.EgressInterface
  177. if egressInterface == "" {
  178. egressInterface = DEFAULT_PUBLIC_INTERFACE_NAME
  179. }
  180. // NAT tun device to external interface
  181. // TODO: need only set forwarding for specific interfaces?
  182. err = common.RunNetworkConfigCommand(
  183. config.Logger,
  184. config.SudoNetworkConfigCommands,
  185. "sysctl",
  186. "net.ipv4.conf.all.forwarding=1")
  187. if err != nil {
  188. return errors.Trace(err)
  189. }
  190. err = common.RunNetworkConfigCommand(
  191. config.Logger,
  192. config.SudoNetworkConfigCommands,
  193. "sysctl",
  194. "net.ipv6.conf.all.forwarding=1")
  195. if err != nil {
  196. if config.AllowNoIPv6NetworkConfiguration {
  197. config.Logger.WithTraceFields(
  198. common.LogFields{
  199. "error": err}).Warning(
  200. "allow IPv6 forwarding failed")
  201. } else {
  202. return errors.Trace(err)
  203. }
  204. }
  205. // To avoid duplicates, first try to drop existing rule, then add
  206. for _, mode := range []string{"-D", "-A"} {
  207. err = common.RunNetworkConfigCommand(
  208. config.Logger,
  209. config.SudoNetworkConfigCommands,
  210. "iptables",
  211. "-t", "nat",
  212. mode, "POSTROUTING",
  213. "-s", privateSubnetIPv4.String(),
  214. "-o", egressInterface,
  215. "-j", "MASQUERADE")
  216. if mode != "-D" && err != nil {
  217. return errors.Trace(err)
  218. }
  219. err = common.RunNetworkConfigCommand(
  220. config.Logger,
  221. config.SudoNetworkConfigCommands,
  222. "ip6tables",
  223. "-t", "nat",
  224. mode, "POSTROUTING",
  225. "-s", privateSubnetIPv6.String(),
  226. "-o", egressInterface,
  227. "-j", "MASQUERADE")
  228. if mode != "-D" && err != nil {
  229. if config.AllowNoIPv6NetworkConfiguration {
  230. config.Logger.WithTraceFields(
  231. common.LogFields{
  232. "error": err}).Warning(
  233. "configure IPv6 masquerading failed")
  234. } else {
  235. return errors.Trace(err)
  236. }
  237. }
  238. }
  239. return nil
  240. }
  241. func configureClientInterface(
  242. config *ClientConfig,
  243. tunDeviceName string) error {
  244. // Set tun device network addresses and MTU
  245. IPv4Address, IPv4Netmask, err := splitIPMask(config.IPv4AddressCIDR)
  246. if err != nil {
  247. return errors.Trace(err)
  248. }
  249. err = common.RunNetworkConfigCommand(
  250. config.Logger,
  251. config.SudoNetworkConfigCommands,
  252. "ifconfig",
  253. tunDeviceName,
  254. IPv4Address,
  255. "netmask", IPv4Netmask,
  256. "mtu", strconv.Itoa(getMTU(config.MTU)),
  257. "up")
  258. if err != nil {
  259. return errors.Trace(err)
  260. }
  261. err = common.RunNetworkConfigCommand(
  262. config.Logger,
  263. config.SudoNetworkConfigCommands,
  264. "ifconfig",
  265. tunDeviceName,
  266. "add", config.IPv6AddressCIDR)
  267. if err != nil {
  268. if config.AllowNoIPv6NetworkConfiguration {
  269. config.Logger.WithTraceFields(
  270. common.LogFields{
  271. "error": err}).Warning(
  272. "assign IPv6 address failed")
  273. } else {
  274. return errors.Trace(err)
  275. }
  276. }
  277. // Set routing. Routes set here should automatically
  278. // drop when the tun device is removed.
  279. // TODO: appear to need explicit routing only for IPv6?
  280. for _, destination := range config.RouteDestinations {
  281. // Destination may be host (IP) or network (CIDR)
  282. IP := net.ParseIP(destination)
  283. if IP == nil {
  284. var err error
  285. IP, _, err = net.ParseCIDR(destination)
  286. if err != nil {
  287. return errors.Trace(err)
  288. }
  289. }
  290. if IP.To4() != nil {
  291. continue
  292. }
  293. // Note: use "replace" instead of "add" as route from
  294. // previous run (e.g., tun_test case) may not yet be cleared.
  295. err = common.RunNetworkConfigCommand(
  296. config.Logger,
  297. config.SudoNetworkConfigCommands,
  298. "ip",
  299. "-6",
  300. "route", "replace",
  301. destination,
  302. "dev", tunDeviceName)
  303. if err != nil {
  304. if config.AllowNoIPv6NetworkConfiguration {
  305. config.Logger.WithTraceFields(
  306. common.LogFields{
  307. "error": err}).Warning("add IPv6 route failed")
  308. } else {
  309. return errors.Trace(err)
  310. }
  311. }
  312. }
  313. return nil
  314. }
  315. // BindToDevice binds a socket to the specified interface.
  316. func BindToDevice(fd int, deviceName string) error {
  317. err := syscall.BindToDevice(fd, deviceName)
  318. if err != nil {
  319. return errors.Trace(err)
  320. }
  321. return nil
  322. }
  323. func fixBindToDevice(logger common.Logger, useSudo bool, tunDeviceName string) error {
  324. // Fix the problem described here:
  325. // https://stackoverflow.com/questions/24011205/cant-perform-tcp-handshake-through-a-nat-between-two-nics-with-so-bindtodevice/
  326. //
  327. // > the linux kernel is configured on certain mainstream distributions
  328. // > (Ubuntu...) to act as a router and drop packets where the source
  329. // > address is suspect in order to prevent spoofing (search "rp_filter" on
  330. // > https://www.kernel.org/doc/Documentation/networking/ip-sysctl.txt and
  331. // > RFC3704)
  332. err := common.RunNetworkConfigCommand(
  333. logger,
  334. useSudo,
  335. "sysctl",
  336. "net.ipv4.conf.all.accept_local=1")
  337. if err != nil {
  338. return errors.Trace(err)
  339. }
  340. err = common.RunNetworkConfigCommand(
  341. logger,
  342. useSudo,
  343. "sysctl",
  344. "net.ipv4.conf.all.rp_filter=0")
  345. if err != nil {
  346. return errors.Trace(err)
  347. }
  348. err = common.RunNetworkConfigCommand(
  349. logger,
  350. useSudo,
  351. "sysctl",
  352. fmt.Sprintf("net.ipv4.conf.%s.rp_filter=0", tunDeviceName))
  353. if err != nil {
  354. return errors.Trace(err)
  355. }
  356. return nil
  357. }