GithubHelp home page GithubHelp logo

nfqueue-go's Introduction

nfqueue-go

Build Status GoDoc

nfqueue-go is a wrapper library for libnetfilter-queue. The goal is to provide a library to gain access to packets queued by the kernel packet filter.

It is important to note that these bindings will not follow blindly libnetfilter_queue API. For ex., some higher-level wrappers will be provided for the open/bind/create mechanism (using one function call instead of three).

The API is not yet stable.

To use the library, a program must

  • open a queue
  • bind to a network family (AF_PACKET for IPv4)
  • provide a callback function, which will be automatically called when a packet is received. The callback must return a verdict
  • create the queue, providing the queue number (which must match the --queue-num from the iptables rules, see below
  • run a loop, waiting for events. The program should also provide a clean way to exit the loop (for ex on SIGINT)

Using library

import "github.com/chifflier/nfqueue-go/nfqueue"

Example

See test_nfqueue for a minimal example, and test_nfqueue_gopacket for an example using the gopacket library to decode the packets.

IPtables

You must add rules in netfilter to send packets to the userspace queue. The number of the queue (--queue-num option in netfilter) must match the number provided to create_queue().

Example of iptables rules:

iptables -A OUTPUT --destination 1.2.3.4 -j NFQUEUE --queue-num 0

Of course, you should be more restrictive, depending on your needs.

Privileges

nfqueue-go does not require root privileges, but needs to open a netlink socket and send/receive packets to the kernel.

You have several options:

  • Use the CAP_NET_ADMIN capability in order to allow your application to receive from and to send packets to kernel-space: setcap 'cap_net_admin=+ep' /path/to/program
  • Run your program as root and drop privileges

License

This library is licensed under the GNU General Public License version 2, or (at your option) any later version.

nfqueue-go's People

Contributors

chifflier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

nfqueue-go's Issues

Build error from bettercap (dependency)

I don't know if this is the right place, but I'm trying to build bettercap inside a Docker and it balks at this:

github.com/chifflier/nfqueue-go/nfqueue

/go/pkg/mod/github.com/chifflier/[email protected]/nfqueue/nfqueue.go:187:29: could not determine kind of name for C.u_int16_t
/go/pkg/mod/github.com/chifflier/[email protected]/nfqueue/nfqueue.go:269:35: could not determine kind of name for C.u_int32_t
/go/pkg/mod/github.com/chifflier/[email protected]/nfqueue/nfqueue.go:257:27: could not determine kind of name for C.u_int8_t

My host OS runs go 1.18.5 and builds fine, but the Docker has 1.19.2 and I guess has the issue?

Package license

Hi, big thanks for your work on this package!

Sadly I can't find any information about code license. Can you please add some license file (MIT or BSD for example) to your repository?

Does nfqueque Handle TCP Replies?

Does nfqueue handle tcp sessions (replies to tcp packets)?
I wrote a tcp proxy client that sends tcp packets to server (server accepts tcp connections), but it doesn't work and I think it's because replies are not handled. Is it true?

Server shows no TCP connections accepted.

Should I check packet destination address and return NF_QUEUE for tcp replies?

package main

import (
  "net"
  "fmt"
  "syscall"
  "flag"
  "sync"

  "github.com/chifflier/nfqueue-go/nfqueue"
)

func run(payload *nfqueue.Payload) int {

  fmt.Println("run")
  handle(payload.Data)
  return nfqueue.NF_ACCEPT

}

func handle(data []byte) {

  fmt.Println("handle")
  toTCP, err := net.ResolveTCPAddr("tcp", *remoteAddr)
  if err != nil {
    panic(nil)
  }

  fmt.Println("dial")
  remote, err := net.DialTCP("tcp", nil, toTCP)
  if err != nil {
    panic(err)
  }
  defer remote.Close()

  fmt.Println("write data...")
  wcount, err := remote.Write(data)
  if err != nil {
    panic(err)
  }
  if wcount != len(data) {
    panic(fmt.Sprintf("Not all data written: %s/%s", wcount, len(data)))
  }

}

var remoteAddr *string = flag.String("r", "boom", "remote address")

func main() {

    flag.Parse();
    if *remoteAddr == "boom" {
      panic("Specify proxy server address!")
    }
    fmt.Println("Starting server...")

    q := new(nfqueue.Queue)

    q.SetCallback(run)

    q.Init()

    q.Unbind(syscall.AF_INET)
    q.Bind(syscall.AF_INET)

    q.CreateQueue(13)

    q.Loop()
    q.DestroyQueue()
    q.Close()

}
# Don't queue packets from proxyclient to proxyclient itself!
sudo iptables -A OUTPUT -p tcp -m tcp --dport 80  -j NFQUEUE --queue-num 13 -m owner ! --gid-owner proxyclient
sudo iptables -A OUTPUT -p tcp -m tcp --dport 443 -j NFQUEUE --queue-num 13 -m owner ! --gid-owner proxyclient

sudo -g proxyclient ./proxy-client -r $@
// server
listener, err := net.ListenTCP("tcp", p.fromTCP)
for each connection := listener.AcceptTCP() {
  packet := new TCPPacket(connection.readPayload())
  remote := net.DialTCP("tcp", nil, packet.destination)
  defer remote.Close()
  remote.Write(packet.asData)
}

Setting callback to method of a type

Hi all,
Is it possible to have a callback method which is of any specific type?
example:

type nfqCallback struct {
	pool *redis.Pool
} 
func(n nfqCallback) real_callback(payload *nfqueue.Payload) int {
   // access the pool here
}

// some where in main
w := nfqCallback{pool: p} 
queue.SetCallback(w.real_callback)

I tried to run the code but it panic'ed with the following trace.

panic: runtime error: cgo argument has Go pointer to Go pointer

goroutine 10 [running]:
panic(0x995e40, 0xc42120ecc0)
        /usr/local/go/src/runtime/panic.go:500 +0x1a1
bitbucket.org/acklio/vdm/vendor/github.com/chifflier/nfqueue-go/nfqueue._cgoCheckPointer0(0xc4212122a0, 0x0, 0x0, 0x0, 0x0)
        ??:0 +0x59
bitbucket.org/acklio/vdm/vendor/github.com/chifflier/nfqueue-go/nfqueue.(*Queue).CreateQueue(0xc4212122a0, 0x0, 0x0, 0x0)
        /home/arun/work/src/bitbucket.org/acklio/vdm/vendor/github.com/chifflier/nfqueue-go/nfqueue/nfqueue.go:165 +0x155

BUG: Raw Sockets And NFQUEUE in The Same Process Block Each Other

With lines commented ReadMsgIP works, uncommenting those lines make it block.

on.bash

#sudo iptables -t nat -D OUTPUT -p tcp -m tcp --dport 80 -j NFQUEUE --queue-num 13 -m owner ! --gid-owner proxyclient
sudo iptables -t nat -D OUTPUT -p tcp -m tcp --dport 80 -j REDIRECT
#sudo iptables -t nat -A OUTPUT -p tcp -m tcp --dport 80 -j NFQUEUE --queue-num 13 -m owner ! --gid-owner proxyclient
sudo iptables -t nat -A OUTPUT -p tcp -m tcp --dport 80 -j REDIRECT

test.go

package main

import (
  "github.com/chifflier/nfqueue-go/nfqueue"
  "syscall"
  "net"
  "fmt"
  "log"
  "math"
)

func handleQueue(payload *nfqueue.Payload) int {

  payload.SetVerdict(nfqueue.NF_ACCEPT)
  return nfqueue.NF_ACCEPT // Must return verdict

}

func createInputQueue() {

  q := new(nfqueue.Queue)

  q.SetCallback(handleQueue)

  q.Init()

  q.Unbind(syscall.AF_INET)
  q.Bind(syscall.AF_INET)

  q.CreateQueue(13)

  q.Loop()
  q.DestroyQueue()
  q.Close()

}

func main() {

  ipConn, err := net.ListenIP("ip:tcp", &net.IPAddr{IP: net.IPv4(127, 0, 0, 1)})
  if err != nil {
    fmt.Println("Try running under root rights.")
    log.Fatal(err)
  }
  log.Println("Listening!")

  maxIPPacketSize := math.MaxUint16
  fmt.Println("BEFORE LOOP")
  go func(){
    for {
      ipBuf := make([]byte, maxIPPacketSize)
      oob := make([]byte, maxIPPacketSize)
      fmt.Println("Blocking on read MSG")
      /*n*/_, _, _, _, err := ipConn.ReadMsgIP(ipBuf, oob)
      if err != nil {
        log.Println(err)
        continue
      }
      fmt.Println("UNBLOCKED")
      // packetData := ipBuf[:n]
    }
  }()

  createInputQueue()

}

off.bash

source <(head -2 on.bash)

start.bash

sudo groupadd proxyclient
sudo -g proxyclient ./test

Instructions

  1. go build test.go, start it with sudo ./start.bash
  2. ./on.bash
  3. Check that UNBLOCKED is printed to output while loading http://time.com
  4. ./off.bash
  5. Restart test.go
  6. ./on.bash
  7. See UNBLOCKED is never printed no matter if you load http://time.com or not
  8. ./off.bash

Why

Maybe because NF_ACCEPT verdict presumes all next rules in the chain are skipped?

unbuntu22.04 No package 'libnetfilter_queue' found

An error occurs when libnetfilter-queue-dev(1.0.5-2) is installed:
Package libnetfilter_queue was not found in the pkg-config search path.
Perhaps you should add the directory containing `libnetfilter_queue.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libnetfilter_queue' found
pkg-config: exit status 1

panic: runtime error: cgo argument has Go pointer to Go pointer

Hi,

Do you know why this line in (CreateQueue):

q.c_qh = C.nfq_create_queue(q.c_h,C.u_int16_t(queue_num),(*C.nfq_callback)(C.c_nfq_cb),unsafe.Pointer(q))

Is halting build with the error:

panic: runtime error: cgo argument has Go pointer to Go pointer

Thanks

what's nfqueue used for ?

I know nfqueue can modify packets queued by linux kernel , but I cannot find the production situation of such cases, could you please give me some introduction ?

Thanks

Add nfq_get_packet_hw please

I maked these...

// Returns the packet HW address
func (p *Payload) GetSrcHwAddr() []byte {
    hwInfo := C.nfq_get_packet_hw(p.nfad)
    addrl := int(C.ntohs(C.uint16_t(hwInfo.hw_addrlen)))
    res := make([]byte, addrl)
    for i := 0; i < addrl; i++  {
        res[i] = byte(hwInfo.hw_addr[i])
    }
    return res
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.