forked from mrtc0/wazuh
/
wazuh.go
108 lines (86 loc) · 2.06 KB
/
wazuh.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
package wazuh
import (
"crypto/tls"
"net/http"
"net/url"
)
type httpClient interface {
Do(*http.Request) (*http.Response, error)
}
type Client struct {
httpclient httpClient
Options ClientOptions
}
type ClientOption func(*ClientOptions)
type ClientOptions struct {
Endpoint url.URL
certificatePath string
keyPath string
certPem []byte
keyPem []byte
BasicUser string
BasicPass string
Raw string
}
func New(endpoint string, options ...ClientOption) (*Client, error) {
var client *Client
u, err := url.Parse(endpoint)
if err != nil {
return client, err
}
opt := ClientOptions{}
for _, o := range options {
o(&opt)
}
opt.Endpoint = *u
tr, err := setCertficate(opt)
if err != nil {
return client, err
}
client = &Client{
httpclient: &http.Client{Transport: tr},
Options: opt,
}
return client, nil
}
func WithBasicAuth(username, password string) ClientOption {
return func(options *ClientOptions) {
options.BasicUser = username
options.BasicPass = password
options.Raw = "true"
}
}
// If you are doing client certificate authentication, use it
func WithClientCertificateFromFile(cert string, key string) ClientOption {
return func(options *ClientOptions) {
options.certificatePath = cert
options.keyPath = key
}
}
func WithClientCertificate(certPEMBlock, keyPEMBlock []byte) ClientOption {
return func(options *ClientOptions) {
options.certPem = certPEMBlock
options.keyPem = keyPEMBlock
}
}
func setCertficate(opt ClientOptions) (*http.Transport, error) {
var cert tls.Certificate
var tr *http.Transport
var err error
if opt.certificatePath != "" && opt.keyPath != "" {
cert, err = tls.LoadX509KeyPair(opt.certificatePath, opt.keyPath)
if err != nil {
return tr, err
}
}
if len(opt.certPem) > 0 && len(opt.keyPem) > 0 {
cert, err = tls.X509KeyPair(opt.certPem, opt.keyPem)
if err != nil {
return tr, err
}
}
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true, Certificates: []tls.Certificate{cert}},
}
return tr, nil
}