tun_linux.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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/syndtr/gocapability/capability"
  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, "", common.ContextError(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, "", common.ContextError(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, common.ContextError(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 common.ContextError(err)
  111. }
  112. return nil
  113. }
  114. func configureNetworkConfigSubprocessCapabilities() error {
  115. // If this process has CAP_NET_ADMIN, make it available to be inherited
  116. // be child processes via ambient mechanism described here:
  117. // https://github.com/torvalds/linux/commit/58319057b7847667f0c9585b9de0e8932b0fdb08
  118. //
  119. // The ambient mechanism is available in Linux kernel 4.3 and later.
  120. // When using capabilities, this process should have CAP_NET_ADMIN in order
  121. // to create tun devices. And the subprocess operations such as using "ifconfig"
  122. // and "iptables" for network config require the same CAP_NET_ADMIN capability.
  123. cap, err := capability.NewPid(0)
  124. if err != nil {
  125. return common.ContextError(err)
  126. }
  127. if cap.Get(capability.EFFECTIVE, capability.CAP_NET_ADMIN) {
  128. cap.Set(capability.INHERITABLE|capability.AMBIENT, capability.CAP_NET_ADMIN)
  129. err = cap.Apply(capability.AMBIENT)
  130. if err != nil {
  131. return common.ContextError(err)
  132. }
  133. }
  134. return nil
  135. }
  136. func resetNATTables(
  137. config *ServerConfig,
  138. IPAddress net.IP) error {
  139. // Uses the "conntrack" command, which is often not installed by default.
  140. // conntrack --delete -src-nat --orig-src <address> will clear NAT tables of existing
  141. // connections, making it less likely that traffic for a previous client using the
  142. // specified address will be forwarded to a new client using this address. This is in
  143. // the already unlikely event that there's still in-flight traffic when the address is
  144. // recycled.
  145. err := runNetworkConfigCommand(
  146. config.Logger,
  147. config.SudoNetworkConfigCommands,
  148. "conntrack",
  149. "--delete",
  150. "--src-nat",
  151. "--orig-src",
  152. IPAddress.String())
  153. if err != nil {
  154. return common.ContextError(err)
  155. }
  156. return nil
  157. }
  158. func configureServerInterface(
  159. config *ServerConfig,
  160. tunDeviceName string) error {
  161. // Set tun device network addresses and MTU
  162. IPv4Address, IPv4Netmask, err := splitIPMask(serverIPv4AddressCIDR)
  163. if err != nil {
  164. return common.ContextError(err)
  165. }
  166. err = runNetworkConfigCommand(
  167. config.Logger,
  168. config.SudoNetworkConfigCommands,
  169. "ifconfig",
  170. tunDeviceName,
  171. IPv4Address, "netmask", IPv4Netmask,
  172. "mtu", strconv.Itoa(getMTU(config.MTU)),
  173. "up")
  174. if err != nil {
  175. return common.ContextError(err)
  176. }
  177. err = runNetworkConfigCommand(
  178. config.Logger,
  179. config.SudoNetworkConfigCommands,
  180. "ifconfig",
  181. tunDeviceName,
  182. "add", serverIPv6AddressCIDR)
  183. if err != nil {
  184. if config.AllowNoIPv6NetworkConfiguration {
  185. config.Logger.WithContextFields(
  186. common.LogFields{
  187. "error": err}).Warning(
  188. "assign IPv6 address failed")
  189. } else {
  190. return common.ContextError(err)
  191. }
  192. }
  193. egressInterface := config.EgressInterface
  194. if egressInterface == "" {
  195. egressInterface = DEFAULT_PUBLIC_INTERFACE_NAME
  196. }
  197. // NAT tun device to external interface
  198. // TODO: need only set forwarding for specific interfaces?
  199. err = runNetworkConfigCommand(
  200. config.Logger,
  201. config.SudoNetworkConfigCommands,
  202. "sysctl",
  203. "net.ipv4.conf.all.forwarding=1")
  204. if err != nil {
  205. return common.ContextError(err)
  206. }
  207. err = runNetworkConfigCommand(
  208. config.Logger,
  209. config.SudoNetworkConfigCommands,
  210. "sysctl",
  211. "net.ipv6.conf.all.forwarding=1")
  212. if err != nil {
  213. if config.AllowNoIPv6NetworkConfiguration {
  214. config.Logger.WithContextFields(
  215. common.LogFields{
  216. "error": err}).Warning(
  217. "allow IPv6 forwarding failed")
  218. } else {
  219. return common.ContextError(err)
  220. }
  221. }
  222. // To avoid duplicates, first try to drop existing rule, then add
  223. for _, mode := range []string{"-D", "-A"} {
  224. err = runNetworkConfigCommand(
  225. config.Logger,
  226. config.SudoNetworkConfigCommands,
  227. "iptables",
  228. "-t", "nat",
  229. mode, "POSTROUTING",
  230. "-s", privateSubnetIPv4.String(),
  231. "-o", egressInterface,
  232. "-j", "MASQUERADE")
  233. if mode != "-D" && err != nil {
  234. return common.ContextError(err)
  235. }
  236. err = runNetworkConfigCommand(
  237. config.Logger,
  238. config.SudoNetworkConfigCommands,
  239. "ip6tables",
  240. "-t", "nat",
  241. mode, "POSTROUTING",
  242. "-s", privateSubnetIPv6.String(),
  243. "-o", egressInterface,
  244. "-j", "MASQUERADE")
  245. if mode != "-D" && err != nil {
  246. if config.AllowNoIPv6NetworkConfiguration {
  247. config.Logger.WithContextFields(
  248. common.LogFields{
  249. "error": err}).Warning(
  250. "configure IPv6 masquerading failed")
  251. } else {
  252. return common.ContextError(err)
  253. }
  254. }
  255. }
  256. return nil
  257. }
  258. func configureClientInterface(
  259. config *ClientConfig,
  260. tunDeviceName string) error {
  261. // Set tun device network addresses and MTU
  262. IPv4Address, IPv4Netmask, err := splitIPMask(config.IPv4AddressCIDR)
  263. if err != nil {
  264. return common.ContextError(err)
  265. }
  266. err = runNetworkConfigCommand(
  267. config.Logger,
  268. config.SudoNetworkConfigCommands,
  269. "ifconfig",
  270. tunDeviceName,
  271. IPv4Address,
  272. "netmask", IPv4Netmask,
  273. "mtu", strconv.Itoa(getMTU(config.MTU)),
  274. "up")
  275. if err != nil {
  276. return common.ContextError(err)
  277. }
  278. err = runNetworkConfigCommand(
  279. config.Logger,
  280. config.SudoNetworkConfigCommands,
  281. "ifconfig",
  282. tunDeviceName,
  283. "add", config.IPv6AddressCIDR)
  284. if err != nil {
  285. if config.AllowNoIPv6NetworkConfiguration {
  286. config.Logger.WithContextFields(
  287. common.LogFields{
  288. "error": err}).Warning(
  289. "assign IPv6 address failed")
  290. } else {
  291. return common.ContextError(err)
  292. }
  293. }
  294. // Set routing. Routes set here should automatically
  295. // drop when the tun device is removed.
  296. // TODO: appear to need explicit routing only for IPv6?
  297. for _, destination := range config.RouteDestinations {
  298. // Destination may be host (IP) or network (CIDR)
  299. IP := net.ParseIP(destination)
  300. if IP == nil {
  301. var err error
  302. IP, _, err = net.ParseCIDR(destination)
  303. if err != nil {
  304. return common.ContextError(err)
  305. }
  306. }
  307. if IP.To4() != nil {
  308. continue
  309. }
  310. // Note: use "replace" instead of "add" as route from
  311. // previous run (e.g., tun_test case) may not yet be cleared.
  312. err = runNetworkConfigCommand(
  313. config.Logger,
  314. config.SudoNetworkConfigCommands,
  315. "ip",
  316. "-6",
  317. "route", "replace",
  318. destination,
  319. "dev", tunDeviceName)
  320. if err != nil {
  321. if config.AllowNoIPv6NetworkConfiguration {
  322. config.Logger.WithContextFields(
  323. common.LogFields{
  324. "error": err}).Warning("add IPv6 route failed")
  325. } else {
  326. return common.ContextError(err)
  327. }
  328. }
  329. }
  330. return nil
  331. }
  332. // BindToDevice binds a socket to the specified interface.
  333. func BindToDevice(fd int, deviceName string) error {
  334. err := syscall.BindToDevice(fd, deviceName)
  335. if err != nil {
  336. return common.ContextError(err)
  337. }
  338. return nil
  339. }
  340. func fixBindToDevice(logger common.Logger, useSudo bool, tunDeviceName string) error {
  341. // Fix the problem described here:
  342. // https://stackoverflow.com/questions/24011205/cant-perform-tcp-handshake-through-a-nat-between-two-nics-with-so-bindtodevice/
  343. err := runNetworkConfigCommand(
  344. logger,
  345. useSudo,
  346. "sysctl",
  347. "net.ipv4.conf.all.accept_local=1")
  348. if err != nil {
  349. return common.ContextError(err)
  350. }
  351. err = runNetworkConfigCommand(
  352. logger,
  353. useSudo,
  354. "sysctl",
  355. "net.ipv4.conf.all.rp_filter=0")
  356. if err != nil {
  357. return common.ContextError(err)
  358. }
  359. err = runNetworkConfigCommand(
  360. logger,
  361. useSudo,
  362. "sysctl",
  363. fmt.Sprintf("net.ipv4.conf.%s.rp_filter=0", tunDeviceName))
  364. if err != nil {
  365. return common.ContextError(err)
  366. }
  367. return nil
  368. }