Adam Bronte

Adam Bronte

Thoughts, stories, and data.

31 Jul 2022

Creating a simple honeypot in Go

Lately, I have had an idea to play around with creating my own honeypot. Something super simple such as a program that just listens on a ton of TCP ports and see what connects.

I chose Go to try this because I’m familiar with it and it should be pretty memory efficient. The plan is to run this on a tiny virtual machine.

To accomplish this in Go, we use net.Listen to listen on a specified port and accept and read the first 1024 bytes of a new connection then close it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
func listener(port string) {
    l, err := net.Listen("tcp", "0.0.0.0:"+port)
    if err != nil {
        fmt.Println("Error listening:", err.Error())
        os.Exit(1)
    }
	 
    // Close the listener when the application closes.
    defer l.Close()
    fmt.Println("Listening on " + port)
    
    for {
        // Listen for an incoming connection.
        conn, err := l.Accept()
        if err != nil {
            fmt.Println("Error accepting: ", err.Error())
            os.Exit(1)
        }
        // Handle connections in a new goroutine.
        go handleRequest(conn, port)
    }
}

To keep things non-blocking, we handle reading the socket in a go-routine calling the handleRequest function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
func handleRequest(conn net.Conn, port string) {
    // Make a buffer to hold incoming data.
    buf := make([]byte, 1024)
    
    // Read the incoming connection into the buffer.
    _, err := conn.Read(buf)
    if err != nil {
        fmt.Println("Error reading:", err.Error())
    }
    
    fmt.Println("connnection on ", port, " from ", conn.RemoteAddr())
    fmt.Println(conn.LocalAddr())
    fmt.Println(string(buf))
    
    conn.Close()
}

Now iterate over all the ports you want to listen on, and voila, your own honeypot. I ended up running this in a docker container using host networking listening on ports 2 through 20000. All in all, it uses about ~300mb of memory and 1% cpu.