tun_linux.go 9.1 KB

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