-
Notifications
You must be signed in to change notification settings - Fork 2
/
configuration.go
435 lines (392 loc) · 11.3 KB
/
configuration.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
package configuration
import (
"crypto/sha1"
"crypto/sha256"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/appgate/sdpctl/pkg/api"
"github.com/appgate/sdpctl/pkg/cmdutil"
"github.com/appgate/sdpctl/pkg/keyring"
"github.com/appgate/sdpctl/pkg/profiles"
"github.com/appgate/sdpctl/pkg/util"
"github.com/denisbrodbeck/machineid"
"github.com/google/uuid"
"github.com/hashicorp/go-version"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/net/context"
)
type Config struct {
URL string `mapstructure:"url"`
Provider *string `mapstructure:"provider"`
Insecure bool `mapstructure:"insecure"`
Debug bool `mapstructure:"debug"` // http debug flag
Version int `mapstructure:"api_version"` // api peer interface version
BearerToken *string `mapstructure:"bearer:squash"` // current logged in user token
ExpiresAt *string `mapstructure:"expires_at"`
DeviceID string `mapstructure:"device_id"`
PemFilePath string `mapstructure:"pem_filepath"` // deprecated in favor of pem_base64, kept for backwards compatibility
PemBase64 *string `mapstructure:"pem_base64"`
DisableVersionCheck bool `mapstructure:"disable_version_check"`
LastVersionCheck string `mapstructure:"last_version_check"`
}
type Credentials struct {
Username string
Password string
}
func (c *Config) GetBearTokenHeaderValue() (string, error) {
// if the bearer token is in the config, we assume the current environment does not support a keyring, so we will use it.
// this will also include if the environment variable SDPCTL_BEARER is being used.
if c.BearerToken != nil && len(*c.BearerToken) > 10 {
return fmt.Sprintf("Bearer %s", *c.BearerToken), nil
}
prefix, err := c.KeyringPrefix()
if err != nil {
return "", fmt.Errorf("Could not retrieve token for current host configuration %w", err)
}
v, err := keyring.GetBearer(prefix)
if err != nil {
return "", err
}
return fmt.Sprintf("Bearer %s", v), nil
}
// DefaultDeviceID return a unique ID in UUID format.
// machine.ID() tries to read
// /etc/machine-id on Linux
// /etc/hostid on BSD
// ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID on OSX
// reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography /v MachineGuid on Windows
// and tries to parse the value as a UUID
// https://github.com/denisbrodbeck/machineid
// if we can't get a valid UUID based on the machine ID, we will fallback to a random UUID value.
func DefaultDeviceID() string {
readAndParseUUID := func() (string, error) {
id, err := machineid.ID()
if err != nil {
return "", err
}
uid, err := uuid.Parse(id)
if err != nil {
return "", err
}
return uid.String(), nil
}
v, err := readAndParseUUID()
if err != nil {
return uuid.New().String()
}
return v
}
const SkipAuthCheck = "skipAuthCheck"
func IsAuthCheckEnabled(cmd *cobra.Command) bool {
switch cmd.Name() {
case "help", cobra.ShellCompRequestCmd, cobra.ShellCompNoDescRequestCmd:
return false
}
for c := cmd; c.Parent() != nil; c = c.Parent() {
if c.Annotations != nil && c.Annotations[SkipAuthCheck] == "true" {
return false
}
}
return true
}
func CheckMinAPIVersionRestriction(cmd *cobra.Command, currentVersion int) error {
c := cmd
for c != nil {
if c.Annotations != nil {
if s, ok := c.Annotations["MinAPIVersion"]; ok {
if minVersion, err := strconv.Atoi(s); err == nil && currentVersion < minVersion {
if message, ok := c.Annotations["ErrorMessage"]; ok {
return errors.New(message)
}
return fmt.Errorf("Minimum API version %d is required to use the '%s' command. Current API version is %d", minVersion, c.Name(), currentVersion)
}
}
}
c = c.Parent()
}
return nil
}
const NeedUpdateAPIConfig = "updateAPIConfig"
func NeedUpdatedAPIVersionConfig(cmd *cobra.Command) bool {
for c := cmd; c.Parent() != nil; c = c.Parent() {
if c.Annotations != nil && c.Annotations[NeedUpdateAPIConfig] == "true" {
return true
}
}
return false
}
var ErrNoAddr = errors.New("No valid address set, run 'sdpctl configure' or set SDPCTL_URL")
func NormalizeConfigurationURL(u string) (string, error) {
if len(u) <= 0 {
return "", ErrNoAddr
}
url, err := util.NormalizeURL(u)
if err != nil {
return "", err
}
if len(url.Port()) <= 0 {
url.Host = fmt.Sprintf("%s:%d", url.Hostname(), 8443)
}
if url.Path != "/admin" {
url.Path = "/admin"
}
return url.String(), nil
}
func (c *Config) IsRequireAuthentication() bool {
if len(c.URL) < 1 {
return true
}
if c.Provider == nil {
return true
}
t, err := c.GetBearTokenHeaderValue()
if err != nil {
return true
}
if len(t) < 10 {
return true
}
return !c.ExpiredAtValid()
}
func (c *Config) ExpiredAtValid() bool {
if c.ExpiresAt == nil {
return false
}
layout := "2006-01-02 15:04:05.999999999 -0700 MST"
t1, err := time.Parse(layout, *c.ExpiresAt)
if err != nil {
return false
}
now := time.Now().Add(-time.Hour * 2)
return t1.After(now)
}
func (c *Config) LoadCredentials() (*Credentials, error) {
creds := &Credentials{}
prefix, err := c.KeyringPrefix()
if err != nil {
return nil, err
}
if v, err := keyring.GetUsername(prefix); err == nil && len(v) > 0 {
creds.Username = v
}
if v, err := keyring.GetPassword(prefix); err == nil && len(v) > 0 {
creds.Password = v
}
return creds, nil
}
func (c *Config) ClearCredentials() error {
prefix, err := c.KeyringPrefix()
if err != nil {
return err
}
if err := keyring.ClearCredentials(prefix); err != nil {
return err
}
if err := c.ClearBearer(); err != nil {
return err
}
c.Provider = nil
keys := []string{"expires_at", "provider"}
allKeys := viper.AllKeys()
for _, k := range keys {
if util.InSlice(k, allKeys) {
viper.Set(k, "")
}
}
if err := viper.WriteConfig(); err != nil {
// only return error if there is a config file to write to
// as is the case when using environment variables for configuration
// or in testing
if !errors.As(err, &viper.ConfigFileNotFoundError{}) {
return err
}
}
return nil
}
func (c *Config) ClearBearer() error {
h, err := c.GetHost()
if err != nil {
return err
}
if err := keyring.DeleteBearer(h); err != nil {
return err
}
c.BearerToken = nil
c.ExpiresAt = nil
return nil
}
func (c *Config) StoreCredentials(username, password string) error {
prefix, err := c.KeyringPrefix()
if err != nil {
return err
}
if err := keyring.SetUsername(prefix, username); err != nil {
return fmt.Errorf("Could not store username in keychain %w", err)
}
if err := keyring.SetPassword(prefix, password); err != nil {
return fmt.Errorf("Could not store password in keychain %w", err)
}
return nil
}
func (c *Config) GetHost() (string, error) {
if len(c.URL) == 0 {
return "", ErrNoAddr
}
url, err := url.Parse(c.URL)
if err != nil {
return "", err
}
return url.Hostname(), nil
}
// KeyringPrefix is the raw string values that will be used in the keyring package
// it needs to be a unique, reproducible value for the selected Collective + profile.
// Downstream, this string value will be converted to a integer value (pkg/hashcode)
// and used as a prefix when storing values in the keyring/keychain.
func (c *Config) KeyringPrefix() (string, error) {
h, err := c.GetHost()
if err != nil {
return "", err
}
p, err := profiles.Read()
if err == nil {
if p.CurrentExists() {
if c, err := p.CurrentProfile(); err == nil {
return c.Name + h, nil
}
}
}
return h, nil
}
func (c *Config) CheckForUpdate(out io.Writer, client *http.Client, current string) (*Config, error) {
// Check if version check is disabled in configuration
if c.DisableVersionCheck {
return c, cmdutil.ErrVersionCheckDisabled
}
// Check if version check has already been done today
lastCheck, err := time.Parse(time.RFC3339Nano, c.LastVersionCheck)
if err == nil {
yesterday := time.Now().AddDate(0, 0, -1)
if !lastCheck.Before(yesterday) {
return c, cmdutil.ErrDailyVersionCheck
}
}
// Perform version check
const cliReleasesURL = "https://api.github.com/repos/appgate/sdpctl/releases"
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, cliReleasesURL, nil)
if err != nil {
return c, err
}
// Write new check time to config after request is made
c.LastVersionCheck = time.Now().Format(time.RFC3339Nano)
viper.Set("last_version_check", c.LastVersionCheck)
req.Header.Add("Accept", "application/vnd.github+json")
res, err := api.RequestRetry(client, req)
if err != nil {
return c, err
}
defer res.Body.Close()
type githubRelease struct {
TagName string `json:"tag_name"`
PreRelease bool `json:"pre_release"`
Draft bool `json:"draft"`
}
type releaseList []githubRelease
if res.StatusCode != http.StatusOK {
return c, fmt.Errorf("unexpected request status: %d", res.StatusCode)
}
b, err := io.ReadAll(res.Body)
if err != nil {
return c, err
}
var releases releaseList
if err := json.Unmarshal(b, &releases); err != nil {
return c, err
}
v, err := version.NewVersion(current)
if err != nil {
return c, err
}
var latest *version.Version
r := releases[0]
n, err := version.NewVersion(r.TagName)
if err != nil {
return c, err
}
if !r.Draft && !r.PreRelease && n.GreaterThan(v) {
latest = n
}
if latest != nil {
fmt.Fprintf(out, "NOTICE: A new version of sdpctl is available for download: %s\nDownload it here: https://github.com/appgate/sdpctl/releases/tag/%s\n\n", latest.Original(), latest.Original())
}
return c, nil
}
func ReadPemFile(path string) (*x509.Certificate, error) {
info, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("Path %s does not exist", path)
}
return nil, fmt.Errorf("%s - %s", path, err)
}
if info.IsDir() {
return nil, fmt.Errorf("path %s is a directory, not a file", path)
}
b, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("not a file %s %s", path, err)
}
pemData, certBytes := pem.Decode(b)
if pemData != nil {
certBytes = pemData.Bytes
}
// See if we can parse the certificate
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, fmt.Errorf("failed to parse certificate: %w", err)
}
return cert, nil
}
func CertificateDetails(cert *x509.Certificate) string {
var sb strings.Builder
if len(cert.Subject.CommonName) > 0 {
sb.WriteString(fmt.Sprintf("[Subject]\n\t%s\n", cert.Subject.CommonName))
}
if len(cert.Issuer.CommonName) > 0 {
sb.WriteString(fmt.Sprintf("[Issuer]\n\t%s\n", cert.Issuer.CommonName))
}
if cert.SerialNumber != nil {
sb.WriteString(fmt.Sprintf("[Serial Number]\n\t%s\n", cert.SerialNumber))
}
sb.WriteString(fmt.Sprintf("[Not Before]\n\t%s\n", cert.NotBefore))
sb.WriteString(fmt.Sprintf("[Not After]\n\t%s\n", cert.NotAfter))
var sha1buf strings.Builder
for i, f := range sha1.Sum(cert.Raw) {
if i > 0 {
sha1buf.Write([]byte(":"))
}
sha1buf.Write([]byte(fmt.Sprintf("%02X", f)))
}
sb.WriteString(fmt.Sprintf("[Thumbprint SHA-1]\n\t%s\n", sha1buf.String()))
var sha256buf strings.Builder
for i, f := range sha256.Sum256(cert.Raw) {
if i > 0 {
sha256buf.Write([]byte(":"))
}
sha256buf.Write([]byte(fmt.Sprintf("%02X", f)))
}
sb.WriteString(fmt.Sprintf("[Thumbprint SHA-256]\n\t%s\n", sha256buf.String()))
return sb.String()
}