packetman_linux.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. /*
  2. * Copyright (c) 2020, 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 packetman
  20. import (
  21. "context"
  22. "encoding/binary"
  23. "log"
  24. "net"
  25. "strconv"
  26. "strings"
  27. "sync"
  28. "syscall"
  29. "time"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  32. "github.com/florianl/go-nfqueue"
  33. "github.com/google/gopacket"
  34. "github.com/google/gopacket/layers"
  35. cache "github.com/patrickmn/go-cache"
  36. )
  37. func IsSupported() bool {
  38. return true
  39. }
  40. const (
  41. netlinkSocketIOTimeout = 10 * time.Millisecond
  42. defaultSocketMark = 0x70736970 // "PSIP"
  43. appliedSpecCacheTTL = 1 * time.Minute
  44. )
  45. // Manipulator is a SYN-ACK packet manipulator.
  46. //
  47. // NFQUEUE/Netlink is used to intercept SYN-ACK packets, on all local
  48. // interfaces, with source port equal to one of the ProtocolPorts specified in
  49. // Config. For each intercepted SYN-ACK packet, the SelectSpecName callback in
  50. // Config is invoked; the callback determines which packet transformation spec
  51. // to apply, based on, for example, client GeoIP, protocol, or other
  52. // considerations.
  53. //
  54. // Protocol network listeners use GetAppliedSpecName to determine which
  55. // transformation spec was applied to a given accepted connection.
  56. //
  57. // When a manipulations are to be applied to a SYN-ACK packet, NFQUEUE is
  58. // instructed to drop the packet and one or more new packets, created by
  59. // applying transformations to the original SYN-ACK packet, are injected via
  60. // raw sockets. Raw sockets are used as NFQUEUE supports only replacing the
  61. // original packet with one alternative packet.
  62. //
  63. // To avoid an intercept loop, injected packets are marked (SO_MARK) and the
  64. // filter for NFQUEUE excludes packets with this mark.
  65. //
  66. // To avoid breaking TCP in unexpected cases, Manipulator fails open --
  67. // allowing the original packet to proceed -- when packet parsing fails. For
  68. // the same reason, the queue-bypass NFQUEUE option is set.
  69. //
  70. // As an iptables filter ensures only SYN-ACK packets are sent to the
  71. // NFQUEUEs, the overhead of packet interception, parsing, and injection is
  72. // incurred no more than once per TCP connection.
  73. //
  74. // NFQUEUE with queue-bypass requires Linux kernel 2.6.39; 3.16 or later is
  75. // validated and recommended.
  76. type Manipulator struct {
  77. config *Config
  78. mutex sync.Mutex
  79. runContext context.Context
  80. stopRunning context.CancelFunc
  81. waitGroup *sync.WaitGroup
  82. injectIPv4FD int
  83. injectIPv6FD int
  84. nfqueue *nfqueue.Nfqueue
  85. compiledSpecsMutex sync.Mutex
  86. compiledSpecs map[string]*compiledSpec
  87. appliedSpecCache *cache.Cache
  88. }
  89. // NewManipulator creates a new Manipulator.
  90. func NewManipulator(config *Config) (*Manipulator, error) {
  91. m := &Manipulator{
  92. config: config,
  93. }
  94. err := m.SetSpecs(config.Specs)
  95. if err != nil {
  96. return nil, errors.Trace(err)
  97. }
  98. // To avoid memory exhaustion, do not retain unconsumed appliedSpecCache
  99. // entries for a longer time than it may reasonably take to complete the TCP
  100. // handshake.
  101. m.appliedSpecCache = cache.New(appliedSpecCacheTTL, appliedSpecCacheTTL/2)
  102. return m, nil
  103. }
  104. // Start initializes NFQUEUEs and raw sockets for packet manipulation. Start
  105. // returns when initialization is complete; once it returns, the caller may
  106. // assume that any SYN-ACK packets on configured ports will be intercepted. In
  107. // the case of initialization failure, Start will undo any partial
  108. // initialization. When Start succeeds, the caller must call Stop to free
  109. // resources and restore networking state.
  110. func (m *Manipulator) Start() (retErr error) {
  111. m.mutex.Lock()
  112. defer m.mutex.Unlock()
  113. if m.runContext != nil {
  114. return errors.TraceNew("already running")
  115. }
  116. err := m.configureIPTables(true)
  117. if err != nil {
  118. return errors.Trace(err)
  119. }
  120. defer func() {
  121. if retErr != nil {
  122. m.configureIPTables(false)
  123. }
  124. }()
  125. m.injectIPv4FD, err = syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_RAW)
  126. if err != nil {
  127. return errors.Trace(err)
  128. }
  129. defer func() {
  130. if retErr != nil {
  131. syscall.Close(m.injectIPv4FD)
  132. }
  133. }()
  134. err = syscall.SetsockoptInt(m.injectIPv4FD, syscall.IPPROTO_IP, syscall.IP_HDRINCL, 1)
  135. if err != nil {
  136. return errors.Trace(err)
  137. }
  138. err = syscall.SetsockoptInt(m.injectIPv4FD, syscall.SOL_SOCKET, syscall.SO_MARK, m.getSocketMark())
  139. if err != nil {
  140. return errors.Trace(err)
  141. }
  142. m.injectIPv6FD, err = syscall.Socket(syscall.AF_INET6, syscall.SOCK_RAW, syscall.IPPROTO_RAW)
  143. if err != nil && !m.config.AllowNoIPv6NetworkConfiguration {
  144. return errors.Trace(err)
  145. }
  146. defer func() {
  147. if retErr != nil {
  148. syscall.Close(m.injectIPv6FD)
  149. }
  150. }()
  151. if m.injectIPv6FD != 0 {
  152. err = syscall.SetsockoptInt(m.injectIPv6FD, syscall.IPPROTO_IPV6, syscall.IP_HDRINCL, 1)
  153. if err != nil {
  154. // There's no AllowNoIPv6NetworkConfiguration in this case: if we can
  155. // create an IPv6 socket, we must be able to set its options.
  156. return errors.Trace(err)
  157. }
  158. err = syscall.SetsockoptInt(m.injectIPv6FD, syscall.SOL_SOCKET, syscall.SO_MARK, m.getSocketMark())
  159. if err != nil {
  160. return errors.Trace(err)
  161. }
  162. }
  163. // Use a reasonable buffer size to avoid excess allocation. As we're
  164. // intercepting only locally generated SYN-ACK packets, which should have no
  165. // payload, this size should be more than sufficient.
  166. maxPacketLen := uint32(1500)
  167. // Use the kernel default of 1024:
  168. // https://github.com/torvalds/linux/blob/cd8dead0c39457e58ec1d36db93aedca811d48f1/net/netfilter/nfnetlink_queue.c#L51,
  169. // via https://github.com/florianl/go-nfqueue/issues/3.
  170. maxQueueLen := uint32(1024)
  171. // Note: runContext alone is not sufficient to interrupt the
  172. // nfqueue.socketCallback goroutine spawned by nfqueue.Register; timeouts
  173. // must be set. See comment in Manipulator.Stop.
  174. m.nfqueue, err = nfqueue.Open(
  175. &nfqueue.Config{
  176. NfQueue: uint16(m.config.QueueNumber),
  177. MaxPacketLen: maxPacketLen,
  178. MaxQueueLen: maxQueueLen,
  179. Copymode: nfqueue.NfQnlCopyPacket,
  180. Logger: newNfqueueLogger(m.config.Logger),
  181. ReadTimeout: netlinkSocketIOTimeout,
  182. WriteTimeout: netlinkSocketIOTimeout,
  183. })
  184. if err != nil {
  185. return errors.Trace(err)
  186. }
  187. defer func() {
  188. if retErr != nil {
  189. m.nfqueue.Close()
  190. }
  191. }()
  192. runContext, stopRunning := context.WithCancel(context.Background())
  193. defer func() {
  194. if retErr != nil {
  195. stopRunning()
  196. }
  197. }()
  198. err = m.nfqueue.Register(runContext, m.handleInterceptedPacket)
  199. if err != nil {
  200. return errors.Trace(err)
  201. }
  202. m.runContext = runContext
  203. m.stopRunning = stopRunning
  204. return nil
  205. }
  206. // Stop halts packet manipulation, frees resources, and restores networking
  207. // state.
  208. func (m *Manipulator) Stop() {
  209. m.mutex.Lock()
  210. defer m.mutex.Unlock()
  211. if m.runContext == nil {
  212. return
  213. }
  214. m.stopRunning()
  215. // stopRunning will cancel the context passed into nfqueue.Register. The
  216. // goroutine spawned by Register, nfqueue.socketCallback, polls the context
  217. // after a read timeout:
  218. // https://github.com/florianl/go-nfqueue/blob/1e38df738c06deffbac08da8fec4b7c28a69b918/nfqueue_gteq_1.12.go#L138-L146
  219. //
  220. // There's no stop synchronization exposed by nfqueue. Calling nfqueue.Close
  221. // while socketCallback is still running can result in errors such as
  222. // "nfqueuenfqueue_gteq_1.12.go:134: Could not unbind from queue: netlink
  223. // send: sendmsg: bad file descriptor".
  224. //
  225. // To avoid invalid file descriptor operations and spurious error messages,
  226. // sleep for two polling periods, which should be sufficient, in most cases,
  227. // for socketCallback to poll the context and exit.
  228. time.Sleep(2 * netlinkSocketIOTimeout)
  229. m.nfqueue.Close()
  230. syscall.Close(m.injectIPv4FD)
  231. if m.injectIPv6FD != 0 {
  232. syscall.Close(m.injectIPv6FD)
  233. }
  234. m.configureIPTables(false)
  235. }
  236. // SetSpecs installs a new set of packet transformation Spec values, replacing
  237. // the initial specs from Config.Specs, or any previous SetSpecs call. When
  238. // SetSpecs returns an error, the previous set of specs is retained.
  239. func (m *Manipulator) SetSpecs(specs []*Spec) error {
  240. compiledSpecs := make(map[string]*compiledSpec)
  241. for _, spec := range specs {
  242. if spec.Name == "" {
  243. return errors.TraceNew("invalid spec name")
  244. }
  245. if _, ok := compiledSpecs[spec.Name]; ok {
  246. return errors.TraceNew("duplicate spec name")
  247. }
  248. compiledSpec, err := compileSpec(spec)
  249. if err != nil {
  250. return errors.Trace(err)
  251. }
  252. compiledSpecs[spec.Name] = compiledSpec
  253. }
  254. m.compiledSpecsMutex.Lock()
  255. m.compiledSpecs = compiledSpecs
  256. m.compiledSpecsMutex.Unlock()
  257. return nil
  258. }
  259. func makeConnectionID(
  260. srcIP net.IP, srcPort uint16, dstIP net.IP, dstPort uint16) string {
  261. // Create a unique connection ID, for appliedSpecCache, from the 4-tuple
  262. // srcIP, dstIP, srcPort, dstPort. In the SYN/ACK context, src is the server
  263. // and dst is the client.
  264. //
  265. // Limitation: there may be many repeat connections from one dstIP,
  266. // especially if many clients are behind the same NAT. Each TCP connection
  267. // will have a distinct dstPort. In principle, there remains a race between
  268. // populating appliedSpecCache, the TCP connection terminating on the
  269. // client-side and the NAT reusing the dstPort, and consuming
  270. // appliedSpecCache.
  271. // From: https://github.com/golang/go/blob/b88efc7e7ac15f9e0b5d8d9c82f870294f6a3839/src/net/ip.go#L55
  272. var v4InV6Prefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}
  273. const uint16Len = 2
  274. var connID [net.IPv6len + uint16Len + net.IPv6len + uint16Len]byte
  275. offset := 0
  276. if len(srcIP) == net.IPv4len {
  277. copy(connID[offset:], v4InV6Prefix)
  278. offset += len(v4InV6Prefix)
  279. copy(connID[offset:], srcIP)
  280. offset += len(srcIP)
  281. } else { // net.IPv6len
  282. copy(connID[offset:], srcIP)
  283. offset += len(srcIP)
  284. }
  285. binary.BigEndian.PutUint16(connID[offset:], srcPort)
  286. offset += uint16Len
  287. if len(dstIP) == net.IPv4len {
  288. copy(connID[offset:], v4InV6Prefix)
  289. offset += len(v4InV6Prefix)
  290. copy(connID[offset:], dstIP)
  291. offset += len(dstIP)
  292. } else { // net.IPv6len
  293. copy(connID[offset:], dstIP)
  294. offset += len(dstIP)
  295. }
  296. binary.BigEndian.PutUint16(connID[offset:], dstPort)
  297. offset += uint16Len
  298. return string(connID[:])
  299. }
  300. // GetAppliedSpecName returns the packet manipulation spec name applied to the
  301. // TCP connection, represented by its local and remote address components,
  302. // that was ultimately accepted by a network listener.
  303. //
  304. // This allows SelectSpecName, the spec selector, to be non-deterministic
  305. // while also allowing for accurate packet manipulation metrics to be
  306. // associated with each TCP connection.
  307. //
  308. // For a given connection, GetAppliedSpecName must be called before a TTL
  309. // clears the stored value. Calling GetAppliedSpecName immediately clears the
  310. // stored value for the given connection.
  311. //
  312. // To obtain the correct result GetAppliedSpecName must be called with a
  313. // RemoteAddr which reflects the true immediate network peer address. In
  314. // particular, for proxied net.Conns which present a synthetic RemoteAddr with
  315. // the original address of a proxied client (e.g., armon/go-proxyproto, or
  316. // psiphon/server.meekConn) the true peer RemoteAddr must instead be
  317. // provided.
  318. func (m *Manipulator) GetAppliedSpecName(
  319. localAddr, remoteAddr *net.TCPAddr) (string, error) {
  320. connID := makeConnectionID(
  321. localAddr.IP,
  322. uint16(localAddr.Port),
  323. remoteAddr.IP,
  324. uint16(remoteAddr.Port))
  325. specName, found := m.appliedSpecCache.Get(connID)
  326. if !found {
  327. return "", errors.TraceNew("connection not found")
  328. }
  329. m.appliedSpecCache.Delete(connID)
  330. return specName.(string), nil
  331. }
  332. func (m *Manipulator) setAppliedSpecName(
  333. interceptedPacket gopacket.Packet, specName string) {
  334. srcIP, dstIP, _, _ := m.getPacketAddressInfo(interceptedPacket)
  335. interceptedTCP := interceptedPacket.Layer(layers.LayerTypeTCP).(*layers.TCP)
  336. connID := makeConnectionID(
  337. srcIP,
  338. uint16(interceptedTCP.SrcPort),
  339. dstIP,
  340. uint16(interceptedTCP.DstPort))
  341. m.appliedSpecCache.Set(connID, specName, cache.DefaultExpiration)
  342. }
  343. func (m *Manipulator) getSocketMark() int {
  344. if m.config.SocketMark == 0 {
  345. return defaultSocketMark
  346. }
  347. return m.config.SocketMark
  348. }
  349. func (m *Manipulator) handleInterceptedPacket(attr nfqueue.Attribute) int {
  350. if attr.PacketID == nil || attr.Payload == nil {
  351. m.config.Logger.WithTrace().Warning("missing nfqueue data")
  352. return 0
  353. }
  354. // Trigger packet manipulation only if the packet is a SYN-ACK and has no
  355. // payload (which a transformation _may_ discard). The iptables filter for
  356. // NFQUEUE should already ensure that only SYN-ACK packets are sent through
  357. // the queue. To avoid breaking all TCP connections in an unanticipated case,
  358. // fail open -- allow the packet -- if these conditions are not met or if
  359. // parsing the packet fails.
  360. packet, err := m.parseInterceptedPacket(*attr.Payload)
  361. if err != nil {
  362. // Fail open in this case.
  363. m.nfqueue.SetVerdict(*attr.PacketID, nfqueue.NfAccept)
  364. m.config.Logger.WithTraceFields(
  365. common.LogFields{"error": err}).Warning("unexpected packet")
  366. return 0
  367. }
  368. spec, err := m.getCompiledSpec(packet)
  369. if err != nil {
  370. // Fail open in this case.
  371. m.nfqueue.SetVerdict(*attr.PacketID, nfqueue.NfAccept)
  372. m.config.Logger.WithTraceFields(
  373. common.LogFields{"error": err}).Warning("get strategy failed")
  374. return 0
  375. }
  376. // Call setAppliedSpecName cache _before_ accepting the packet or injecting
  377. // manipulated packets to avoid a potential race in which the TCP handshake
  378. // completes and GetAppliedSpecName is called before the cache is populated.
  379. if spec == nil {
  380. // No packet manipulation in this case.
  381. m.setAppliedSpecName(packet, "")
  382. m.nfqueue.SetVerdict(*attr.PacketID, nfqueue.NfAccept)
  383. return 0
  384. }
  385. m.setAppliedSpecName(packet, spec.name)
  386. m.nfqueue.SetVerdict(*attr.PacketID, nfqueue.NfDrop)
  387. err = m.injectPackets(packet, spec)
  388. if err != nil {
  389. m.config.Logger.WithTraceFields(
  390. common.LogFields{"error": err}).Warning("inject packets failed")
  391. return 0
  392. }
  393. return 0
  394. }
  395. func (m *Manipulator) parseInterceptedPacket(packetData []byte) (gopacket.Packet, error) {
  396. // Note that NFQUEUE doesn't send an Ethernet layer. This first layer is
  397. // either IPv4 or IPv6.
  398. //
  399. // As we parse only one packet per TCP connection, we are not using the
  400. // faster DecodingLayerParser API,
  401. // https://godoc.org/github.com/google/gopacket#hdr-Fast_Decoding_With_DecodingLayerParser,
  402. // or zero-copy approaches.
  403. //
  404. // TODO: use a stub gopacket.Decoder as the first layer to avoid the extra
  405. // NewPacket call? Use distinct NFQUEUE queue numbers and nfqueue instances
  406. // for IPv4 and IPv6?
  407. packet := gopacket.NewPacket(packetData, layers.LayerTypeIPv4, gopacket.Default)
  408. if packet.ErrorLayer() != nil {
  409. packet = gopacket.NewPacket(packetData, layers.LayerTypeIPv6, gopacket.Default)
  410. }
  411. errLayer := packet.ErrorLayer()
  412. if errLayer != nil {
  413. return nil, errors.Trace(errLayer.Error())
  414. }
  415. // After this check, Layer([IPv4,IPv6]/TCP) return values are assumed to be
  416. // non-nil and unchecked layer type assertions are assumed safe.
  417. tcpLayer := packet.Layer(layers.LayerTypeTCP)
  418. if tcpLayer == nil {
  419. return nil, errors.TraceNew("missing TCP layer")
  420. }
  421. if packet.Layer(gopacket.LayerTypePayload) != nil {
  422. return nil, errors.TraceNew("unexpected payload layer")
  423. }
  424. tcp := tcpLayer.(*layers.TCP)
  425. // Any of the ECN TCP flags (https://tools.ietf.org/html/rfc3168 and
  426. // rfc3540), ECE/CWR/NS, may be set in a SYN-ACK, and are retained.
  427. //
  428. // Limitation: these additional flags are retained as-is on injected packets
  429. // only when no TCP flag transformation is applied.
  430. if !tcp.SYN || !tcp.ACK ||
  431. tcp.FIN || tcp.RST || tcp.PSH || tcp.URG {
  432. return nil, errors.TraceNew("unexpected TCP flags")
  433. }
  434. stripEOLOption(packet)
  435. return packet, nil
  436. }
  437. func (m *Manipulator) getCompiledSpec(interceptedPacket gopacket.Packet) (*compiledSpec, error) {
  438. _, dstIP, _, _ := m.getPacketAddressInfo(interceptedPacket)
  439. interceptedTCP := interceptedPacket.Layer(layers.LayerTypeTCP).(*layers.TCP)
  440. protocolPort := interceptedTCP.SrcPort
  441. clientIP := dstIP
  442. specName := m.config.SelectSpecName(int(protocolPort), clientIP)
  443. if specName == "" {
  444. return nil, nil
  445. }
  446. // Concurrency note: m.compiledSpecs may be replaced by SetSpecs, but any
  447. // reference to an individual compiledSpec remains valid; each compiledSpec
  448. // is read-only.
  449. m.compiledSpecsMutex.Lock()
  450. spec, ok := m.compiledSpecs[specName]
  451. m.compiledSpecsMutex.Unlock()
  452. if !ok {
  453. return nil, errors.Tracef("invalid spec name: %s", specName)
  454. }
  455. return spec, nil
  456. }
  457. func (m *Manipulator) injectPackets(interceptedPacket gopacket.Packet, spec *compiledSpec) error {
  458. // A sockAddr parameter with dstIP (but not port) set appears to be required
  459. // even with the IP_HDRINCL socket option.
  460. _, _, injectFD, sockAddr := m.getPacketAddressInfo(interceptedPacket)
  461. injectPackets, err := spec.apply(interceptedPacket)
  462. if err != nil {
  463. return errors.Trace(err)
  464. }
  465. for _, injectPacket := range injectPackets {
  466. err = syscall.Sendto(injectFD, injectPacket, 0, sockAddr)
  467. if err != nil {
  468. return errors.Trace(err)
  469. }
  470. }
  471. return nil
  472. }
  473. func (m *Manipulator) getPacketAddressInfo(interceptedPacket gopacket.Packet) (net.IP, net.IP, int, syscall.Sockaddr) {
  474. var srcIP, dstIP net.IP
  475. var injectFD int
  476. var sockAddr syscall.Sockaddr
  477. ipv4Layer := interceptedPacket.Layer(layers.LayerTypeIPv4)
  478. if ipv4Layer != nil {
  479. interceptedIPv4 := ipv4Layer.(*layers.IPv4)
  480. srcIP = interceptedIPv4.SrcIP
  481. dstIP = interceptedIPv4.DstIP
  482. injectFD = m.injectIPv4FD
  483. var ipv4 [4]byte
  484. copy(ipv4[:], interceptedIPv4.DstIP.To4())
  485. sockAddr = &syscall.SockaddrInet4{Addr: ipv4, Port: 0}
  486. } else {
  487. interceptedIPv6 := interceptedPacket.Layer(layers.LayerTypeIPv6).(*layers.IPv6)
  488. srcIP = interceptedIPv6.SrcIP
  489. dstIP = interceptedIPv6.DstIP
  490. injectFD = m.injectIPv6FD
  491. var ipv6 [16]byte
  492. copy(ipv6[:], interceptedIPv6.DstIP.To16())
  493. sockAddr = &syscall.SockaddrInet6{Addr: ipv6, Port: 0}
  494. }
  495. return srcIP, dstIP, injectFD, sockAddr
  496. }
  497. func (m *Manipulator) configureIPTables(addRules bool) error {
  498. execCommands := func(mode string) error {
  499. ports := make([]string, len(m.config.ProtocolPorts))
  500. for i, port := range m.config.ProtocolPorts {
  501. ports[i] = strconv.Itoa(port)
  502. }
  503. socketMark := strconv.Itoa(m.getSocketMark())
  504. args := []string{
  505. mode, "OUTPUT",
  506. "--protocol", "tcp",
  507. "--match", "multiport",
  508. "--source-ports", strings.Join(ports, ","),
  509. "--match", "mark",
  510. "!", "--mark", socketMark,
  511. "--tcp-flags", "ALL", "SYN,ACK",
  512. "-j", "NFQUEUE",
  513. "--queue-bypass",
  514. "--queue-num", strconv.Itoa(m.config.QueueNumber),
  515. }
  516. err := common.RunNetworkConfigCommand(
  517. m.config.Logger,
  518. m.config.SudoNetworkConfigCommands,
  519. "iptables",
  520. args...)
  521. if mode != "-D" && err != nil {
  522. return errors.Trace(err)
  523. }
  524. err = common.RunNetworkConfigCommand(
  525. m.config.Logger,
  526. m.config.SudoNetworkConfigCommands,
  527. "ip6tables",
  528. args...)
  529. if mode != "-D" && err != nil {
  530. if m.config.AllowNoIPv6NetworkConfiguration {
  531. m.config.Logger.WithTraceFields(
  532. common.LogFields{
  533. "error": err}).Warning(
  534. "configure IPv6 NFQUEUE failed")
  535. } else {
  536. return errors.Trace(err)
  537. }
  538. }
  539. return nil
  540. }
  541. // To avoid duplicates, first try to drop existing rules, then add. Also try
  542. // to revert any partial configuration in the case of an error.
  543. _ = execCommands("-D")
  544. if addRules {
  545. err := execCommands("-I")
  546. if err != nil {
  547. _ = execCommands("-D")
  548. }
  549. return errors.Trace(err)
  550. }
  551. return nil
  552. }
  553. func newNfqueueLogger(logger common.Logger) *log.Logger {
  554. return log.New(
  555. &nfqueueLoggerWriter{logger: logger},
  556. "nfqueue",
  557. log.Lshortfile)
  558. }
  559. type nfqueueLoggerWriter struct {
  560. logger common.Logger
  561. }
  562. func (n *nfqueueLoggerWriter) Write(p []byte) (int, error) {
  563. n.logger.WithTraceFields(
  564. common.LogFields{"log": string(p)}).Warning("nfqueue log")
  565. return len(p), nil
  566. }