-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_smtp
227 lines (198 loc) · 11 KB
/
check_smtp
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
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
import smtplib
import argparse
import sys
import time
import datetime
import socket
import ssl
#-------------------------------------------------------------------------------
_candebug = False
def candebug():
global _candebug
return _candebug
def setcandebug(value):
global _candebug
_candebug = value
def infomsg(msg):
if candebug() == True:
print(msg, flush=True)
def exitnagios(status,message):
if status=="OK":
exitcode = 0
elif status=="WARNING":
exitcode = 1
elif status=="CRITICAL":
exitcode = 2
elif status=="UNKNOWN":
exitcode = 3
else:
exitcode = 4
print(status+": "+message, flush=True)
sys.exit(exitcode)
#-------------------------------------------------------------------------------
original_getaddrinfo = socket.getaddrinfo
def forced_ipv6_gai_family(*args, **kwargs):
global original_getaddrinfo
responses = original_getaddrinfo(*args, **kwargs)
return [response
for response in responses
if response[0] == socket.AF_INET6]
def forced_ipv4_gai_family(*args, **kwargs):
global original_getaddrinfo
responses = original_getaddrinfo(*args, **kwargs)
return [response
for response in responses
if response[0] == socket.AF_INET]
#-------------------------------------------------------------------------------
def dosmtpcheck(protocol,hostname,port,dossl,warning,critical,timeoutvalue,timeoutstatus,certificatedays,relay,blocked,source):
smtpconnection = None
try:
start = datetime.datetime.now(datetime.UTC)
sourcetuple = None
if source!=None:
sourcetuple = (source,0)
#socket.setdefaulttimeout(timeoutvalue)
if dossl==True:
ctx = ssl.create_default_context()
smtpconnection = smtplib.SMTP_SSL(host=hostname,port=port,timeout=timeoutvalue,context=ctx,source_address=sourcetuple)
else:
smtpconnection = smtplib.SMTP(host=hostname,port=port,timeout=timeoutvalue,source_address=sourcetuple)
except socket.error as e:
infomsg("socket error - "+str(e)+" | time=-1 validity=-1")
if blocked==True:
if smtpconnection == None:
exitnagios("OK","the connection is blocked as expected | time=-1 validity=-1")
else:
exitnagios(timeoutstatus,"the connection is responding but it was expected to be blocked | time=-1 validity=-1")
if smtpconnection != None:
certexpirationparsed = None
if dossl==True:
infomsg("doing SSL")
certexpirationraw = None
try:
cert_data = smtpconnection.sock.getpeercert()
infomsg(cert_data)
certexpirationraw = cert_data["notAfter"]
infomsg("Expiry date: "+str(certexpirationraw))
if certexpirationraw != None:
from dateutil.parser import parse
certexpirationparsed = parse(cert_data["notAfter"])
except:
infomsg(str(traceback.format_exc()))
pass
smtpconnection.ehlo_or_helo_if_needed()
response,message = smtpconnection.noop()
# 220 after connection stablished, 250 after EHLO or HELO
infomsg("initial response is "+str(response)+" "+str(message))
if response not in [200,250]:
exitnagios("CRITICAL","initial check, unexpected state - "+str(response)+": "+message.decode()+" | time=-1 validity=-1")
warningmsg= ""
testemailaddress = "[email protected]"
response,message = smtpconnection.docmd("MAIL FROM:",testemailaddress)
infomsg("mailfrom response is "+str(response)+" "+str(message))
if response in [250]:
response,message = smtpconnection.docmd("RCPT TO:",testemailaddress)
infomsg(response)
infomsg(message)
if response in [250,251,354]:
if relay != "open":
exitnagios("CRITICAL","found an open relay "+str(response)+", but it should be closed | time=-1 validity=-1")
elif response in [550]:
if relay != "closed":
exitnagios("CRITICAL","found an closed relay "+str(response)+", but it should be open | time=-1 validity=-1")
warningmsg = "exitstaus "+str(response)+": "+message.decode()
elif response in [555] and relay == "closed":
exitnagios("OK","closed relay with response "+str(response)+" | time=-1 validity=-1")
else:
exitnagios("CRITICAL","sending test, unexpected state - "+str(response)+": "+message.decode()+" | time=-1 validity=-1")
smtpconnection.quit()
elapsed = datetime.datetime.now(datetime.UTC)-start
duration = elapsed.total_seconds()
daysremaining = -1
if duration>=critical:
exitnagios("CRITICAL", "it took "+str(duration)+ " seconds to answer | time="+str(duration)+" validity="+str(daysremaining))
elif duration>=warning:
exitnagios("WARNING", "it took "+str(duration)+ " seconds to answer | time="+str(duration)+" validity="+str(daysremaining))
else:
if dossl==True and certificatedays!="":
if certexpirationparsed==None:
exitnagios("CRITICAL","cannot parse certificate expiration date '"+str(certexpirationraw)+"' | time="+str(duration)+" validity=0")
else:
today = datetime.datetime.now(datetime.UTC)
timeremaining = certexpirationparsed.timestamp()-today.timestamp()
daysremaining = int(timeremaining/86400)
if duration>=critical:
exitnagios("CRITICAL", "it took "+str(duration)+ " seconds to answer | time="+str(duration)+" validity="+str(daysremaining))
elif duration>=warning:
exitnagios("WARNING", "it took "+str(duration)+ " seconds to answer | time="+str(duration)+" validity="+str(daysremaining))
else:
certificatedaysparts = certificatedays.split(",")
criticaldays = int(certificatedaysparts[0])
if len(certificatedaysparts)>1:
warningdays = int(certificatedaysparts[1])
else:
warningdays = -1
if daysremaining>=0 and daysremaining<criticaldays:
exitnagios("CRITICAL","the certificate is expiring in '"+str(daysremaining)+"' days | time="+str(duration)+" validity="+str(daysremaining))
elif daysremaining>=0 and daysremaining<warningdays:
exitnagios("WARNING","the certificate is expiring in '"+str(daysremaining)+"' days | time="+str(duration)+" validity="+str(daysremaining))
else:
exitnagios("OK", "it took "+str(duration)+ " seconds to answer | time="+str(duration)+" validity="+str(daysremaining))
else:
exitnagios("CRITICAL","cannot init SMTP connection | time=-1 validity=-1")
#-------------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-4", "--ipv4", action="store_true", dest="ipv4", default=False, help="use ipv4 (exclusive with ipv6)")
parser.add_argument("-6", "--ipv6", action="store_true", dest="ipv6", default=False, help="use ipv6 (exclusive with ipv4)")
parser.add_argument("-0", "--ipv0", action="store_true", dest="ipv0", default=False, help="do not specify ip protocol version")
parser.add_argument("-H", "--hostname", dest="hostname", default="", help="server to check")
parser.add_argument("-p", "--port", dest="port", default=25, help="port to use, usually 143 or 993")
parser.add_argument("-w", "--warning", dest="warning", default=15, help="warning time (float)")
parser.add_argument("-c", "--critical", dest="critical", default=20, help="critical time (float)")
parser.add_argument("-S", "--ssl", action="store_true", dest="ssl", default=False, help="use ssl")
parser.add_argument("-t", "--timeout", dest="timeout", default="30:CRITICAL", help="timeout value:STATUS")
parser.add_argument("-C", "--certificatedays", dest="certificatedays", default="5,20", help="minimum number of days a certificate has to be valid crit,warn")
parser.add_argument("-r", "--relay", dest="relay", default="closed", help="open or closed relay")
parser.add_argument("-b", "--blocked", action="store_true", dest="blocked", default=False, help="check if the connection is blocked")
parser.add_argument("-u", "--source", dest="source", default="", help="source IP for the connection")
parser.add_argument("-®", "--debug", action="store_true", dest="debug", default=False, help="be more verbose")
args = parser.parse_args()
setcandebug(args.debug)
protocol = None
exclist = 0
if args.ipv0 == True :
protocol = ""
exclist = exclist+1
if args.ipv4 == True :
protocol = "-4"
exclist = exclist+1
socket.getaddrinfo = forced_ipv4_gai_family
if args.ipv6 == True :
protocol = "-6"
exclist = exclist+1
socket.getaddrinfo = forced_ipv6_gai_family
if (exclist>1) :
exitnagios("CRITICAL","select ip protocol version 4 or 6, or 0 to relay on OS handling")
elif (exclist<1) :
exitnagios("CRITICAL","no protocol selected")
if (args.hostname == ""):
exitnagios("CRITICAL","hostname not defined")
source=None
if args.source!="":
source=args.source
parts = args.timeout.split(":")
timeoutvalue = int(parts[0])
if len(parts)>1:
timeoutstatus = parts[1]
else:
timeoutstatus = "CRITICAL"
if timeoutstatus in ["OK", "WARNING", "CRITICAL", "UNKNOWN"]:
dosmtpcheck(protocol,args.hostname,int(args.port),args.ssl,int(args.warning),int(args.critical),timeoutvalue,timeoutstatus,args.certificatedays,args.relay,args.blocked,source)
else:
exitnagios("CRITICAL","timeout status is not valid")
if __name__ == "__main__":
main()
#-------------------------------------------------------------------------------