-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
188 lines (164 loc) · 4.89 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package main
import (
"bytes"
"encoding/base32"
"encoding/binary"
"errors"
"flag"
"fmt"
"golang.org/x/sys/unix"
"log"
"math/rand"
"net"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/cilium/ebpf/link"
"github.com/cilium/ebpf/perf"
"github.com/cilium/ebpf/rlimit"
)
// $BPF_CLANG and $BPF_CFLAGS are set by the Makefile.
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc $BPF_CLANG -cflags $BPF_CFLAGS bpf tracepoint.c -- -I./headers
const MaxPathnameLength = 128
type bpfEvent struct {
Pathname [MaxPathnameLength]uint8
}
// add custom data to token using the format specified at:
// https://docs.canarytokens.org/guide/dns-token.html#encoding-additional-information-in-your-token
// ```
// Base32 encode your data, and remove any padding '=' characters
// Insert periods (.) after every 63-bytes
// Append the magic string '.G'+<2-random-digits>+'.' (e.g. '.G12.' or '.G83.')
// ```
func hostnameWithPayload(hostname string, payload string, r *rand.Rand) string {
if len(payload) == 0 {
return hostname
}
data := []byte(payload)
dst := make([]byte, base32.StdEncoding.EncodedLen(len(data)))
base32.StdEncoding.Encode(dst, data)
trimmed := strings.TrimRight(string(dst), "=")
chunkSize := 63
var sb strings.Builder
for i, r := range []rune(trimmed) {
sb.WriteRune(r)
if i != 0 && i != 1 && (i+1)%chunkSize == 0 {
sb.WriteRune('.')
}
}
encodedPayloadWithSeparator := sb.String()
magicString := fmt.Sprintf(".G%d%d", r.Intn(10), r.Intn(10))
hostNameWithMagicString := strings.Join([]string{magicString, hostname}, ".")
maxHostnameLength := 253
maxPayloadSize := maxHostnameLength - len(hostNameWithMagicString)
if len(encodedPayloadWithSeparator) <= maxPayloadSize {
return encodedPayloadWithSeparator + hostNameWithMagicString
}
return encodedPayloadWithSeparator[0:maxPayloadSize] + hostNameWithMagicString
}
// send DNS requests
func consumer(canaryHostname string, link <-chan string, done chan<- bool) {
rs := rand.NewSource(time.Now().UnixNano())
r := rand.New(rs)
for pathname := range link {
log.Printf("triggering DNS token for: %s", pathname)
base := filepath.Base(pathname)
hostnameWithData := hostnameWithPayload(canaryHostname, base, r)
_, err := net.LookupIP(hostnameWithData)
if err != nil {
fmt.Fprintf(os.Stderr, "DNS request failed: %v\n", err)
}
}
done <- true
}
// read perf events
func producer(pathnames []string, rd *perf.Reader, link chan<- string) {
watchedPathnames := map[string]struct{}{}
for _, p := range pathnames {
watchedPathnames[p] = struct{}{}
}
var event bpfEvent
for {
record, err := rd.Read()
if err != nil {
if errors.Is(err, perf.ErrClosed) {
close(link)
return
}
log.Printf("reading from perf event reader: %s", err)
continue
}
if record.LostSamples != 0 {
log.Printf("perf event ring buffer full, dropped %d samples", record.LostSamples)
continue
}
if err := binary.Read(bytes.NewBuffer(record.RawSample), binary.LittleEndian, &event); err != nil {
log.Printf("parsing perf event: %s", err)
continue
}
pathname := unix.ByteSliceToString(event.Pathname[:])
_, ok := watchedPathnames[pathname]
if ok {
log.Printf("read perf event value: %s", pathname)
link <- pathname
}
}
close(link)
}
func main() {
// parse CLI flags
var canaryHostname string
flag.StringVar(&canaryHostname, "hostname", "", "DNS hostname to ping on events")
var pathNames string
flag.StringVar(&pathNames, "paths", "/usr/bin/id,/usr/bin/whoami,/usr/bin/hostname", "CSV; match `execve` syscalls with these pathnames as a first arg")
flag.Parse()
if len(canaryHostname) == 0 {
log.Fatalf("hostname not set but required")
}
splitPathNames := strings.Split(pathNames, ",")
for _, p := range splitPathNames {
if len(p) > MaxPathnameLength {
log.Fatalf("pathname too long: %s (%d chars)", p, len(p))
}
}
// setup interrupt channel
stopper := make(chan os.Signal, 1)
signal.Notify(stopper, os.Interrupt, syscall.SIGTERM)
// eBPF setup prelude
if err := rlimit.RemoveMemlock(); err != nil {
log.Fatal(err)
}
objs := bpfObjects{}
if err := loadBpfObjects(&objs, nil); err != nil {
log.Fatalf("loading objects: %s", err)
}
defer objs.Close()
tp, err := link.Tracepoint("syscalls", "sys_enter_execve", objs.BpfProg, nil)
if err != nil {
log.Fatalf("tracepoint uretprobe: %s", err)
}
defer tp.Close()
rd, err := perf.NewReader(objs.Events, os.Getpagesize())
if err != nil {
log.Fatalf("creating perf event reader: %s", err)
}
defer rd.Close()
// interrupt channel goroutine
go func() {
<-stopper
log.Println("Received signal, exiting program..")
if err := rd.Close(); err != nil {
log.Fatalf("closing perf event reader: %s", err)
}
}()
log.Printf("Listening for events..")
// setup producer-consumer pattern
link := make(chan string)
done := make(chan bool)
go producer(splitPathNames, rd, link)
go consumer(canaryHostname, link, done)
<-done
}