This repository has been archived by the owner on Mar 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
conn.go
217 lines (189 loc) · 6.52 KB
/
conn.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
package splunk
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"time"
"github.com/fatih/structs"
uuid "github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/certutil"
"github.com/hashicorp/vault/sdk/helper/tlsutil"
"github.com/hashicorp/vault/sdk/helper/useragent"
"github.com/hashicorp/vault/sdk/logical"
"golang.org/x/oauth2"
"github.com/splunk/vault-plugin-splunk/clients/splunk"
)
const (
respErrEmptyName = `missing or empty "name" parameter`
)
type splunkConfig struct {
ID string `json:"id" structs:"id"`
Username string `json:"username" structs:"username"`
Password string `json:"password" structs:"password"`
URL string `json:"url" structs:"url"`
IsStandalone bool `json:"is_standalone" structs:"is_standalone"`
AllowedRoles []string `json:"allowed_roles" structs:"allowed_roles"`
Verify bool `json:"verify" structs:"verify"`
InsecureTLS bool `json:"insecure_tls" structs:"insecure_tls"`
Certificate string `json:"certificate" structs:"certificate"`
PrivateKey string `json:"private_key" structs:"private_key"`
CAChain []string `json:"ca_chain" structs:"ca_chain"`
RootCA []string `json:"root_ca" structs:"root_ca"`
TLSMinVersion string `json:"tls_min_version" structs:"tls_min_version"`
ConnectTimeout time.Duration `json:"connect_timeout" structs:"connect_timeout"`
}
func (config *splunkConfig) toResponseData() map[string]interface{} {
data := structs.New(config).Map()
data["connect_timeout"] = int64(config.ConnectTimeout.Seconds())
data["password"] = "n/a"
data["private_key"] = "n/a"
return data
}
func (config *splunkConfig) toMinimalResponseData() map[string]interface{} {
data := map[string]interface{}{
"id": config.ID,
"username": config.Username,
// "X-DEBUG-password": config.Password,
"url": config.URL,
}
return data
}
func (config *splunkConfig) store(ctx context.Context, s logical.Storage, name string) (err error) {
oldConfigID := config.ID
if oldConfigID != "" {
// we cannot reliably clean up the old cached connection, since some in-progress operation
// might just call ensureConnection and reinstate it. The window for this is the max life-time
// of any request that was in flight during this store operation.
//
// Therefore, we'll have the WAL clean up after some time that's longer than the longest
// expected response time.
var walID string
walID, err = framework.PutWAL(ctx, s, walTypeConn, &walConnection{oldConfigID})
if err != nil {
return fmt.Errorf("unable to create WAL for deleting cached connection: %w", err)
}
defer func() {
if err != nil {
// config was not stored => cancel cleanup
// #nosec G104
// nolint:errcheck
framework.DeleteWAL(ctx, s, walID)
}
}()
}
config.ID, err = uuid.GenerateUUID()
if err != nil {
return fmt.Errorf("error generating new configuration ID: %w", err)
}
var newEntry *logical.StorageEntry
newEntry, err = logical.StorageEntryJSON(fmt.Sprintf("config/%s", name), config)
if err != nil {
return fmt.Errorf("error writing config/%s JSON: %w", name, err)
}
if err = s.Put(ctx, newEntry); err != nil {
return fmt.Errorf("error saving new config/%s: %w", name, err)
}
// if config.Verify {
// config.verifyConnection(ctx, s, name)
// }
return err
}
func connectionConfigExists(ctx context.Context, s logical.Storage, name string) (bool, error) {
if name == "" {
return false, fmt.Errorf(respErrEmptyName)
}
entry, err := s.Get(ctx, fmt.Sprintf("config/%s", name))
if err != nil {
return false, fmt.Errorf("error reading connection configuration: %w", err)
}
return entry != nil, nil
}
func connectionConfigLoad(ctx context.Context, s logical.Storage, name string) (*splunkConfig, error) {
if name == "" {
return nil, fmt.Errorf(respErrEmptyName)
}
entry, err := s.Get(ctx, fmt.Sprintf("config/%s", name))
if err != nil {
return nil, fmt.Errorf("error reading connection configuration: %w", err)
}
if entry == nil {
return nil, fmt.Errorf("connection configuration not found: %q", name)
}
config := splunkConfig{}
if err := entry.DecodeJSON(&config); err != nil {
return nil, err
}
return &config, nil
}
func (config *splunkConfig) newConnection(ctx context.Context) (*splunk.API, error) {
p := &splunk.APIParams{
BaseURL: config.URL,
UserAgent: useragent.String(),
Config: oauth2.Config{
ClientID: config.Username,
ClientSecret: config.Password,
},
}
tlsConfig, err := config.tlsConfig()
if err != nil {
return nil, err
}
tr := &http.Transport{
TLSClientConfig: tlsConfig,
Proxy: http.ProxyFromEnvironment,
}
// client is the underlying transport for API calls, including Login (for obtaining session token)
client := &http.Client{
Transport: tr,
Timeout: config.ConnectTimeout,
}
ctx = context.WithValue(ctx, oauth2.HTTPClient, client)
return p.NewAPI(ctx), nil
}
func (config *splunkConfig) tlsConfig() (tlsConfig *tls.Config, err error) {
if len(config.Certificate) > 0 || (config.CAChain != nil && len(config.CAChain) > 0) {
if len(config.Certificate) > 0 && len(config.PrivateKey) == 0 {
return nil, fmt.Errorf("found certificate for TLS authentication but no private key")
}
certBundle := &certutil.CertBundle{
Certificate: config.Certificate,
PrivateKey: config.PrivateKey,
CAChain: config.CAChain,
}
parsedCertBundle, err := certBundle.ToParsedCertBundle()
if err != nil {
return nil, fmt.Errorf("failed to parse certificate bundle: %w", err)
}
tlsConfig, err = parsedCertBundle.GetTLSConfig(certutil.TLSClient)
if err != nil || tlsConfig == nil {
return nil, fmt.Errorf("failed to get TLS configuration: tlsConfig: %#v; %w", tlsConfig, err)
}
} else {
tlsConfig = &tls.Config{
MinVersion: tls.VersionTLS12, // gosec G402
}
}
tlsConfig.InsecureSkipVerify = config.InsecureTLS
if config.TLSMinVersion != "" {
var ok bool
if tlsConfig.MinVersion, ok = tlsutil.TLSLookup[config.TLSMinVersion]; !ok {
return nil, fmt.Errorf(`invalid "tls_min_version" in config`)
}
} else {
// MinVersion was not being set earlier. Reset it to
// zero to gracefully handle upgrades.
tlsConfig.MinVersion = 0
}
if config.RootCA != nil && len(config.RootCA) > 0 {
if tlsConfig.RootCAs == nil {
tlsConfig.RootCAs = x509.NewCertPool()
}
for _, cert := range config.RootCA {
tlsConfig.RootCAs.AppendCertsFromPEM([]byte(cert))
}
}
return tlsConfig, nil
}