Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example DNS parser #163

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ run: build

docker:
docker build -t glutton .
docker run --cap-add=NET_ADMIN -it glutton
docker run --cap-add=NET_ADMIN -it --name glutton glutton

test:
go test -v ./...
3 changes: 3 additions & 0 deletions config/rules.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ rules:
- match: tcp dst port 11211
type: conn_handler
target: memcache
- match: udp dst port 53
type: conn_handler
target: dns
Comment on lines +32 to +34
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rule to handle all UDP traffic on port 53 with the new DNS handler

- match: tcp
type: conn_handler
target: tcp
Expand Down
16 changes: 15 additions & 1 deletion glutton.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,22 @@ func (g *Glutton) udpListen() {
if hfunc, ok := g.udpProtocolHandlers[rule.Target]; ok {
data := buffer[:n]
go func() {
if err := hfunc(g.ctx, srcAddr, dstAddr, data, md); err != nil {
response, err := hfunc(g.ctx, srcAddr, dstAddr, data, md)
if err != nil {
g.Logger.Error("failed to handle UDP payload", producer.ErrAttr(err))
return
}
if response != nil {
con, err := net.DialUDP("udp", dstAddr, srcAddr)
if err != nil {
g.Logger.Error("failed to dial UDP connection", producer.ErrAttr(err))
return
}
defer con.Close()
_, err = con.Write(response)
if err != nil {
g.Logger.Error("failed to send UDP response", producer.ErrAttr(err))
Comment on lines +180 to +188
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have to create a new outgoing connection. If we send through the UDP listener, we will have the wrong source port.

}
}
}()
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ require (
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.18.2
github.com/stretchr/testify v1.9.0
golang.org/x/net v0.25.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
gopkg.in/yaml.v2 v2.4.0
)
Expand Down Expand Up @@ -44,7 +45,6 @@ require (
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/term v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
Expand Down
9 changes: 6 additions & 3 deletions protocols/protocols.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,16 @@ import (

type TCPHandlerFunc func(ctx context.Context, conn net.Conn, md connection.Metadata) error

type UDPHandlerFunc func(ctx context.Context, srcAddr, dstAddr *net.UDPAddr, data []byte, md connection.Metadata) error
type UDPHandlerFunc func(ctx context.Context, srcAddr, dstAddr *net.UDPAddr, data []byte, md connection.Metadata) ([]byte, error)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UDP handlers now return a byte slice as response to the client.


// MapUDPProtocolHandlers map protocol handlers to corresponding protocol
func MapUDPProtocolHandlers(log interfaces.Logger, h interfaces.Honeypot) map[string]UDPHandlerFunc {
protocolHandlers := map[string]UDPHandlerFunc{}
protocolHandlers["udp"] = func(ctx context.Context, srcAddr, dstAddr *net.UDPAddr, data []byte, md connection.Metadata) error {
return udp.HandleUDP(ctx, srcAddr, dstAddr, data, md, log, h)
protocolHandlers["udp"] = func(ctx context.Context, srcAddr, dstAddr *net.UDPAddr, data []byte, md connection.Metadata) ([]byte, error) {
return nil, udp.HandleUDP(ctx, srcAddr, dstAddr, data, md, log, h)
}
protocolHandlers["dns"] = func(ctx context.Context, srcAddr, dstAddr *net.UDPAddr, data []byte, md connection.Metadata) ([]byte, error) {
return udp.HandleDNS(ctx, srcAddr, dstAddr, data, md, log, h)
}
return protocolHandlers
}
Expand Down
115 changes: 115 additions & 0 deletions protocols/udp/dns.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package udp

import (
"context"
"fmt"
"net"
"time"

"github.com/mushorg/glutton/connection"
"github.com/mushorg/glutton/producer"
"github.com/mushorg/glutton/protocols/interfaces"

"golang.org/x/net/dns/dnsmessage"
)

var (
maxRequestCount = 3
throttleSeconds = int64(60)
)

type throttleState struct {
count int
last int64
}

var throttle = map[string]throttleState{}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't want to become a UDP amplification service.


func cleanupThrottle() {
for ip, state := range throttle {
if state.last+throttleSeconds < time.Now().Unix() {
delete(throttle, ip)
}
}
}

func shouldThrottle(ip string) bool {
defer func() { go cleanupThrottle() }()
if _, ok := throttle[ip]; ok {
if throttle[ip].count > maxRequestCount {
if throttle[ip].last+throttleSeconds > time.Now().Unix() {
return true
}
throttle[ip] = throttleState{count: 1, last: time.Now().Unix()}
return false
}
throttle[ip] = throttleState{count: throttle[ip].count + 1, last: time.Now().Unix()}
return false
}
throttle[ip] = throttleState{count: 1, last: time.Now().Unix()}
return false
}

// HandleDNS handles DNS packets
func HandleDNS(ctx context.Context, srcAddr, dstAddr *net.UDPAddr, data []byte, md connection.Metadata, log interfaces.Logger, h interfaces.Honeypot) ([]byte, error) {
if shouldThrottle(srcAddr.IP.String()) {
return nil, fmt.Errorf("throttling DNS requests")
}
var p dnsmessage.Parser
if _, err := p.Start(data); err != nil {
return nil, fmt.Errorf("failed to parse DNS query: %w", err)
}

questions, err := p.AllQuestions()
if err != nil {
return nil, fmt.Errorf("failed to parse DNS questions: %w", err)
}

msg := dnsmessage.Message{
Header: dnsmessage.Header{Response: true, Authoritative: true},
}

for _, q := range questions {
msg.Questions = append(msg.Questions, q)
name, err := dnsmessage.NewName(q.Name.String())
if err != nil {
return nil, err
}

answer := dnsmessage.Resource{
Header: dnsmessage.ResourceHeader{
Name: name,
Type: q.Type,
Class: q.Class,
TTL: 453,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to make this not fingerprintable

},
}

switch q.Type {
case dnsmessage.TypeA:
answer.Body = &dnsmessage.AResource{A: [4]byte{127, 0, 0, 1}}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we actually do a DNS lookup instead of localhost? If we resolve anything, it's a dead giveaway.

case dnsmessage.TypeAAAA:
answer.Body = &dnsmessage.AAAAResource{AAAA: [16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1}}
case dnsmessage.TypeCNAME:
answer.Body = &dnsmessage.CNAMEResource{CNAME: dnsmessage.MustNewName("localhost")}
case dnsmessage.TypeNS:
answer.Body = &dnsmessage.NSResource{NS: dnsmessage.MustNewName("localhost")}
case dnsmessage.TypePTR:
answer.Body = &dnsmessage.PTRResource{PTR: dnsmessage.MustNewName("localhost")}
case dnsmessage.TypeTXT:
answer.Body = &dnsmessage.TXTResource{TXT: []string{"localhost"}}
}
msg.Answers = append(msg.Answers, answer)
}

buf, err := msg.Pack()
if err != nil {
return nil, fmt.Errorf("failed to pack DNS response: %w", err)
}

if err := h.ProduceUDP("dns", srcAddr, dstAddr, md, data[:len(data)%1024], nil); err != nil {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We probably want to also report the structured message instead of just the raw payload.

log.Error("failed to produce DNS payload", producer.ErrAttr(err))
return nil, err
}
return buf, nil
}
37 changes: 37 additions & 0 deletions protocols/udp/dns_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package udp

import (
"net"
"testing"
"time"

"github.com/stretchr/testify/require"
)

func TestThrottling(t *testing.T) {
testIP := net.IPv4(192, 168, 1, 1).String()
throttle[testIP] = throttleState{count: maxRequestCount + 1, last: time.Now().Unix()}
tests := []struct {
name string
ip string
expected bool
}{
{
name: "throttle",
ip: testIP,
expected: true,
},
{
name: "no throttle",
ip: net.IPv4(192, 168, 1, 2).String(),
expected: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ok := shouldThrottle(tt.ip)
require.Equal(t, tt.expected, ok)
})
}
}
Loading