-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
pki_health_check.go
379 lines (318 loc) · 10.9 KB
/
pki_health_check.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
package command
import (
"encoding/json"
"fmt"
"os"
"strings"
"github.com/hashicorp/vault/command/healthcheck"
"github.com/ghodss/yaml"
"github.com/mitchellh/cli"
"github.com/posener/complete"
"github.com/ryanuber/columnize"
)
const (
pkiRetOK int = iota
pkiRetUsage
pkiRetInformational
pkiRetWarning
pkiRetCritical
pkiRetInvalidVersion
pkiRetInsufficientPermissions
)
var (
_ cli.Command = (*PKIHealthCheckCommand)(nil)
_ cli.CommandAutocomplete = (*PKIHealthCheckCommand)(nil)
// Ensure the above return codes match (outside of OK/Usage) the values in
// the healthcheck package.
_ = pkiRetInformational == int(healthcheck.ResultInformational)
_ = pkiRetWarning == int(healthcheck.ResultWarning)
_ = pkiRetCritical == int(healthcheck.ResultCritical)
_ = pkiRetInvalidVersion == int(healthcheck.ResultInvalidVersion)
_ = pkiRetInsufficientPermissions == int(healthcheck.ResultInsufficientPermissions)
)
type PKIHealthCheckCommand struct {
*BaseCommand
flagConfig string
flagReturnIndicator string
flagDefaultDisabled bool
flagList bool
}
func (c *PKIHealthCheckCommand) Synopsis() string {
return "Check a PKI Secrets Engine mount's health and operational status"
}
func (c *PKIHealthCheckCommand) Help() string {
helpText := `
Usage: vault pki health-check [options] MOUNT
Reports status of the specified mount against best practices and pending
failures. This is an informative command and not all recommendations will
apply to all mounts; consider using a configuration file to tune the
executed health checks.
To check the pki-root mount with default configuration:
$ vault pki health-check pki-root
To specify a configuration:
$ vault pki health-check -health-config=mycorp-root.json /pki-root
Return codes indicate failure type:
0 - Everything is good.
1 - Usage error (check CLI parameters).
2 - Informational message from a health check.
3 - Warning message from a health check.
4 - Critical message from a health check.
5 - A version mismatch between health check and Vault Server occurred,
preventing one or more health checks from being run.
6 - A permission denied message was returned from Vault Server for
one or more health checks.
For more detailed information, refer to the online documentation about the
vault pki health-check command.
` + c.Flags().Help()
return strings.TrimSpace(helpText)
}
func (c *PKIHealthCheckCommand) Flags() *FlagSets {
set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
f.StringVar(&StringVar{
Name: "health-config",
Target: &c.flagConfig,
Default: "",
EnvVar: "",
Usage: "Path to JSON configuration file to modify health check execution and parameters.",
})
f.StringVar(&StringVar{
Name: "return-indicator",
Target: &c.flagReturnIndicator,
Default: "default",
EnvVar: "",
Completion: complete.PredictSet("default", "informational", "warning", "critical", "permission"),
Usage: `Behavior of the return value:
- permission, for exiting with a non-zero code when the tool lacks
permissions or has a version mismatch with the server;
- critical, for exiting with a non-zero code when a check returns a
critical status in addition to the above;
- warning, for exiting with a non-zero status when a check returns a
warning status in addition to the above;
- informational, for exiting with a non-zero status when a check returns
an informational status in addition to the above;
- default, for the default behavior based on severity of message and
only returning a zero exit status when all checks have passed
and no execution errors have occurred.
`,
})
f.BoolVar(&BoolVar{
Name: "default-disabled",
Target: &c.flagDefaultDisabled,
Default: false,
EnvVar: "",
Usage: `When specified, results in all health checks being disabled by
default unless enabled by the configuration file explicitly.`,
})
f.BoolVar(&BoolVar{
Name: "list",
Target: &c.flagList,
Default: false,
EnvVar: "",
Usage: `When specified, no health checks are run, but all known health
checks are printed.`,
})
return set
}
func (c *PKIHealthCheckCommand) isValidRetIndicator() bool {
switch c.flagReturnIndicator {
case "", "default", "informational", "warning", "critical", "permission":
return true
default:
return false
}
}
func (c *PKIHealthCheckCommand) AutocompleteArgs() complete.Predictor {
// Return an anything predictor here, similar to `vault write`. We
// don't know what values are valid for the mount path.
return complete.PredictAnything
}
func (c *PKIHealthCheckCommand) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *PKIHealthCheckCommand) Run(args []string) int {
// Parse and validate the arguments.
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return pkiRetUsage
}
args = f.Args()
if !c.flagList && len(args) < 1 {
c.UI.Error("Not enough arguments (expected mount path, got nothing)")
return pkiRetUsage
} else if !c.flagList && len(args) > 1 {
c.UI.Error(fmt.Sprintf("Too many arguments (expected only mount path, got %d arguments)", len(args)))
for _, arg := range args {
if strings.HasPrefix(arg, "-") {
c.UI.Warn(fmt.Sprintf("Options (%v) must be specified before positional arguments (%v)", arg, args[0]))
break
}
}
return pkiRetUsage
}
if !c.isValidRetIndicator() {
c.UI.Error(fmt.Sprintf("Invalid flag -return-indicator=%v; known options are default, informational, warning, critical, and permission", c.flagReturnIndicator))
return pkiRetUsage
}
// Setup the client and the executor.
client, err := c.Client()
if err != nil {
c.UI.Error(err.Error())
return pkiRetUsage
}
// When listing is enabled, we lack an argument here, but do not contact
// the server at all, so we're safe to use a hard-coded default here.
pkiPath := "<mount>"
if len(args) == 1 {
pkiPath = args[0]
}
mount := sanitizePath(pkiPath)
executor := healthcheck.NewExecutor(client, mount)
executor.AddCheck(healthcheck.NewCAValidityPeriodCheck())
executor.AddCheck(healthcheck.NewCRLValidityPeriodCheck())
executor.AddCheck(healthcheck.NewHardwareBackedRootCheck())
executor.AddCheck(healthcheck.NewRootIssuedLeavesCheck())
executor.AddCheck(healthcheck.NewRoleAllowsLocalhostCheck())
executor.AddCheck(healthcheck.NewRoleAllowsGlobWildcardsCheck())
executor.AddCheck(healthcheck.NewRoleNoStoreFalseCheck())
executor.AddCheck(healthcheck.NewAuditVisibilityCheck())
executor.AddCheck(healthcheck.NewAllowIfModifiedSinceCheck())
executor.AddCheck(healthcheck.NewEnableAutoTidyCheck())
executor.AddCheck(healthcheck.NewTidyLastRunCheck())
executor.AddCheck(healthcheck.NewTooManyCertsCheck())
if c.flagDefaultDisabled {
executor.DefaultEnabled = false
}
// Handle listing, if necessary.
if c.flagList {
uiFormat := Format(c.UI)
if uiFormat == "yaml" {
c.UI.Error("YAML output format is not supported by the --list command")
return pkiRetUsage
}
if uiFormat != "json" {
c.UI.Output("Default health check config:")
}
config := map[string]map[string]interface{}{}
for _, checker := range executor.Checkers {
config[checker.Name()] = checker.DefaultConfig()
}
marshaled, err := json.MarshalIndent(config, "", " ")
if err != nil {
c.UI.Error(fmt.Sprintf("Failed to marshal default config for check: %v", err))
return pkiRetUsage
}
c.UI.Output(string(marshaled))
return pkiRetOK
}
// Handle config merging.
external_config := map[string]interface{}{}
if c.flagConfig != "" {
contents, err := os.Open(c.flagConfig)
if err != nil {
c.UI.Error(fmt.Sprintf("Failed to read configuration file %v: %v", c.flagConfig, err))
return pkiRetUsage
}
decoder := json.NewDecoder(contents)
decoder.UseNumber() // Use json.Number instead of float64 values as we are decoding to an interface{}.
if err := decoder.Decode(&external_config); err != nil {
c.UI.Error(fmt.Sprintf("Failed to parse configuration file %v: %v", c.flagConfig, err))
return pkiRetUsage
}
}
if err := executor.BuildConfig(external_config); err != nil {
c.UI.Error(fmt.Sprintf("Failed to build health check configuration: %v", err))
return pkiRetUsage
}
// Run the health checks.
results, err := executor.Execute()
if err != nil {
c.UI.Error(fmt.Sprintf("Failed to run health check: %v", err))
return pkiRetUsage
}
// Display the output.
if err := c.outputResults(executor, results); err != nil {
c.UI.Error(fmt.Sprintf("Failed to render results for display: %v", err))
}
// Select an appropriate return code.
return c.selectRetCode(results)
}
func (c *PKIHealthCheckCommand) outputResults(e *healthcheck.Executor, results map[string][]*healthcheck.Result) error {
switch Format(c.UI) {
case "", "table":
return c.outputResultsTable(e, results)
case "json":
return c.outputResultsJSON(results)
case "yaml":
return c.outputResultsYAML(results)
default:
return fmt.Errorf("unknown output format: %v", Format(c.UI))
}
}
func (c *PKIHealthCheckCommand) outputResultsTable(e *healthcheck.Executor, results map[string][]*healthcheck.Result) error {
// Iterate in checker order to ensure stable output.
for _, checker := range e.Checkers {
if !checker.IsEnabled() {
continue
}
scanner := checker.Name()
findings := results[scanner]
c.UI.Output(scanner)
c.UI.Output(strings.Repeat("-", len(scanner)))
data := []string{"status" + hopeDelim + "endpoint" + hopeDelim + "message"}
for _, finding := range findings {
row := []string{
finding.StatusDisplay,
finding.Endpoint,
finding.Message,
}
data = append(data, strings.Join(row, hopeDelim))
}
c.UI.Output(tableOutput(data, &columnize.Config{
Delim: hopeDelim,
}))
c.UI.Output("\n")
}
return nil
}
func (c *PKIHealthCheckCommand) outputResultsJSON(results map[string][]*healthcheck.Result) error {
bytes, err := json.MarshalIndent(results, "", " ")
if err != nil {
return err
}
c.UI.Output(string(bytes))
return nil
}
func (c *PKIHealthCheckCommand) outputResultsYAML(results map[string][]*healthcheck.Result) error {
bytes, err := yaml.Marshal(results)
if err != nil {
return err
}
c.UI.Output(string(bytes))
return nil
}
func (c *PKIHealthCheckCommand) selectRetCode(results map[string][]*healthcheck.Result) int {
var highestResult healthcheck.ResultStatus = healthcheck.ResultNotApplicable
for _, findings := range results {
for _, finding := range findings {
if finding.Status > highestResult {
highestResult = finding.Status
}
}
}
cutOff := healthcheck.ResultInformational
switch c.flagReturnIndicator {
case "", "default", "informational":
case "permission":
cutOff = healthcheck.ResultInvalidVersion
case "critical":
cutOff = healthcheck.ResultCritical
case "warning":
cutOff = healthcheck.ResultWarning
}
if highestResult >= cutOff {
return int(highestResult)
}
return pkiRetOK
}