/
live_bouncer.go
96 lines (76 loc) · 2.3 KB
/
live_bouncer.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
package csbouncer
import (
"context"
"fmt"
"io"
"os"
"strings"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
type LiveBouncer struct {
APIKey string `yaml:"api_key"`
APIUrl string `yaml:"api_url"`
InsecureSkipVerify *bool `yaml:"insecure_skip_verify"`
CertPath string `yaml:"cert_path"`
KeyPath string `yaml:"key_path"`
CAPath string `yaml:"ca_cert_path"`
APIClient *apiclient.ApiClient
UserAgent string
}
// Config() fills the struct with configuration values from a file. It is not
// aware of .yaml.local files so it is recommended to use ConfigReader() instead.
func (b *LiveBouncer) Config(configPath string) error {
reader, err := os.Open(configPath)
if err != nil {
return fmt.Errorf("unable to read config file '%s': %w", configPath, err)
}
return b.ConfigReader(reader)
}
func (b *LiveBouncer) ConfigReader(configReader io.Reader) error {
content, err := io.ReadAll(configReader)
if err != nil {
return fmt.Errorf("unable to read configuration: %w", err)
}
err = yaml.Unmarshal(content, b)
if err != nil {
return fmt.Errorf("unable to unmarshal config file: %w", err)
}
return nil
}
func (b *LiveBouncer) Init() error {
var err error
// validate the configuration
if b.APIUrl == "" {
return fmt.Errorf("config does not contain LAPI url")
}
if !strings.HasSuffix(b.APIUrl, "/") {
b.APIUrl += "/"
}
if b.APIKey == "" && b.CertPath == "" && b.KeyPath == "" {
return fmt.Errorf("config does not contain LAPI key or certificate")
}
b.APIClient, err = getAPIClient(b.APIUrl, b.UserAgent, b.APIKey, b.CAPath, b.CertPath, b.KeyPath, b.InsecureSkipVerify, log.StandardLogger())
if err != nil {
return fmt.Errorf("api client init: %w", err)
}
return nil
}
func (b *LiveBouncer) Get(value string) (*models.GetDecisionsResponse, error) {
filter := apiclient.DecisionsListOpts{
IPEquals: &value,
}
decision, resp, err := b.APIClient.Decisions.List(context.Background(), filter)
if err != nil {
if resp != nil && resp.Response != nil {
resp.Response.Body.Close()
}
return &models.GetDecisionsResponse{}, err
}
if resp != nil && resp.Response != nil {
resp.Response.Body.Close()
}
return decision, nil
}