-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtestmx.py
executable file
·228 lines (196 loc) · 7.61 KB
/
testmx.py
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
#!/usr/bin/env python3
# test MXes
# thread version
# Copyright 2019-2020 Standcore LLC
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import dns.resolver
import argparse
import sys
import pymysql
import concurrent.futures
import socket
import struct
import smtplib
# eai dict indexed by MX addr
# contains (ndoms, name, okeai, ok8bit)
dolist = []
eai = dict()
oldtld = None
clientaddr = None
timeout = 30
replace = False
mx = dict() # mx'es we've already tested
dbmx = None # mx'es from the database
parallel = None
def process(f):
"""
process file of the form
domain exchange v4address
"""
global oldtld, eai, dolist, mx, dbmx
for l in f:
if l.startswith('###'): # end of tld
if dolist:
testmx()
if eai:
putaway(replace)
eai = dict()
print("end", oldtld)
oldtld = None
continue
(dom, exch, addr) = l.split()[:3]
#print(dom,addr)
if dom[-1] == '.':
dom = dom[:-1]
if "." not in dom:
print("mystery domain",dom)
continue
tld = dom.rsplit('.', maxsplit=1)[1].lower()
if tld != oldtld:
if dolist:
testmx()
if eai:
putaway(replace)
eai = dict()
oldtld = tld
print("start", oldtld)
if addr in eai:
eai[addr][0] += 1
continue
if addr in mx:
eai[addr] = [1, exch ] + mx[addr]
continue
if dbmx and addr in dbmx:
eai[addr] = [1, exch ] + dbmx[addr]
print(addr,exch,"from db")
continue
# need to test this one
eai[addr] = [ 1, exch ]
dolist.append(addr)
if len(dolist) >= parallel:
testmx()
mtas = (b"Postfix", b"Sendmail", b"Exim", b"MailSite", b"protection.outlook", b"Microsoft", b"gsmtp",
b"Haraka", b"Nemesis", b"Amazon SES", b"bizsmtp", b"MailEnable", b"MDaemon", b"CommuniGate",
b"hostedemail", b"yahoo.com")
def tmx1(addr):
""" test one MX in thread
"""
#print("test", addr)
if addr in ("0.0.0.0", "1.1.1.1", "127.0.0.1"):
return (addr, False, False, "Noaddr")
try:
if clientaddr:
sess = smtplib.SMTP(timeout=timeout, source_address=(clientaddr, 0))
else:
sess = smtplib.SMTP(timeout=timeout)
if not sess:
return (addr, False, False, "Norej")
ms = sess.connect(addr);
if ms[0] != 220:
print("bad greet",ms)
return (addr, False, False, "Nogreet")
s = sess.ehlo()
sess.quit()
if s[0] != 250:
print("bad ehlo",s)
return (addr, False, False, "Nohelo")
# mta signature
print("mta sig is", ms[1])
mta = None
for mm in mtas:
if mm in ms[1]:
mta = mm
#print("it is",mta)
break
#print("text is",s[1])
r = (addr, b"SMTPUTF8" in s[1], b"8BITMIME" in s[1], mta)
print("return",r)
return r
except (OSError, PermissionError, socket.timeout, TimeoutError, smtplib.SMTPServerDisconnected, ConnectionRefusedError):
print("fail",addr)
return (addr, False, False, "Noconn")
def testmx():
"""
test all the MTAs in dolist
"""
global dolist, mx
print("test", oldtld, len(dolist))
fl = []
with concurrent.futures.ThreadPoolExecutor(max_workers=parallel) as tex:
for d in dolist:
fl.append(tex.submit(tmx1, d))
for future in concurrent.futures.as_completed(fl):
try:
r = future.result()
if r:
(addr,okeai,ok8bit,mtasw) = r
#print(addr, okeai, ok8bit,mtasw)
oldr = eai[addr]
eai[addr] = oldr[:2] + list(r[1:])
mx[addr] = list(r[1:])
except Exception as exc:
print("thread barf", exc, file=sys.stderr)
dolist = []
def putaway(replace=False):
"""
store everything in eai
as tld oldtld
"""
global eai,oldtld
def aton(s):
""" ipv4 to unsigned int """
return struct.unpack(">I", socket.inet_aton(s))[0]
db = pymysql.connect(user='eaimail',password='x',db='eaimail')
ex = [ [oldtld, aton(a)]+i for (a,i) in eai.items() if len(i) == 5]
print("to database",ex)
with db.cursor() as cur:
if replace:
cur.execute("""DELETE FROM eaimail WHERE tld=%s""", (oldtld,))
cur.executemany("""REPLACE INTO eaimail(tld, mxip, ndomain, mx, neai,n8bit,mtasw,scandate)
values(%s,%s,%s,%s,%s,%s,%s,DATE(NOW()))""",
ex)
db.commit()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='check whether MX is EAI')
parser.add_argument('--par', type=int, help="Do this many in parallel (default 10)");
parser.add_argument('--timeout', type=int, help="connection timeout (default 30)");
parser.add_argument('--addr', type=str, help="IP client address");
parser.add_argument('--replace', action='store_true', help="replace current DB entries");
parser.add_argument('--dbmx', action='store_true', help="use MX info from existing database");
parser.add_argument('domains', type=str, nargs='*', help="domain exch addr aaaaddr");
args = parser.parse_args();
parallel = args.par or 10
clientaddr = args.addr
timeout = args.timeout or 30
replace = args.replace
if args.dbmx:
db = pymysql.connect(host='g4.iecc.com',user='eaimail',password='x',db='eaimail')
with db.cursor() as cur:
r = cur.execute("""SELECT inet_ntoa(mxip),neai,n8bit,mtasw FROM eaimail GROUP BY mxip""")
dbmx = { m[0]: [ bool(m[1]), bool(m[2]), m[3] ] for m in cur.fetchall() }
print("fetched {} mx from db".format(len(dbmx)))
eai = dict()
if args.domains:
for zf in args.domains:
try:
if '.gz' in zf:
f = gzip.open(zf, 'r')
else:
f = open(zf, 'r')
except FileNotFoundError:
print("Cannot open file", zf)
continue
process(f)
f.close()
else:
process(sys.stdin)
if dolist:
testmx()
if eai:
putaway(replace)