-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
287 lines (240 loc) · 7.3 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/hashicorp/go-retryablehttp"
"github.com/jpillora/backoff"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
// Use the eu-west-1 region as default
awsDefaultRegion = "eu-west-1"
// Firehose will create objects with a year/month/day/hour structure.
// Prefix indicates that we are only interested in the events from
// firehose and not anything else in the bucket.
firehosePrefix = "20"
// dataEventMessageType is the Firehose message type for data
dataEventMessageType = "DATA_MESSAGE"
// checkInterval is the delay in minutes to check for new Firehose events
checkInterval = 2 * time.Minute
// magicNumberMessageLength is the minimum length of the event. Sometimes event like "54" is recongnized as valid json
magicNumberMessageLength = 10
)
var (
auditEvents = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "feab_audit_event_total",
Help: "How many audit logs have been processed.",
},
)
errorEvents = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "feab_errors_total",
Help: "How many errors encountered.",
},
[]string{"type"},
)
)
// Log is a CloudWatch K8s audit log line
type Log struct {
Message string `json:"message"`
}
// Event is a firehose event
type Event struct {
MessageType string `json:"messageType"`
LogEvents []Log `json:"logEvents"`
}
func init() {
// Track the amount of K8s audit logs processed and errors encountered
prometheus.MustRegister(auditEvents)
prometheus.MustRegister(errorEvents)
// Register the HTTP handlers
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/health", func(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(http.StatusOK)
})
// Start the monitoring service
go http.ListenAndServe(":8080", nil)
fmt.Printf("Started monitoring services\n")
}
// validJSON parses the JSON while discarding the contents.
// It returns true for valid JSON, false otherwise.
func validJSON(data string) bool {
if len(data) < magicNumberMessageLength {
return false
}
dec := json.NewDecoder(bytes.NewReader([]byte(data)))
for {
_, err := dec.Token()
if err == io.EOF {
return true
}
if err != nil {
return false
}
}
}
func main() {
bucket, ok := os.LookupEnv("BUCKET")
if !ok {
fmt.Println("Environment variable 'BUCKET' not set, exiting.")
os.Exit(1)
}
falcoEndpoint, ok := os.LookupEnv("FALCO_ENDPOINT")
if !ok {
fmt.Println("Environment variable 'FALCO_ENDPOINT' not set, exiting.")
os.Exit(1)
}
region, ok := os.LookupEnv("AWS_DEFAULT_REGION")
if !ok {
region = awsDefaultRegion
}
prefix, ok := os.LookupEnv("FIREHOSE_PREFIX")
if !ok {
prefix = firehosePrefix
}
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String(region),
}))
s3client := s3.New(sess)
b := &backoff.Backoff{
Jitter: true,
}
httpClient := retryablehttp.NewClient()
// Disable the verbose debug logging for now
httpClient.Logger = nil
for {
res, err := s3client.ListObjects(&s3.ListObjectsInput{
Bucket: aws.String(bucket),
Prefix: aws.String(prefix),
})
if err != nil {
d := b.Duration()
fmt.Printf("Error listing bucket:\n%v\nRetrying in %s", err, d)
errorEvents.With(prometheus.Labels{"type": "s3-list"}).Inc()
time.Sleep(d)
continue
}
b.Reset()
objects := res.Contents
// Sort the objects according to LastModified date
sort.Slice(objects, func(i, j int) bool {
return objects[i].LastModified.Before(*objects[j].LastModified)
})
for _, object := range objects {
// Check if the object was already processed but somehow not deleted
_, err := s3client.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(fmt.Sprintf("processed/%s", *object.Key)),
})
if err != nil {
// Apparently the object doesn't exist in the processed folder, so start processing it
fmt.Printf("Processing: %s\n", *object.Key)
} else {
// The object already exists in the processed folder, so delete and ignore it
_, err = s3client.DeleteObject(&s3.DeleteObjectInput{
Bucket: aws.String(bucket),
Key: object.Key,
})
if err != nil {
fmt.Printf("Could not delete file from the Firehose folder:\n%v\n", err)
errorEvents.With(prometheus.Labels{"type": "s3-delete"}).Inc()
continue
}
}
// Download the file from S3
file, err := s3client.GetObject(
&s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: object.Key,
})
if err != nil {
fmt.Printf("Could not download the Firehose events file:\n%v\n", err)
errorEvents.With(prometheus.Labels{"type": "s3-get"}).Inc()
continue
}
// Uncompress the file
contents, err := gzip.NewReader(file.Body)
if err != nil {
fmt.Printf("Could not decompress the Firehose events:\n%v\n", err)
errorEvents.With(prometheus.Labels{"type": "gzip"}).Inc()
continue
}
// Parse the JSON file contents
decoder := json.NewDecoder(contents)
event := Event{}
var processed bool
DECODER:
for {
if err := decoder.Decode(&event); err == io.EOF {
processed = true
break
} else if err != nil {
fmt.Printf("Unable to (fully) parse Firehose event:\n%v\n", err)
errorEvents.With(prometheus.Labels{"type": "parsing"}).Inc()
break
}
if event.MessageType == dataEventMessageType {
for _, log := range event.LogEvents {
if validJSON(log.Message) {
// Post the audit log to Falco for compliance checking
res, err := httpClient.Post(falcoEndpoint, "application/json", strings.NewReader(log.Message))
if err != nil {
fmt.Printf("Unable to send the audit log to Falco.\nError: %v\n", err)
errorEvents.With(prometheus.Labels{"type": "falco"}).Inc()
break DECODER
}
if res.StatusCode != 200 {
fmt.Printf("Falco did not accept the audit log\nLog: %s, Code: %d\n", log.Message, res.StatusCode)
errorEvents.With(prometheus.Labels{"type": "falco"}).Inc()
break DECODER
}
res.Body.Close()
}
}
}
}
if processed {
// Track successfull processing
auditEvents.Inc()
_, err = s3client.CopyObject(&s3.CopyObjectInput{
Bucket: aws.String(bucket),
CopySource: aws.String(fmt.Sprintf("/%s/%s", bucket, *object.Key)),
Key: aws.String(fmt.Sprintf("processed/%s", *object.Key)),
})
if err != nil {
fmt.Printf("Could not copy file to processed folder:\n%v\n", err)
errorEvents.With(prometheus.Labels{"type": "s3-copy"}).Inc()
continue
}
_, err = s3client.DeleteObject(&s3.DeleteObjectInput{
Bucket: aws.String(bucket),
Key: object.Key,
})
if err != nil {
fmt.Printf("Could not delete file from the Firehose folder:\n%v\n", err)
errorEvents.With(prometheus.Labels{"type": "s3-delete"}).Inc()
continue
}
} else {
fmt.Printf("Object '%s' was not (fully) processed, not moving it to the processed folder.\n", *object.Key)
}
}
if len(objects) == 0 {
fmt.Println("No new Firehose events found, waiting for next check interval.")
time.Sleep(checkInterval)
}
}
}