-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
551 lines (457 loc) · 16.8 KB
/
main.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
// Copyright 2020 Adam Chalkley
//
// https://github.com/atc0005/check-cert
//
// Licensed under the MIT License. See LICENSE file in the project root for
// full license information.
package main
import (
"crypto/x509"
"errors"
"fmt"
"strings"
"time"
"github.com/rs/zerolog"
zlog "github.com/rs/zerolog/log"
"github.com/atc0005/check-cert/internal/certs"
"github.com/atc0005/check-cert/internal/config"
"github.com/atc0005/check-cert/internal/netutils"
"github.com/atc0005/go-nagios"
)
func main() {
// Set initial "state" as valid, adjust as we go.
var nagiosExitState = nagios.ExitState{
LastError: nil,
ExitStatusCode: nagios.StateOKExitCode,
}
// defer this from the start so it is the last deferred function to run
defer nagiosExitState.ReturnCheckResults()
// Setup configuration by parsing user-provided flags.
cfg, cfgErr := config.New(config.AppType{Plugin: true})
switch {
case errors.Is(cfgErr, config.ErrVersionRequested):
fmt.Println(config.Version())
return
case cfgErr != nil:
// We're using the standalone Err function from rs/zerolog/log as we
// do not have a working configuration.
zlog.Err(cfgErr).Msg("Error initializing application")
nagiosExitState.ServiceOutput = fmt.Sprintf(
"%s: Error initializing application",
nagios.StateCRITICALLabel,
)
nagiosExitState.LastError = cfgErr
nagiosExitState.ExitStatusCode = nagios.StateCRITICALExitCode
return
}
if cfg.EmitBranding {
// If enabled, show application details at end of notification
nagiosExitState.BrandingCallback = config.Branding("Notification generated by ")
}
// Use provided threshold values to calculate the expiration times that
// should trigger either a WARNING or CRITICAL state.
now := time.Now().UTC()
certsExpireAgeWarning := now.AddDate(0, 0, cfg.AgeWarning)
certsExpireAgeCritical := now.AddDate(0, 0, cfg.AgeCritical)
nagiosExitState.WarningThreshold = fmt.Sprintf(
"Expires before %v (%d days)",
certsExpireAgeWarning.Format(certs.CertValidityDateLayout),
cfg.AgeWarning,
)
nagiosExitState.CriticalThreshold = fmt.Sprintf(
"Expires before %v (%d days)",
certsExpireAgeCritical.Format(certs.CertValidityDateLayout),
cfg.AgeCritical,
)
log := cfg.Log.With().
Str("expected_sans_entries", cfg.SANsEntries.String()).
Logger()
var certChain []*x509.Certificate
var certChainSource string
// Honor request to parse filename first
switch {
case cfg.Filename != "":
log.Debug().Msg("Attempting to parse certificate file")
// Anything from the specified file that couldn't be converted to a
// certificate chain. While likely not of high value by itself,
// failure to parse a certificate file indicates a likely source of
// trouble. We consider this scenario to be a CRITICAL state.
var parseAttemptLeftovers []byte
var err error
certChain, parseAttemptLeftovers, err = certs.GetCertsFromFile(cfg.Filename)
if err != nil {
log.Error().Err(err).Msg(
"Error parsing certificates file")
nagiosExitState.LastError = err
nagiosExitState.ServiceOutput = fmt.Sprintf(
"%s: Error parsing certificates file %q",
nagios.StateCRITICALLabel,
cfg.Filename,
)
nagiosExitState.ExitStatusCode = nagios.StateCRITICALExitCode
return
}
certChainSource = cfg.Filename
log.Debug().Msg("Certificate file parsed")
if len(parseAttemptLeftovers) > 0 {
log.Error().Err(err).Msg(
"Unknown data encountered while parsing certificates file")
nagiosExitState.LastError = fmt.Errorf(
"%d unknown/unparsed bytes remaining at end of cert file %q",
len(parseAttemptLeftovers),
cfg.Filename,
)
nagiosExitState.ServiceOutput = fmt.Sprintf(
"%s: Unknown data encountered while parsing certificates file %q",
nagios.StateCRITICALLabel,
cfg.Filename,
)
nagiosExitState.LongServiceOutput = fmt.Sprintf(
"The following text from the %q certificate file failed to parse"+
" and is provided here for troubleshooting purposes:%s%s%s",
cfg.Filename,
nagios.CheckOutputEOL,
nagios.CheckOutputEOL,
string(parseAttemptLeftovers),
)
nagiosExitState.ExitStatusCode = nagios.StateCRITICALExitCode
return
}
case cfg.Server != "":
log.Debug().Msg("Expanding given host pattern in order to obtain IP Address")
expandedHost, expandErr := netutils.ExpandHost(cfg.Server)
switch {
case expandErr != nil:
log.Error().Err(expandErr).Msg(
"Error expanding given host pattern")
nagiosExitState.LastError = expandErr
nagiosExitState.ServiceOutput = fmt.Sprintf(
"%s: Error expanding given host pattern %q to target IP Address",
nagios.StateCRITICALLabel,
cfg.Server,
)
nagiosExitState.ExitStatusCode = nagios.StateCRITICALExitCode
// no need to go any further, we *want* to exit right away; we don't
// have a connection to the remote server and there isn't anything
// further we can do
return
// Fail early for IP Ranges. While we could just grab the first
// expanded IP Address, this may be a potential source of confusion
// best avoided.
case expandedHost.Range:
invalidHostPatternErr := errors.New("invalid host pattern")
msg := fmt.Sprintf(
"Given host pattern invalid; " +
"host pattern is a CIDR or partial IP range",
)
log.Error().Err(invalidHostPatternErr).Msg(msg)
nagiosExitState.LastError = invalidHostPatternErr
nagiosExitState.ServiceOutput = fmt.Sprintf(
"%s: %s",
nagios.StateCRITICALLabel,
msg,
)
nagiosExitState.ExitStatusCode = nagios.StateCRITICALExitCode
// no need to go any further, we *want* to exit right away; we don't
// have a connection to the remote server and there isn't anything
// further we can do
return
case len(expandedHost.Expanded) == 0:
expandHostErr := errors.New("host pattern expansion failed")
msg := "Error expanding given host value to IP Address"
log.Error().Err(expandHostErr).Msg(msg)
nagiosExitState.LastError = expandHostErr
nagiosExitState.ServiceOutput = fmt.Sprintf(
"%s: %s",
nagios.StateCRITICALLabel,
msg,
)
nagiosExitState.ExitStatusCode = nagios.StateCRITICALExitCode
// no need to go any further, we *want* to exit right away; we don't
// have a connection to the remote server and there isn't anything
// further we can do
return
case len(expandedHost.Expanded) > 1:
ipAddrs := zerolog.Arr()
for _, ip := range expandedHost.Expanded {
ipAddrs.Str(ip)
}
log.Debug().
Int("num_ip_addresses", len(expandedHost.Expanded)).
Array("ip_addresses", ipAddrs).
Msg("Multiple IP Addresses resolved from given host pattern")
log.Debug().Msg("Using first IP Address, ignoring others")
}
// Grab first IP Address from the resolved collection. We'll
// explicitly use it for cert retrieval and note it in the report
// output.
ipAddr := expandedHost.Expanded[0]
var hostVal string
switch {
case expandedHost.Resolved:
hostVal = expandedHost.Given
certChainSource = fmt.Sprintf(
"service running on %s (%s) at port %d",
hostVal,
ipAddr,
cfg.Port,
)
default:
certChainSource = fmt.Sprintf(
"service running on %s at port %d",
ipAddr,
cfg.Port,
)
}
log.Debug().
Str("host", hostVal).
Str("ip_address", ipAddr).
Int("port", cfg.Port).
Msg("Retrieving certificate chain")
var certFetchErr error
certChain, certFetchErr = netutils.GetCerts(
// NOTE: This is a potentially empty string depending on whether
// host pattern was a resolvable name/FQDN.
hostVal,
ipAddr,
cfg.Port,
cfg.Timeout(),
log,
)
if certFetchErr != nil {
log.Error().Err(certFetchErr).Msg(
"Error fetching certificates chain")
nagiosExitState.LastError = certFetchErr
nagiosExitState.ServiceOutput = fmt.Sprintf(
"%s: Error fetching certificates from port %d on %s",
nagios.StateCRITICALLabel,
cfg.Port,
cfg.Server,
)
nagiosExitState.ExitStatusCode = nagios.StateCRITICALExitCode
// no need to go any further, we *want* to exit right away; we don't
// have a connection to the remote server and there isn't anything
// further we can do
return
}
}
certsSummary := certs.ChainSummary(
certChain,
certsExpireAgeCritical,
certsExpireAgeWarning,
)
// NOTE: Not sure this would ever be reached due to expectations of
// tls.Dial() that a certificate is present for the connection
if certsSummary.TotalCertsCount == 0 {
noCertsErr := fmt.Errorf("no certificates found")
nagiosExitState.LastError = noCertsErr
nagiosExitState.ServiceOutput = fmt.Sprintf(
"%s: 0 certificates found at port %d on %q",
nagios.StateCRITICALLabel,
cfg.Port,
cfg.Server,
)
nagiosExitState.ExitStatusCode = nagios.StateCRITICALExitCode
log.Error().Err(noCertsErr).Msg("No certificates found")
return
}
if certsSummary.TotalCertsCount > 0 {
hostnameValue := cfg.Server
// Allow user to explicitly specify which hostname should be used
// for comparison against the leaf certificate.
if cfg.DNSName != "" {
hostnameValue = cfg.DNSName
}
// Go 1.17 removed support for the legacy behavior of treating the
// CommonName field on X.509 certificates as a host name when no
// Subject Alternative Names are present. Go 1.17 also removed support
// for re-enabling the behavior by way of adding the value
// x509ignoreCN=0 to the GODEBUG environment variable.
//
// If the SANs list is empty and if requested, we skip hostname
// verification and log the event.
switch {
case len(certChain[0].DNSNames) == 0 &&
cfg.DisableHostnameVerificationIfEmptySANsList:
log.Warn().
Str("hostname", hostnameValue).
Str("cert_cn", certChain[0].Subject.CommonName).
Str("sans_entries", fmt.Sprintf("%s", certChain[0].DNSNames)).
Msg("disabling hostname verification as requested for empty SANs list")
default:
// Verify leaf certificate is valid for the provided server FQDN; we
// make the assumption that the leaf certificate is ALWAYS in position
// 0 of the chain. Not having the cert in that position is treated as
// an error condition.
//
// Server Name Indication (SNI) support is used to provide the value
// specified by the `server` flag to the remote server. This is less
// important for remote hosts with only one certificate, but for a
// host with multiple certificates it becomes very important to
// provide the sitename as the value to the `server` flag so that the
// correct certificate for the connection can be provided.
verifyErr := certChain[0].VerifyHostname(hostnameValue)
switch {
// Go 1.17 removed support for the legacy behavior of treating the
// CommonName field on X.509 certificates as a host name when no
// Subject Alternative Names are present. Go 1.17 also removed
// support for re-enabling the behavior by way of adding the value
// x509ignoreCN=0 to the GODEBUG environment variable.
//
// We attempt to detect this situation in order to supply
// additional troubleshooting information and guidance to resolve
// the issue.
case verifyErr != nil &&
// TODO: Is there value in matching the specific error string?
(verifyErr.Error() == certs.X509CertReliesOnCommonName ||
len(certChain[0].DNSNames) == 0):
nagiosExitState.LastError = verifyErr
nagiosExitState.ExitStatusCode = nagios.StateCRITICALExitCode
nagiosExitState.ServiceOutput = fmt.Sprintf(
"%s: Verification of hostname %q failed for first cert in chain",
nagios.StateCRITICALLabel,
hostnameValue,
)
nagiosExitState.LongServiceOutput =
"This certificate is missing Subject Alternate Names (SANs)" +
" and should be replaced." +
nagios.CheckOutputEOL +
nagios.CheckOutputEOL +
"As a temporary workaround, you can" +
" use v0.5.3 of this plugin, rebuild this plugin" +
" using Go 1.16 or specify the flag to skip hostname" +
" verification if the SANs list is found to be empty." +
nagios.CheckOutputEOL +
nagios.CheckOutputEOL +
"See these resources for additional information: " +
nagios.CheckOutputEOL +
nagios.CheckOutputEOL +
" - https://github.com/atc0005/check-cert/issues/276" +
nagios.CheckOutputEOL +
" - https://chromestatus.com/feature/4981025180483584" +
nagios.CheckOutputEOL +
" - https://bugzilla.mozilla.org/show_bug.cgi?id=1245280"
return
// Hostname verification failed for another reason aside from an
// empty SANs list.
case verifyErr != nil:
log.Error().
Err(verifyErr).
Str("hostname", hostnameValue).
Str("cert_cn", certChain[0].Subject.CommonName).
Str("sans_entries", fmt.Sprintf("%s", certChain[0].DNSNames)).
Msg("verification of hostname failed for first cert in chain")
nagiosExitState.LastError = verifyErr
nagiosExitState.ExitStatusCode = nagios.StateCRITICALExitCode
nagiosExitState.ServiceOutput = fmt.Sprintf(
"%s: Verification of hostname %q failed for first cert in chain",
nagios.StateCRITICALLabel,
hostnameValue,
)
nagiosExitState.LongServiceOutput =
"Consider updating the service check or command " +
"definition to specify the website FQDN instead of " +
"the host FQDN as the 'dns-name' (or 'server') flag value. " +
"E.g., use 'www.example.org' instead of " +
"'host7.example.com' in order to allow the remote " +
"server to select the correct certificate instead " +
"of using the default certificate."
return
// Hostname verification succeeded.
default:
log.Debug().
Str("hostname", hostnameValue).
Str("cert_cn", certChain[0].Subject.CommonName).
Msg("Verification of hostname succeeded for first cert in chain")
}
}
}
// Prepend a baseline lead-in that summarizes the number of certificates
// retrieved and from which target host/IP Address.
defer func() {
nagiosExitState.LongServiceOutput = fmt.Sprintf(
"%d certs found for %s%s%s%s",
certsSummary.TotalCertsCount,
certChainSource,
nagios.CheckOutputEOL,
nagios.CheckOutputEOL,
nagiosExitState.LongServiceOutput,
)
}()
// check SANS entries if provided via command-line
if len(cfg.SANsEntries) > 0 {
// Check for special keyword, skip SANs entry checks if provided
firstSANsEntry := strings.ToLower(strings.TrimSpace(cfg.SANsEntries[0]))
if firstSANsEntry != strings.ToLower(strings.TrimSpace(config.SkipSANSCheckKeyword)) {
if mismatched, err := certs.CheckSANsEntries(certChain[0], certChain, cfg.SANsEntries); err != nil {
nagiosExitState.LastError = err
nagiosExitState.LongServiceOutput = certs.GenerateCertsReport(
certsSummary,
cfg.VerboseOutput,
)
nagiosExitState.ServiceOutput = fmt.Sprintf(
"%s: Mismatch of %d SANs entries for certificate",
nagios.StateCRITICALLabel,
mismatched,
)
nagiosExitState.ExitStatusCode = nagios.StateWARNINGExitCode
log.Warn().
Err(nagiosExitState.LastError).
Int("sans_entries_requested", len(cfg.SANsEntries)).
Int("sans_entries_found", len(certChain)).
Msg("SANs entries mismatch")
return
}
}
}
switch {
case certsSummary.IsCriticalState() || certsSummary.IsWarningState():
nagiosExitState.LastError = fmt.Errorf(
"%d certificates expired or expiring",
certsSummary.ExpiredCertsCount+certsSummary.ExpiringCertsCount,
)
nagiosExitState.LongServiceOutput = certs.GenerateCertsReport(
certsSummary,
cfg.VerboseOutput,
)
nagiosExitState.ServiceOutput = certs.OneLineCheckSummary(
certsSummary,
true,
)
nagiosExitState.ExitStatusCode = certsSummary.ServiceState().ExitCode
log.Error().
Err(nagiosExitState.LastError).
Int("expired_certs", certsSummary.ExpiredCertsCount).
Int("expiring_certs", certsSummary.ExpiringCertsCount).
Msg("expired or expiring certs present in chain")
default:
nagiosExitState.LastError = nil
nagiosExitState.ServiceOutput = certs.OneLineCheckSummary(
certsSummary,
true,
)
nagiosExitState.LongServiceOutput = certs.GenerateCertsReport(
certsSummary,
cfg.VerboseOutput,
)
nagiosExitState.ExitStatusCode = nagios.StateOKExitCode
log.Debug().Msg("No problems with certificate chain detected")
}
// While we provide a flag to skip hostname verification for certs missing
// SANs list entries, it isn't advisable for long-term use. We note this
// in the LongServiceOutput as a reminder to sysadmins who may review the
// output.
if certsSummary.TotalCertsCount > 0 &&
len(certChain[0].DNSNames) == 0 &&
cfg.DisableHostnameVerificationIfEmptySANsList {
nagiosExitState.LongServiceOutput +=
nagios.CheckOutputEOL +
"NOTE: The option to skip hostname verification when" +
" certificate SANs list is empty has been specified." +
nagios.CheckOutputEOL +
nagios.CheckOutputEOL +
"While viable as a short-term workaround for certificates" +
" missing SANs list entries, this is not recommended as a" +
" long-term fix."
}
}