This repository has been archived by the owner on May 19, 2022. It is now read-only.
forked from carbonblack/cb-event-forwarder
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconfig.go
734 lines (641 loc) · 18.4 KB
/
config.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
package main
import (
"crypto/tls"
"crypto/x509"
"errors"
_ "expvar"
"fmt"
log "github.com/sirupsen/logrus"
"io/ioutil"
"strconv"
"strings"
"text/template"
"time"
"github.com/vaughan0/go-ini"
)
const (
FileOutputType = iota
S3OutputType
TCPOutputType
UDPOutputType
SyslogOutputType
HttpOutputType
SplunkOutputType
KafkaOutputType
)
const (
LEEFOutputFormat = iota
JSONOutputFormat
)
type Configuration struct {
ServerName string
AMQPHostname string
DebugFlag bool
DebugStore string
OutputType int
OutputFormat int
AMQPDisabled bool
AMQPUsername string
AMQPPassword string
AMQPPort int
AMQPTLSEnabled bool
AMQPTLSClientKey string
AMQPTLSClientCert string
AMQPTLSCACert string
AMQPQueueName string
AMQPAutoDeleteQueue bool
OutputParameters string
EventTypes []string
EventMap map[string]bool
HTTPServerPort int
CbServerURL string
UseRawSensorExchange bool
MonitoredLogs []string
// this is a hack for S3 specific configuration
S3ServerSideEncryption *string
S3CredentialProfileName *string
S3ACLPolicy *string
S3ObjectPrefix *string
S3StorageClass *string
S3VerboseKey bool
S3CompressData bool
// Syslog-specific configuration
TLSClientKey *string
TLSClientCert *string
TLSCACert *string
TLSVerify bool
TLSCName *string
TLS12Only bool
// HTTP-specific configuration
HttpAuthorizationToken *string
HttpPostTemplate *template.Template
HttpContentType *string
// configuration options common to bundled outputs (S3, HTTP)
UploadEmptyFiles bool
CommaSeparateEvents bool
BundleSendTimeout time.Duration
BundleSizeMax int64
// Compress data on S3 or file output types
FileHandlerCompressData bool
TLSConfig *tls.Config
// optional post processing of feed hits to retrieve titles
PerformFeedPostprocessing bool
CbAPIToken string
CbAPIVerifySSL bool
CbAPIProxyUrl string
// Kafka-specific configuration
KafkaBrokers *string
KafkaTopicSuffix *string
//Splunkd
SplunkToken *string
AuditLog bool
}
type ConfigurationError struct {
Errors []string
Empty bool
}
func (c *Configuration) AMQPURL() string {
if c.AMQPTLSEnabled == true {
return fmt.Sprintf("amqps://%s:%s@%s:%d", c.AMQPUsername, c.AMQPPassword, c.AMQPHostname, c.AMQPPort)
} else {
return fmt.Sprintf("amqp://%s:%s@%s:%d", c.AMQPUsername, c.AMQPPassword, c.AMQPHostname, c.AMQPPort)
}
}
func (e ConfigurationError) Error() string {
return fmt.Sprintf("Configuration errors:\n %s", strings.Join(e.Errors, "\n "))
}
func (e *ConfigurationError) addErrorString(err string) {
e.Empty = false
e.Errors = append(e.Errors, err)
}
func (e *ConfigurationError) addError(err error) {
e.Empty = false
e.Errors = append(e.Errors, err.Error())
}
func parseCbConf() (username, password string, err error) {
input, err := ini.LoadFile("/etc/cb/cb.conf")
if err != nil {
return username, password, err
}
username, _ = input.Get("", "RabbitMQUser")
password, _ = input.Get("", "RabbitMQPassword")
if len(username) == 0 || len(password) == 0 {
return username, password, errors.New("Could not get RabbitMQ credentials from /etc/cb/cb.conf")
}
return
}
func (c *Configuration) parseEventTypes(input ini.File) {
eventTypes := [...]struct {
configKey string
eventList []string
}{
{"events_watchlist", []string{
"watchlist.#",
}},
{"events_feed", []string{
"feed.#",
}},
{"events_alert", []string{
"alert.#",
}},
{"events_raw_sensor", []string{
"ingress.event.process",
"ingress.event.procstart",
"ingress.event.netconn",
"ingress.event.procend",
"ingress.event.childproc",
"ingress.event.moduleload",
"ingress.event.module",
"ingress.event.filemod",
"ingress.event.regmod",
"ingress.event.tamper",
"ingress.event.crossprocopen",
"ingress.event.remotethread",
"ingress.event.processblock",
"ingress.event.emetmitigation",
}},
{"events_binary_observed", []string{
"binaryinfo.#",
}},
{"events_binary_upload", []string{
"binarystore.#",
}},
{"events_storage_partition", []string{
"events.partition.#",
}},
}
for _, eventType := range eventTypes {
val, ok := input.Get("bridge", eventType.configKey)
if ok {
val = strings.ToLower(val)
if val == "all" {
for _, routingKey := range eventType.eventList {
c.EventTypes = append(c.EventTypes, routingKey)
}
} else if val == "0" {
// nothing
} else {
for _, routingKey := range strings.Split(val, ",") {
c.EventTypes = append(c.EventTypes, routingKey)
}
}
}
}
c.EventMap = make(map[string]bool)
log.Info("Raw Event Filtering Configuration:")
for _, eventName := range c.EventTypes {
c.EventMap[eventName] = true
if strings.HasPrefix(eventName, "ingress.event.") {
log.Infof("%s: %t", eventName, c.EventMap[eventName])
}
}
}
func (c *Configuration) parseMonitoredLogs(input ini.File) {
val, ok := input.Get("bridge", "monitored_logs")
if ok {
for _, monitored_log := range strings.Split(val, ",") {
c.MonitoredLogs = append(c.MonitoredLogs, monitored_log)
}
}
}
func ParseConfig(fn string) (Configuration, error) {
config := Configuration{}
errs := ConfigurationError{Empty: true}
input, err := ini.LoadFile(fn)
if err != nil {
return config, err
}
// defaults
config.DebugFlag = false
config.OutputFormat = JSONOutputFormat
config.OutputType = FileOutputType
config.AMQPDisabled = false
config.AMQPHostname = "localhost"
config.AMQPUsername = "cb"
config.HTTPServerPort = 33706
config.AMQPPort = 5004
config.DebugStore = "/tmp"
config.S3ACLPolicy = nil
config.S3ServerSideEncryption = nil
config.S3CredentialProfileName = nil
config.S3StorageClass = nil
config.AMQPAutoDeleteQueue = true
// required values
val, ok := input.Get("bridge", "server_name")
if !ok {
config.ServerName = "CB"
} else {
config.ServerName = val
}
val, ok = input.Get("bridge", "debug")
if ok {
if val == "1" {
config.DebugFlag = true
log.SetLevel(log.DebugLevel)
customFormatter := new(log.TextFormatter)
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
log.SetFormatter(customFormatter)
customFormatter.FullTimestamp = true
log.Debug("Debugging output is set to True")
}
}
debugStore, ok := input.Get("bridge", "debug_store")
if ok {
config.DebugStore = debugStore
} else {
config.DebugStore = "/var/log/cb/integrations/cb-event-forwarder"
}
log.Debugf("Debug Store is %s", config.DebugStore)
val, ok = input.Get("bridge", "http_server_port")
if ok {
port, err := strconv.Atoi(val)
if err == nil {
config.HTTPServerPort = port
}
}
val, ok = input.Get("bridge", "rabbit_mq_disabled")
if ok {
b, err := strconv.ParseBool(val)
if err == nil {
config.AMQPDisabled = b
}
}
if !config.AMQPDisabled {
val, ok = input.Get("bridge", "rabbit_mq_username")
if ok {
config.AMQPUsername = val
}
val, ok = input.Get("bridge", "rabbit_mq_password")
if !ok {
errs.addErrorString("Missing required rabbit_mq_password section")
} else {
config.AMQPPassword = val
}
val, ok = input.Get("bridge", "rabbit_mq_port")
if ok {
port, err := strconv.Atoi(val)
if err == nil {
config.AMQPPort = port
}
}
val, ok = input.Get("bridge", "rabbit_mq_auto_delete_queue")
if ok {
b, err := strconv.ParseBool(val)
if err == nil {
config.AMQPAutoDeleteQueue = b
}
}
if len(config.AMQPUsername) == 0 || len(config.AMQPPassword) == 0 {
config.AMQPUsername, config.AMQPPassword, err = parseCbConf()
if err != nil {
errs.addError(err)
}
}
val, ok = input.Get("bridge", "rabbit_mq_use_tls")
if ok {
b, err := strconv.ParseBool(val)
if err == nil {
config.AMQPTLSEnabled = b
}
}
rabbitKeyFilename, ok := input.Get("bridge", "rabbit_mq_key")
if ok {
config.AMQPTLSClientKey = rabbitKeyFilename
}
rabbitCertFilename, ok := input.Get("bridge", "rabbit_mq_cert")
if ok {
config.AMQPTLSClientCert = rabbitCertFilename
}
rabbitCaCertFilename, ok := input.Get("bridge", "rabbit_mq_ca_cert")
if ok {
config.AMQPTLSCACert = rabbitCaCertFilename
}
rabbitQueueName, ok := input.Get("bridge", "rabbit_mq_queue_name")
if ok {
config.AMQPQueueName = rabbitQueueName
}
val, ok = input.Get("bridge", "cb_server_hostname")
if ok {
config.AMQPHostname = val
}
}
val, ok = input.Get("bridge", "cb_server_url")
if ok {
if !strings.HasSuffix(val, "/") {
val = val + "/"
}
config.CbServerURL = val
}
val, ok = input.Get("bridge", "output_format")
if ok {
val = strings.TrimSpace(val)
val = strings.ToLower(val)
if val == "leef" {
config.OutputFormat = LEEFOutputFormat
}
}
config.FileHandlerCompressData = false
val, ok = input.Get("bridge", "compress_data")
if ok {
b, err := strconv.ParseBool(val)
if err == nil {
config.FileHandlerCompressData = b
}
}
config.AuditLog = false
val, ok = input.Get("bridge", "audit_log")
if ok {
b, err := strconv.ParseBool(val)
if err == nil {
config.AuditLog = b
}
}
outType, ok := input.Get("bridge", "output_type")
var parameterKey string
if ok {
outType = strings.TrimSpace(outType)
outType = strings.ToLower(outType)
switch outType {
case "file":
parameterKey = "outfile"
config.OutputType = FileOutputType
case "tcp":
parameterKey = "tcpout"
config.OutputType = TCPOutputType
case "udp":
parameterKey = "udpout"
config.OutputType = UDPOutputType
case "s3":
parameterKey = "s3out"
config.OutputType = S3OutputType
profileName, ok := input.Get("s3", "credential_profile")
if ok {
config.S3CredentialProfileName = &profileName
}
aclPolicy, ok := input.Get("s3", "acl_policy")
if ok {
config.S3ACLPolicy = &aclPolicy
}
storageClass, ok := input.Get("s3", "storage_class")
if ok {
config.S3StorageClass = &storageClass
log.Println("Set storage class: ", storageClass)
} else {
log.Println("Unable to set storage class: ", storageClass)
}
sseType, ok := input.Get("s3", "server_side_encryption")
if ok {
config.S3ServerSideEncryption = &sseType
}
objectPrefix, ok := input.Get("s3", "object_prefix")
if ok {
config.S3ObjectPrefix = &objectPrefix
}
val, ok = input.Get("s3", "verbose_key")
if ok {
b, err := strconv.ParseBool(val)
if err == nil {
config.S3VerboseKey = b
}
}
val, ok = input.Get("s3", "compress_data")
if ok {
b, err := strconv.ParseBool(val)
if err == nil {
config.S3CompressData = b
}
} else {
config.S3CompressData = true
}
case "http":
parameterKey = "httpout"
config.OutputType = HttpOutputType
token, ok := input.Get("http", "authorization_token")
if ok {
config.HttpAuthorizationToken = &token
}
postTemplate, ok := input.Get("http", "http_post_template")
config.HttpPostTemplate = template.New("http_post_output")
if ok {
config.HttpPostTemplate = template.Must(config.HttpPostTemplate.Parse(postTemplate))
} else {
if config.OutputFormat == JSONOutputFormat {
config.HttpPostTemplate = template.Must(config.HttpPostTemplate.Parse(
`{"filename": "{{.FileName}}", "service": "carbonblack", "alerts":[{{range .Events}}{{.EventText}}{{end}}]}`))
} else {
config.HttpPostTemplate = template.Must(config.HttpPostTemplate.Parse(`{{range .Events}}{{.EventText}}{{end}}`))
}
}
contentType, ok := input.Get("http", "content_type")
if ok {
config.HttpContentType = &contentType
} else {
jsonString := "application/json"
config.HttpContentType = &jsonString
}
case "syslog":
parameterKey = "syslogout"
config.OutputType = SyslogOutputType
case "kafka":
config.OutputType = KafkaOutputType
kafkaBrokers, ok := input.Get("kafka", "brokers")
if ok {
config.KafkaBrokers = &kafkaBrokers
}
kafkaTopicSuffix, ok := input.Get("kafka", "topic_suffix")
if ok {
config.KafkaTopicSuffix = &kafkaTopicSuffix
}
case "splunk":
parameterKey = "splunkout"
config.OutputType = SplunkOutputType
token, ok := input.Get("splunk", "hec_token")
if ok {
config.SplunkToken = &token
}
postTemplate, ok := input.Get("splunk", "http_post_template")
config.HttpPostTemplate = template.New("http_post_output")
if ok {
config.HttpPostTemplate = template.Must(config.HttpPostTemplate.Parse(postTemplate))
} else {
if config.OutputFormat == JSONOutputFormat {
config.HttpPostTemplate = template.Must(config.HttpPostTemplate.Parse(
`{{range .Events}}{"sourcetype":"bit9:carbonblack:json","event":{{.EventText}}}{{end}}`))
} else {
config.HttpPostTemplate = template.Must(config.HttpPostTemplate.Parse(`{{range .Events}}{{.EventText}}{{end}}`))
}
}
contentType, ok := input.Get("http", "content_type")
if ok {
config.HttpContentType = &contentType
} else {
jsonString := "application/json"
config.HttpContentType = &jsonString
}
default:
errs.addErrorString(fmt.Sprintf("Unknown output type: %s", outType))
}
} else {
errs.addErrorString("No output type specified")
return config, errs
}
if len(parameterKey) > 0 {
val, ok = input.Get("bridge", parameterKey)
if !ok {
errs.addErrorString(fmt.Sprintf("Missing value for key %s, required by output type %s",
parameterKey, outType))
} else {
config.OutputParameters = val
}
}
val, ok = input.Get("bridge", "use_raw_sensor_exchange")
if ok {
boolval, err := strconv.ParseBool(val)
if err == nil {
config.UseRawSensorExchange = boolval
if boolval {
log.Warn("Configured to listen on the Carbon Black Enterprise Response raw sensor event feed.")
log.Warn("- This will result in a *large* number of messages output via the event forwarder!")
log.Warn("- Ensure that raw sensor events are enabled in your Cb server (master & minion) via")
log.Warn(" the 'EnableRawSensorDataBroadcast' variable in /etc/cb/cb.conf")
}
} else {
errs.addErrorString("Unknown value for 'use_raw_sensor_exchange': valid values are true, false, 1, 0")
}
}
// TLS configuration
config.TLSVerify = true
tlsVerify, ok := input.Get(outType, "tls_verify")
if ok {
boolval, err := strconv.ParseBool(tlsVerify)
if err == nil {
if boolval == false {
config.TLSVerify = false
}
} else {
errs.addErrorString("Unknown value for 'tls_verify': valid values are true, false, 1, 0. Default is 'true'")
}
}
config.TLS12Only = true
tlsInsecure, ok := input.Get(outType, "insecure_tls")
if ok {
boolval, err := strconv.ParseBool(tlsInsecure)
if err == nil {
if boolval == true {
config.TLS12Only = false
}
} else {
errs.addErrorString("Unknown value for 'insecure_tls': ")
}
}
serverCName, ok := input.Get(outType, "server_cname")
if ok {
config.TLSCName = &serverCName
}
config.TLSConfig = configureTLS(config)
// Bundle configuration
// default to sending empty files to S3/HTTP POST endpoint
if outType == "splunk" {
config.UploadEmptyFiles = false
log.Info("Splunk HEC does not accept empty files as input, ignoring upload_empty_files=true for 'splunkout'")
} else {
config.UploadEmptyFiles = true
}
sendEmptyFiles, ok := input.Get(outType, "upload_empty_files")
if ok {
boolval, err := strconv.ParseBool(sendEmptyFiles)
if err == nil {
if boolval == false {
config.UploadEmptyFiles = false
}
} else {
errs.addErrorString("Unknown value for 'upload_empty_files': valid values are true, false, 1, 0. Default is 'true'")
}
}
if config.OutputFormat == JSONOutputFormat {
config.CommaSeparateEvents = true
} else {
config.CommaSeparateEvents = false
}
// default 10MB bundle size max before forcing a send
config.BundleSizeMax = 10 * 1024 * 1024
bundleSizeMax, ok := input.Get(outType, "bundle_size_max")
if ok {
bundleSizeMax, err := strconv.ParseInt(bundleSizeMax, 10, 64)
if err == nil {
config.BundleSizeMax = bundleSizeMax
}
}
// default 5 minute send interval
config.BundleSendTimeout = 5 * time.Minute
bundleSendTimeout, ok := input.Get(outType, "bundle_send_timeout")
if ok {
bundleSendTimeout, err := strconv.ParseInt(bundleSendTimeout, 10, 64)
if err == nil {
config.BundleSendTimeout = time.Duration(bundleSendTimeout) * time.Second
}
}
val, ok = input.Get("bridge", "api_verify_ssl")
if ok {
config.CbAPIVerifySSL, err = strconv.ParseBool(val)
if err != nil {
errs.addErrorString("Unknown value for 'api_verify_ssl': valid values are true, false, 1, 0. Default is 'false'")
}
}
val, ok = input.Get("bridge", "api_token")
if ok {
config.CbAPIToken = val
config.PerformFeedPostprocessing = true
}
config.CbAPIProxyUrl = ""
val, ok = input.Get("bridge", "api_proxy_url")
if ok {
config.CbAPIProxyUrl = val
}
config.parseEventTypes(input)
config.parseMonitoredLogs(input)
if !errs.Empty {
return config, errs
} else {
return config, nil
}
}
func configureTLS(config Configuration) *tls.Config {
tlsConfig := &tls.Config{}
if config.TLSVerify == false {
log.Info("Disabling TLS verification for remote output")
tlsConfig.InsecureSkipVerify = true
}
if config.TLSClientCert != nil && config.TLSClientKey != nil && len(*config.TLSClientCert) > 0 &&
len(*config.TLSClientKey) > 0 {
log.Infof("Loading client cert/key from %s & %s", *config.TLSClientCert, *config.TLSClientKey)
cert, err := tls.LoadX509KeyPair(*config.TLSClientCert, *config.TLSClientKey)
if err != nil {
log.Fatal(err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
if config.TLSCACert != nil && len(*config.TLSCACert) > 0 {
// Load CA cert
log.Infof("Loading valid CAs from file %s", *config.TLSCACert)
caCert, err := ioutil.ReadFile(*config.TLSCACert)
if err != nil {
log.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = caCertPool
}
if config.TLSCName != nil && len(*config.TLSCName) > 0 {
log.Infof("Forcing TLS Common Name check to use '%s' as the hostname", *config.TLSCName)
tlsConfig.ServerName = *config.TLSCName
}
if config.TLS12Only == true {
log.Info("Enforcing minimum TLS version 1.2")
tlsConfig.MinVersion = tls.VersionTLS12
} else {
log.Info("Relaxing minimum TLS version to 1.0")
tlsConfig.MinVersion = tls.VersionTLS10
}
return tlsConfig
}