aboutsummaryrefslogtreecommitdiff
path: root/certmon.go
blob: d76e44b938eb806f4f08d861a2823b743dc7ac34 (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
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
// This file is part of certmon -*- go -*-
// Copyright (C) 2019 Sergey Poznyakoff
//
// Certmon is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, or (at your option)
// any later version.
//
// Certmon is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with certmon.  If not, see <http://www.gnu.org/licenses/>.

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 {
	Subject string
	Status int
	Ttl time.Duration
	Error string
}

type CertResultList struct {
	Address string
	Status int
	Result []CertResult
}

func CNMatch(pat, name string) bool {
	pat = strings.ToLower(pat)
	if (pat[0] == '*') {
		return len(name) >= len(pat) &&
			strings.HasSuffix(name, pat[1:]) &&
			strings.Index(name[0:(len(name) - len(pat) + 1)], `.`) == -1
	} else {
		return pat == name
	}
}

func CertMatch(cert *x509.Certificate, cn string) bool {
	if cn == `` || CNMatch(cert.Subject.CommonName, cn) {
		return true
	}
	for _, name := range cert.DNSNames {
		if CNMatch(name, cn) {
			return true
		}
	}
	return false
}

// Argument list
type ArgList struct {
	args []string
}

func NewArgList(a []string) *ArgList {
	var args ArgList
	if len(a) > 0 {
		args.args = a
	} else {
		args.args = []string{``}
	}
	return &args
}

func (a *ArgList) Next() (string) {
	s := a.args[0]
	a.args = a.args[1:]
	return s
}

func (a *ArgList) DropMatches(cert *x509.Certificate) {
	for i := 0; i < len(a.args); {
		if CertMatch(cert, a.args[i]) {
			a.args = append(a.args[:i], a.args[i+1:]...)
		} else {
			i++
		}
	}
}

func (a *ArgList) More() bool {
	return len(a.args) > 0
}

// Command line options
var warnLimit time.Duration
var critLimit time.Duration
var verboseOption bool
var helpOption bool
var quietOption bool
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.StringVar(&host, `H`, ``, `host name`)
	flag.BoolVar(&quietOption, `q`, false, `quiet mode: print nothing, exit with a meaningful status`)
	flag.Usage = func() {
		if helpOption {
			flag.CommandLine.SetOutput(os.Stdout)
		}
		fmt.Fprintf(flag.CommandLine.Output(),
			    "Usage: %s [OPTIONS] [CN...]\n",
			    os.Args[0])
		fmt.Fprintln(flag.CommandLine.Output(), `OPTIONS are:`)
		flag.PrintDefaults()
	}
}

func main() {
	flag.Parse()
	
	if helpOption {
		flag.Usage()
		os.Exit(0)
	}
	if host == `` {
		fmt.Fprintf(os.Stderr, "-H option is mandatory\n")
		flag.Usage()
		os.Exit(2)
	}
	
	res := CertResultList{Address: host, Status: StatusOK}

	for args := NewArgList(flag.Args()); args.More(); {
		res.Check(args)
	}
	if !quietOption {
		res.Format()
	}
	os.Exit(res.Status)
}

func (res CertResult) FormatHR() {
	if res.Status == StatusUnknown {
		fmt.Printf("%s - %s;", res.Subject, res.Error)
	} else {
		fmt.Printf("%s TTL %s;", 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() {
	// For details about Nagios plugin output format, refer to:
	//   https://assets.nagios.com/downloads/nagioscore/docs/nagioscore/4/en/pluginapi.html
	// and
	//   https://nagios-plugins.org/doc/guidelines.html
	// In particular, performance data format is:
	//   'label'=value[UOM];[warn];[crit];[min];[max]
	fmt.Printf("%s - %s ", statusString[rl.Status], rl.Address)
	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(args *ArgList) {
	cn := strings.ToLower(args.Next())
	addr := rl.Address;
	a := strings.Split(addr, `:`)
	switch (len(a)) {
	case 1:
		addr += `:443`
	case 2:
		break
	default:
		rl.Append(CertResult{Status: StatusUnknown,
		                     Error: `bad address`})
		return
	}

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

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

	state := conn.ConnectionState()

	for _, cert := range state.PeerCertificates {
		if cert.IsCA {
			continue
		}
		if cn == `` {
			cn = cert.Subject.CommonName
		}
		if !CertMatch(cert, cn) {
			continue
		}
		args.DropMatches(cert)
		res := CertResult{Subject: cn, 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)
		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.Printf("Status: %s\n", statusString[res.Status])
			fmt.Println()
		}
		return
	}
	rl.Append(CertResult{Status: StatusUnknown,
		             Subject: cn,
                             Error: `No such CN`})
}

Return to:

Send suggestions and report system problems to the System administrator.