aboutsummaryrefslogtreecommitdiff
path: root/certwatch.go
blob: e75d09eea5a82cbb05df0f88afa8131936320c45 (plain)
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
package main

import (
	"crypto/tls"
	"crypto/x509"
	"os"
	"strings"
	"fmt"
	"time"
	"flag"
)

// Nagios status constants
const (
	StatusOK = iota
	StatusWarning
	StatusCritical
	StatusUnknown
)

var statusString = []string{StatusOK: `OK`,
		            StatusWarning: `WARNING`,
	                    StatusCritical: `CRITICAL`,
	                    StatusUnknown: `UNKNOWN`,}

type CertResult struct {
	Address string
	Subject string
	Status int
	Ttl time.Duration
	Error string
}

type CertResultList struct {
	Status int
	Result []CertResult
}

// The cnmap interface
type cnmap map[string]bool

func (mp *cnmap) Set(value string) error {
	if *mp == nil {
		*mp = make(map[string]bool)
	}
	for _, cn := range strings.Split(value, ",") {
		(*mp)[cn] = true
	}
	return nil
}

func (mp *cnmap) String() string {
	var a []string
	for k := range *mp {
		a = append(a, k)
	}
	return strings.Join(a, `,`)
}

func (mp cnmap) Selected(cert *x509.Certificate) bool {
	if mp == nil {
		return true
	}
	if v, p := mp[cert.Subject.CommonName]; p {
		return v
	}
	for _, name := range cert.DNSNames {
		if v, p := mp[name]; p {
			return v
		}
	}
	return false
}

// Command line options
var warnLimit time.Duration
var critLimit time.Duration
var verboseOption bool
var helpOption bool
var selectCN cnmap
var host string

// Intitialize command line parser
func init() {
	flag.DurationVar(&warnLimit, `w`, 0, `warning threshold`)
	flag.DurationVar(&critLimit, `c`, 0, `critical threshold`)
	flag.BoolVar(&verboseOption, `v`, false, `verbose mode`)
	flag.BoolVar(&helpOption, `h`, false, `show help summary`)
	flag.Var(&selectCN, `s`, `comma-separated list of allowed CNs`)
	flag.StringVar(&host, `H`, ``, `host name`)
	flag.Usage = func() {
		if helpOption {
			flag.CommandLine.SetOutput(os.Stdout)
		}
		fmt.Fprintf(flag.CommandLine.Output(),
			    "Usage: %s [OPTIONS] [HOST...]\n",
			    os.Args[0])
		fmt.Fprintln(flag.CommandLine.Output(), `OPTIONS are:`)
		flag.PrintDefaults()
	}
}

func main() {
	flag.Parse()
	
	if helpOption {
		flag.Usage()
		os.Exit(0)
	}
	
	res := CertResultList{Status: StatusOK}

	if host != `` {
		res.Check(host)
	}

	for _, arg := range flag.Args() {
		res.Check(arg)
	}
	res.Format()
	os.Exit(res.Status)
}

var conf = &tls.Config {
	InsecureSkipVerify: true,
}

func (res CertResult) FormatHR() {
	if res.Status == StatusUnknown {
		fmt.Printf("%s - %s;", res.Address, res.Error)
	} else {
		fmt.Printf("%s[%s] TTL %s;",
			    res.Address, res.Subject, res.Ttl.String())
	}
}
	
func (res CertResult) FormatPerfData() {
	fmt.Printf("%s=%d;%d;%d;;",
		   res.Subject,
		   int(res.Ttl.Seconds()),
	           int(warnLimit.Seconds()),
		   int(critLimit.Seconds()))
}

func (rl CertResultList) Format() {
	//'label'=value[UOM];[warn];[crit];[min];[max]
	fmt.Printf("%s - ", statusString[rl.Status])
	rl.Result[0].FormatHR()
	fmt.Printf(" | ")
	rl.Result[0].FormatPerfData()
	if len(rl.Result) > 1 {
		for _, res := range rl.Result[1:] {
			fmt.Println()
			res.FormatHR()
	        }
		fmt.Printf(`|`)
		for _, res := range rl.Result[1:] {
			res.FormatPerfData()
			fmt.Println()
		}
	} else {
		fmt.Println()
	}
}

func (rl *CertResultList) Append(res CertResult) {
	rl.Result = append(rl.Result, res)
	if res.Status > rl.Status {
		rl.Status = res.Status
	}
}

func (rl *CertResultList) Check(addr string) {
	a := strings.Split(addr, `:`)
	switch (len(a)) {
	case 1:
		addr += `:443`
	case 2:
		break
	default:
		rl.Append(CertResult{Address: addr,
				     Status: StatusUnknown,
		                     Error: `bad address`})
		return
	}

	conn, err := tls.Dial("tcp", addr, conf)
	if err != nil {
		rl.Append(CertResult{Address: addr, Status: StatusUnknown, Error: err.Error()})
		return
	}
	defer conn.Close()

	state := conn.ConnectionState()

	for _, cert := range state.PeerCertificates {
		if cert.IsCA {
			continue
		}
		if !selectCN.Selected(cert) {
			continue
		}
		if (verboseOption) {
			fmt.Printf("Host: %s\n", addr)
			fmt.Printf("CN: %s\n", cert.Subject.CommonName)
			fmt.Printf("DNS: %s\n", strings.Join(cert.DNSNames, `,`))
			fmt.Printf("Expires: %s\n", cert.NotAfter.String())
			fmt.Println()
		}
		res := CertResult{Address: addr,
			          Subject: cert.Subject.CommonName,
			          Status: StatusOK}
		res.Ttl = time.Until(cert.NotAfter)
		if res.Ttl < critLimit {
			res.Status = StatusCritical
		} else if res.Ttl < warnLimit {
			res.Status = StatusWarning
		}
		rl.Append(res)
	}
}

Return to:

Send suggestions and report system problems to the System administrator.