tun_linux.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. "io"
  23. "net"
  24. "os"
  25. "strconv"
  26. "strings"
  27. "syscall"
  28. "unsafe"
  29. "github.com/Psiphon-Inc/gocapability/capability"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. )
  32. const (
  33. DEFAULT_PUBLIC_INTERFACE_NAME = "eth0"
  34. )
  35. func makeDeviceInboundBuffer(MTU int) []byte {
  36. return make([]byte, MTU)
  37. }
  38. func makeDeviceOutboundBuffer(MTU int) []byte {
  39. // On Linux, no outbound buffer is used.
  40. return nil
  41. }
  42. func createTunDevice() (io.ReadWriteCloser, string, error) {
  43. // Requires process to run as root or have CAP_NET_ADMIN.
  44. // This code follows snippets in this thread:
  45. // https://groups.google.com/forum/#!msg/golang-nuts/x_c_pZ6p95c/8T0JBZLpTwAJ
  46. file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
  47. if err != nil {
  48. return nil, "", common.ContextError(err)
  49. }
  50. // Definitions from <linux/if.h>, <linux/if_tun.h>
  51. // Note: using IFF_NO_PI, so packets have no size/flags header. This does mean
  52. // that if the MTU is changed after the tun device is initialized, packets could
  53. // be truncated when read.
  54. const (
  55. IFNAMSIZ = 16
  56. IF_REQ_PAD_SIZE = 40 - 18
  57. IFF_TUN = 0x0001
  58. IFF_NO_PI = 0x1000
  59. )
  60. var ifName [IFNAMSIZ]byte
  61. copy(ifName[:], []byte("tun%d"))
  62. ifReq := struct {
  63. name [IFNAMSIZ]byte
  64. flags uint16
  65. pad [IF_REQ_PAD_SIZE]byte
  66. }{
  67. ifName,
  68. uint16(IFF_TUN | IFF_NO_PI),
  69. [IF_REQ_PAD_SIZE]byte{},
  70. }
  71. _, _, errno := syscall.Syscall(
  72. syscall.SYS_IOCTL,
  73. file.Fd(),
  74. uintptr(syscall.TUNSETIFF),
  75. uintptr(unsafe.Pointer(&ifReq)))
  76. if errno != 0 {
  77. return nil, "", common.ContextError(errno)
  78. }
  79. deviceName := strings.Trim(string(ifReq.name[:]), "\x00")
  80. // TODO: set CLOEXEC on tun fds?
  81. // https://github.com/OpenVPN/openvpn/blob/3e4e300d6c5ea9c320e62def79e5b70f8e255248/src/openvpn/tun.c#L3060
  82. return file, deviceName, nil
  83. }
  84. func (device *Device) readTunPacket() (int, int, error) {
  85. // Assumes MTU passed to makeDeviceInboundBuffer is actual MTU and
  86. // so buffer is sufficiently large to always read a complete packet.
  87. n, err := device.deviceIO.Read(device.inboundBuffer)
  88. if err != nil {
  89. return 0, 0, common.ContextError(err)
  90. }
  91. return 0, n, nil
  92. }
  93. func (device *Device) writeTunPacket(packet []byte) error {
  94. // Doesn't need outboundBuffer since there's no header; write directly to device.
  95. _, err := device.deviceIO.Write(packet)
  96. if err != nil {
  97. return common.ContextError(err)
  98. }
  99. return nil
  100. }
  101. func configureNetworkConfigSubprocessCapabilities() error {
  102. // If this process has CAP_NET_ADMIN, make it available to be inherited
  103. // be child processes via ambient mechanism described here:
  104. // https://github.com/torvalds/linux/commit/58319057b7847667f0c9585b9de0e8932b0fdb08
  105. //
  106. // The ambient mechanim is available in Linux kernel 4.3 and later.
  107. // When using capabilities, this process should have CAP_NET_ADMIN in order
  108. // to create tun devices. And the subprocess operations such as using "ifconfig"
  109. // and "iptables" for network config require the same CAP_NET_ADMIN capability.
  110. cap, err := capability.NewPid(0)
  111. if err != nil {
  112. return common.ContextError(err)
  113. }
  114. if cap.Get(capability.EFFECTIVE, capability.CAP_NET_ADMIN) {
  115. cap.Set(capability.INHERITABLE|capability.AMBIENT, capability.CAP_NET_ADMIN)
  116. err = cap.Apply(capability.AMBIENT)
  117. if err != nil {
  118. return common.ContextError(err)
  119. }
  120. }
  121. return nil
  122. }
  123. func resetNATTables(
  124. config *ServerConfig,
  125. IPAddress net.IP) error {
  126. // Uses the "conntrack" command, which is often not installed by default.
  127. // conntrack --delete -src-nat --orig-src <address> will clear NAT tables of existing
  128. // connections, making it less likely that traffic for a previous client using the
  129. // specified address will be forwarded to a new client using this address. This is in
  130. // the already unlikely event that there's still in-flight traffic when the address is
  131. // recycled.
  132. err := runNetworkConfigCommand(
  133. config.Logger,
  134. config.SudoNetworkConfigCommands,
  135. "conntrack",
  136. "--delete",
  137. "--src-nat",
  138. "--orig-src",
  139. IPAddress.String())
  140. if err != nil {
  141. return common.ContextError(err)
  142. }
  143. return nil
  144. }
  145. func configureServerInterface(
  146. config *ServerConfig,
  147. tunDeviceName string) error {
  148. // Set tun device network addresses and MTU
  149. IPv4Address, IPv4Netmask, err := splitIPMask(serverIPv4AddressCIDR)
  150. if err != nil {
  151. return common.ContextError(err)
  152. }
  153. err = runNetworkConfigCommand(
  154. config.Logger,
  155. config.SudoNetworkConfigCommands,
  156. "ifconfig",
  157. tunDeviceName,
  158. IPv4Address, "netmask", IPv4Netmask,
  159. "mtu", strconv.Itoa(getMTU(config.MTU)),
  160. "up")
  161. if err != nil {
  162. return common.ContextError(err)
  163. }
  164. err = runNetworkConfigCommand(
  165. config.Logger,
  166. config.SudoNetworkConfigCommands,
  167. "ifconfig",
  168. tunDeviceName,
  169. "add", serverIPv6AddressCIDR)
  170. if err != nil {
  171. return common.ContextError(err)
  172. }
  173. egressInterface := config.EgressInterface
  174. if egressInterface == "" {
  175. egressInterface = DEFAULT_PUBLIC_INTERFACE_NAME
  176. }
  177. // NAT tun device to external interface
  178. // TODO: need only set forwarding for specific interfaces?
  179. err = runNetworkConfigCommand(
  180. config.Logger,
  181. config.SudoNetworkConfigCommands,
  182. "sysctl",
  183. "net.ipv4.conf.all.forwarding=1")
  184. if err != nil {
  185. return common.ContextError(err)
  186. }
  187. err = runNetworkConfigCommand(
  188. config.Logger,
  189. config.SudoNetworkConfigCommands,
  190. "sysctl",
  191. "net.ipv6.conf.all.forwarding=1")
  192. if err != nil {
  193. return common.ContextError(err)
  194. }
  195. // To avoid duplicates, first try to drop existing rule, then add
  196. for _, mode := range []string{"-D", "-A"} {
  197. err = runNetworkConfigCommand(
  198. config.Logger,
  199. config.SudoNetworkConfigCommands,
  200. "iptables",
  201. "-t", "nat",
  202. mode, "POSTROUTING",
  203. "-s", privateSubnetIPv4.String(),
  204. "-o", egressInterface,
  205. "-j", "MASQUERADE")
  206. if mode != "-D" && err != nil {
  207. return common.ContextError(err)
  208. }
  209. err = runNetworkConfigCommand(
  210. config.Logger,
  211. config.SudoNetworkConfigCommands,
  212. "ip6tables",
  213. "-t", "nat",
  214. mode, "POSTROUTING",
  215. "-s", privateSubnetIPv6.String(),
  216. "-o", egressInterface,
  217. "-j", "MASQUERADE")
  218. if mode != "-D" && err != nil {
  219. return common.ContextError(err)
  220. }
  221. }
  222. return nil
  223. }
  224. func configureClientInterface(
  225. config *ClientConfig,
  226. tunDeviceName string) error {
  227. // Set tun device network addresses and MTU
  228. IPv4Address, IPv4Netmask, err := splitIPMask(config.IPv4AddressCIDR)
  229. if err != nil {
  230. return common.ContextError(err)
  231. }
  232. err = runNetworkConfigCommand(
  233. config.Logger,
  234. config.SudoNetworkConfigCommands,
  235. "ifconfig",
  236. tunDeviceName,
  237. IPv4Address,
  238. "netmask", IPv4Netmask,
  239. "mtu", strconv.Itoa(getMTU(config.MTU)),
  240. "up")
  241. if err != nil {
  242. return common.ContextError(err)
  243. }
  244. err = runNetworkConfigCommand(
  245. config.Logger,
  246. config.SudoNetworkConfigCommands,
  247. "ifconfig",
  248. tunDeviceName,
  249. "add", config.IPv6AddressCIDR)
  250. if err != nil {
  251. return common.ContextError(err)
  252. }
  253. // Set routing. Routes set here should automatically
  254. // drop when the tun device is removed.
  255. // TODO: appear to need explict routing only for IPv6?
  256. for _, destination := range config.RouteDestinations {
  257. // Destination may be host (IP) or network (CIDR)
  258. IP := net.ParseIP(destination)
  259. if IP == nil {
  260. var err error
  261. IP, _, err = net.ParseCIDR(destination)
  262. if err != nil {
  263. return common.ContextError(err)
  264. }
  265. }
  266. if IP.To4() != nil {
  267. continue
  268. }
  269. // Note: use "replace" instead of "add" as route from
  270. // previous run (e.g., tun_test case) may not yet be cleared.
  271. err = runNetworkConfigCommand(
  272. config.Logger,
  273. config.SudoNetworkConfigCommands,
  274. "ip",
  275. "-6",
  276. "route", "replace",
  277. destination,
  278. "dev", tunDeviceName)
  279. if err != nil {
  280. return common.ContextError(err)
  281. }
  282. }
  283. return nil
  284. }
  285. func fixBindToDevice(logger common.Logger, useSudo bool, tunDeviceName string) error {
  286. // Fix the problem described here:
  287. // https://stackoverflow.com/questions/24011205/cant-perform-tcp-handshake-through-a-nat-between-two-nics-with-so-bindtodevice/
  288. err := runNetworkConfigCommand(
  289. logger,
  290. useSudo,
  291. "sysctl",
  292. "net.ipv4.conf.all.accept_local=1")
  293. if err != nil {
  294. return common.ContextError(err)
  295. }
  296. err = runNetworkConfigCommand(
  297. logger,
  298. useSudo,
  299. "sysctl",
  300. "net.ipv4.conf.all.rp_filter=0")
  301. if err != nil {
  302. return common.ContextError(err)
  303. }
  304. err = runNetworkConfigCommand(
  305. logger,
  306. useSudo,
  307. "sysctl",
  308. fmt.Sprintf("net.ipv4.conf.%s.rp_filter=0", tunDeviceName))
  309. if err != nil {
  310. return common.ContextError(err)
  311. }
  312. return nil
  313. }