tun_linux.go 11 KB

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