certexpire

package module
v0.0.0-...-6deaddc Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2021 License: MIT Imports: 22 Imported by: 0

README

# certexpire

certexpire is a tool to check the expiration date (NotAfter) and optionally the hash of x509 certificates.
These certificates can be loaded from file, the standard output of a program, or from the network.
Network protocols supported are direct TLS/SSL connections over TCP, as well as IMAP and SMTP with STARTTLS.

Certificate checks are defined in a configuration file that understand several commands.
Each line defines one command. Lines starting with # are comments.

== 
The standard test command looks like:
  hostname:param:protocol:deadline:<hash>

hostname refers both to network connection hostname as well as owner of certificate.
param refers to the parameter used for this check, it depends on the protocol. Supported protocols are:
  ssl or tls: Direct TLS/SSL connection over TCP. Param must contain the port number.
  imap: STARTTLS for IMAP. Param is the port number.
  smtp: STARTTLS for SMTP. Param is the port number.
  file: Load certificate from a file. Param is the path to the file.
  command: Load certificate from the standard output of a command. Param is the command to run.
deadline is the warning duration before certificate expiration. Understands s/m/d.
hash is optional, and is the sha512 hash of the certificate. Use certexpire with verbosity level 1 or over to
learn the hash.

==
certexpire can send warnings via email. The following line defines the outgoing email settings to use.
  =mailserver:port:from:username:password

mailserver is the SMTP server to connect to, at port.
from is the sender address for all emails.
username and password are used for authentication (only LOGIN is supported).

==
certexpire will send the warnings for checks only if a receiving email address is defined.
Checks apply to the closest previous receiving email address defined.

  @emailaddress

emailaddress is the address to send to.

==
certexpire also supports SOCKS5 connections for its checks. The setting applies to all following checks.

  !proxyaddress

proxyaddress is the hostname:port of a SOCKS5 server.
Set proxyaddress to "direct" to disable a previous proxy configuration.

==
The exit code of certexpire is meaningful. It returns:

 0 if no errors were encountered. Everything is a-okay.
 1 if at least one of the checks failed.
 2 if there was a processing error and a certificate could not be loaded.
 3 is only returned if there are errors in the check configuration file.

==
There are verbose and debug outputs. By default they are both 0 and as a consequence nothing is printed.

Verbosity levels:
  0  Print nothing
  1  Print errors from checks
  2  Print both errors and successes from checks

Debug levels:
  0  Print nothing
  1  Print processing and configuration errors
  2  Print processing and configuration errors as well as status messages

==
The template to generate emails can be changed. The default template is:

----- SNIP -----
From: <{{ .From }}>
To: <{{ .Report.MailTo }}>
Subject: SSL certificates check failed

The following servers have failed the TLS certificate check:
{{ range $e := .Report.Checks }}
{{- if or $e.Error $e.ExecuteError }}
{{ $e.Hostname }}:{{ $e.Param}} ({{$e.Protocol}}): Expires {{ $e.ExpireTime }}
{{ if $e.Error -}} {{- range $err := $e.Error }} ==> {{ $err}} {{- end}} {{- end}} 
{{ if $e.ExecuteError -}} ==> ({{$e.ExecuteError}}) {{- end -}} 
{{- end -}}
{{- end }}

Update ASAP!
----- SNIP -----

Data available for the check result are:
 Hostname,        string: Hostname for connect and certificate ownership.
 Param,           string: The parameter. Depends on protocol.
 Protocol,        string: The protocol (tls, imap, etc).
 Deadline, time.Duration: Warning deadline for expiration.
 Hash,            string: The expected/configured certificate hash.
 ReturnHash,      string: The actual hash returned by the check.
 Error,          []error: List of verification errors.
 ExecuteError,     error: If there was an error on retrieving the certificate.
 ExpireTime,   time.Time: The certificate's NotAfter.



==
Commandline parameters:

  -c string Check configuration file
            Define the file from which to load check configuration. Required.

  -d int    Debug level, max 2 (default 0)
  -v int    Verbosity level, max 2 (default 0)
  -extendend-help  Print the extended help (this!)
    	
  -m string Mail message template file
  			Define the file containing an alternative mail message template.

  -s	    Use check cache (default true)
            Cache duplicate certificate retrieval results.

  -t int    Check execution timeout (default 10)
            Timeout for a check to complete, or fail.

  -w int    Number of concurrent checks (default 10)
            Parallel checks are performed. Define how many may run in parallel.

Documentation

Index

Constants

View Source
const (
	MsgError     = 0
	MsgStatus    = 1
	MsgLogError  = 2
	MsgLogStatus = 3
)

Variables

View Source
var (
	ErrProtocol = errors.New("certexpire: protocol error")
	ErrNoCert   = errors.New("certexpire: no certificate")
	ErrConfig   = errors.New("certexpire: configuration error")
	ErrHash     = errors.New("Hash does not match")
	ErrExpire   = errors.New("Expiration warning")
)

Functions

func ParseDuration

func ParseDuration(s string) (time.Duration, error)

ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

func TCPDailer

func TCPDailer(hostaddr string, proxyaddr *Proxy, timeout time.Duration) (net.Conn, error)

Types

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache caches call results.

func NewCache

func NewCache() *Cache

NewCache creates a new cache.

func (*Cache) Lookup

func (c *Cache) Lookup(key string, factory func() interface{}) chan interface{}

Lookup checks for the cached object. If none is found, the factory will be called. Returns a channel to receive the result from.

type CertValues

type CertValues struct {
	Hostname    string    // Hostname used for retrieval connection.
	Expire      time.Time // Time this certificate expires.
	VerifyError error     // Any TLS  errors when connecting.
	Hash        string    // Hash of the raw certificate.
	Certificate *x509.Certificate
}

CertValues contains the relevant aspects of a certificate.

func GetCert

func GetCert(servername, param, proto string, timeout time.Duration, proxy *Proxy) (*CertValues, error)

GetCert returns the server certificate's expiry time. Proto is tls/ssl, imap, smtp.

func GetCertCMD

func GetCertCMD(servername, command string, timeout time.Duration) (*CertValues, error)

GetCertCMD runs a command and interpretes the standard output as a certificate.

func GetCertFile

func GetCertFile(servername, path string) (*CertValues, error)

GetCertFile verifies a file

func GetCertIMAP

func GetCertIMAP(servername, port string, timeout time.Duration, proxy *Proxy) (*CertValues, error)

GetCertIMAP returns the expiration date of an IMAP STARTTLS cert.

func GetCertSMTP

func GetCertSMTP(servername, port string, timeout time.Duration, proxy *Proxy) (*CertValues, error)

GetCertSMTP returns the expiration date of an SMTP STARTTLS cert.

func GetCertTLS

func GetCertTLS(servername, port string, timeout time.Duration, proxy *Proxy) (*CertValues, error)

GetCertTLS returns the server certificate's expiry time for a TLS server.

func GetCertificate

func GetCertificate(conn net.Conn, hostname string, timeout time.Duration) (*CertValues, error)

GetCertificate returns the server certificate's expiry time. conn is an established connection. hostname is the hostname of the remote server.

type Config

type Config struct {
	Tests []ConfigEntry
	Mail  *SMTPConfig
}

func ParseConfig

func ParseConfig(l string) (*Config, []string, error)

type ConfigEntry

type ConfigEntry struct {
	MailTo    string
	NumChecks int
	Alert     bool
	Checks    []ServerCheck
}

type EmailData

type EmailData struct {
	From   string
	Report ConfigEntry
}

type LineReader

type LineReader struct {
	// contains filtered or unexported fields
}

LineReader helps with dealing with text protocols on the network.

func NewLineReader

func NewLineReader(r io.Reader) *LineReader

NewLineReader returns r as a LineReader

func (LineReader) Line

func (lr LineReader) Line() ([]byte, error)

Line returns the next newline terminated line.

func (LineReader) ReadNumeric

func (lr LineReader) ReadNumeric() (code, message string, cont bool, err error)

ReadNumeric reads SMTP-like text protocol lines. Code contains the numeric code, if any. message contains the remainder of the line. cont signals if more lines should be read.

func (LineReader) ReadNumericContinuous

func (lr LineReader) ReadNumericContinuous() (code string, messages []string, err error)

ReadNumericContinuous continues to read until the server expects a message.

type LogLine

type LogLine struct {
	MsgType int
	Message string
}

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

func NewLogger

func NewLogger(debug, verbose int) *Logger

func (*Logger) Log

func (l *Logger) Log(msgType int, msg string)

func (*Logger) Stop

func (l *Logger) Stop() int

type Proxy

type Proxy struct {
	Server string
}

func ParseProxyLine

func ParseProxyLine(l string) *Proxy

type Report

type Report struct {
	Workers      int
	Timeout      time.Duration
	UseCache     bool
	Logger       *Logger
	MailTemplate []byte

	MailHostname string
	MailPort     string
	MailFrom     string
	MailUsername string
	MailPassword string
	// contains filtered or unexported fields
}

func (*Report) Error

func (rep *Report) Error(err string)

func (*Report) Generate

func (rep *Report) Generate(config *Config)

func (*Report) GetCert

func (rep *Report) GetCert(servername, port, proto string, timeout time.Duration, proxy *Proxy) (*CertValues, error)

func (*Report) LogError

func (rep *Report) LogError(sc *ServerCheck)

func (*Report) LogStatus

func (rep *Report) LogStatus(sc *ServerCheck)

func (*Report) SendReport

func (rep *Report) SendReport(ce ConfigEntry)

func (*Report) Status

func (rep *Report) Status(s string)

func (*Report) VerifyCert

func (rep *Report) VerifyCert(sc *ServerCheck, timeout time.Duration) error

type SMTPConfig

type SMTPConfig struct {
	Hostname string
	Port     string
	From     string
	Username string
	Password string
}

func ParseSMTPLine

func ParseSMTPLine(l string) (*SMTPConfig, error)

func (*SMTPConfig) Copy

func (sc *SMTPConfig) Copy() *SMTPConfig

type ServerCheck

type ServerCheck struct {
	Hostname     string
	Param        string
	Protocol     string
	Deadline     time.Duration
	Hash         string
	ReturnHash   string
	Error        []error
	ExecuteError error
	ExpireTime   time.Time
	Proxy        *Proxy
	KeyS, KeyC   int // used internally
}

func ParseServerLine

func ParseServerLine(l string) (*ServerCheck, error)

func (ServerCheck) Copy

func (sc ServerCheck) Copy() ServerCheck

Directories

Path Synopsis
cmd
wcex/stringduration
Package stringduration extends formatting for durations as strings.
Package stringduration extends formatting for durations as strings.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL