tun_linux.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. // 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. if config.AllowNoIPv6NetworkConfiguration {
  175. config.Logger.WithContextFields(
  176. common.LogFields{
  177. "error": err}).Warning(
  178. "assign IPv6 address failed")
  179. } else {
  180. return common.ContextError(err)
  181. }
  182. }
  183. egressInterface := config.EgressInterface
  184. if egressInterface == "" {
  185. egressInterface = DEFAULT_PUBLIC_INTERFACE_NAME
  186. }
  187. // NAT tun device to external interface
  188. // TODO: need only set forwarding for specific interfaces?
  189. err = runNetworkConfigCommand(
  190. config.Logger,
  191. config.SudoNetworkConfigCommands,
  192. "sysctl",
  193. "net.ipv4.conf.all.forwarding=1")
  194. if err != nil {
  195. return common.ContextError(err)
  196. }
  197. err = runNetworkConfigCommand(
  198. config.Logger,
  199. config.SudoNetworkConfigCommands,
  200. "sysctl",
  201. "net.ipv6.conf.all.forwarding=1")
  202. if err != nil {
  203. if config.AllowNoIPv6NetworkConfiguration {
  204. config.Logger.WithContextFields(
  205. common.LogFields{
  206. "error": err}).Warning(
  207. "allow IPv6 forwarding failed")
  208. } else {
  209. return common.ContextError(err)
  210. }
  211. }
  212. // To avoid duplicates, first try to drop existing rule, then add
  213. for _, mode := range []string{"-D", "-A"} {
  214. err = runNetworkConfigCommand(
  215. config.Logger,
  216. config.SudoNetworkConfigCommands,
  217. "iptables",
  218. "-t", "nat",
  219. mode, "POSTROUTING",
  220. "-s", privateSubnetIPv4.String(),
  221. "-o", egressInterface,
  222. "-j", "MASQUERADE")
  223. if mode != "-D" && err != nil {
  224. return common.ContextError(err)
  225. }
  226. err = runNetworkConfigCommand(
  227. config.Logger,
  228. config.SudoNetworkConfigCommands,
  229. "ip6tables",
  230. "-t", "nat",
  231. mode, "POSTROUTING",
  232. "-s", privateSubnetIPv6.String(),
  233. "-o", egressInterface,
  234. "-j", "MASQUERADE")
  235. if mode != "-D" && err != nil {
  236. if config.AllowNoIPv6NetworkConfiguration {
  237. config.Logger.WithContextFields(
  238. common.LogFields{
  239. "error": err}).Warning(
  240. "configure IPv6 masquerading failed")
  241. } else {
  242. return common.ContextError(err)
  243. }
  244. }
  245. }
  246. return nil
  247. }
  248. func configureClientInterface(
  249. config *ClientConfig,
  250. tunDeviceName string) error {
  251. // Set tun device network addresses and MTU
  252. IPv4Address, IPv4Netmask, err := splitIPMask(config.IPv4AddressCIDR)
  253. if err != nil {
  254. return common.ContextError(err)
  255. }
  256. err = runNetworkConfigCommand(
  257. config.Logger,
  258. config.SudoNetworkConfigCommands,
  259. "ifconfig",
  260. tunDeviceName,
  261. IPv4Address,
  262. "netmask", IPv4Netmask,
  263. "mtu", strconv.Itoa(getMTU(config.MTU)),
  264. "up")
  265. if err != nil {
  266. return common.ContextError(err)
  267. }
  268. err = runNetworkConfigCommand(
  269. config.Logger,
  270. config.SudoNetworkConfigCommands,
  271. "ifconfig",
  272. tunDeviceName,
  273. "add", config.IPv6AddressCIDR)
  274. if err != nil {
  275. if config.AllowNoIPv6NetworkConfiguration {
  276. config.Logger.WithContextFields(
  277. common.LogFields{
  278. "error": err}).Warning(
  279. "assign IPv6 address failed")
  280. } else {
  281. return common.ContextError(err)
  282. }
  283. }
  284. // Set routing. Routes set here should automatically
  285. // drop when the tun device is removed.
  286. // TODO: appear to need explict routing only for IPv6?
  287. for _, destination := range config.RouteDestinations {
  288. // Destination may be host (IP) or network (CIDR)
  289. IP := net.ParseIP(destination)
  290. if IP == nil {
  291. var err error
  292. IP, _, err = net.ParseCIDR(destination)
  293. if err != nil {
  294. return common.ContextError(err)
  295. }
  296. }
  297. if IP.To4() != nil {
  298. continue
  299. }
  300. // Note: use "replace" instead of "add" as route from
  301. // previous run (e.g., tun_test case) may not yet be cleared.
  302. err = runNetworkConfigCommand(
  303. config.Logger,
  304. config.SudoNetworkConfigCommands,
  305. "ip",
  306. "-6",
  307. "route", "replace",
  308. destination,
  309. "dev", tunDeviceName)
  310. if err != nil {
  311. if config.AllowNoIPv6NetworkConfiguration {
  312. config.Logger.WithContextFields(
  313. common.LogFields{
  314. "error": err}).Warning("add IPv6 route failed")
  315. } else {
  316. return common.ContextError(err)
  317. }
  318. }
  319. }
  320. return nil
  321. }
  322. func fixBindToDevice(logger common.Logger, useSudo bool, tunDeviceName string) error {
  323. // Fix the problem described here:
  324. // https://stackoverflow.com/questions/24011205/cant-perform-tcp-handshake-through-a-nat-between-two-nics-with-so-bindtodevice/
  325. err := runNetworkConfigCommand(
  326. logger,
  327. useSudo,
  328. "sysctl",
  329. "net.ipv4.conf.all.accept_local=1")
  330. if err != nil {
  331. return common.ContextError(err)
  332. }
  333. err = runNetworkConfigCommand(
  334. logger,
  335. useSudo,
  336. "sysctl",
  337. "net.ipv4.conf.all.rp_filter=0")
  338. if err != nil {
  339. return common.ContextError(err)
  340. }
  341. err = runNetworkConfigCommand(
  342. logger,
  343. useSudo,
  344. "sysctl",
  345. fmt.Sprintf("net.ipv4.conf.%s.rp_filter=0", tunDeviceName))
  346. if err != nil {
  347. return common.ContextError(err)
  348. }
  349. return nil
  350. }