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 import asyncio
34 import aiodns
35 import base64
36 import dkim
37 import re
38
39 __all__ = [
40 'get_txt_async',
41 'load_pk_from_dns_async',
42 'verify_async'
43 ]
44
45
47 """Return a TXT record associated with a DNS name in an asnyc loop. For
48 DKIM we can assume there is only one."""
49
50
51 loop = asyncio.get_event_loop()
52 resolver = aiodns.DNSResolver(loop=loop, timeout=timeout)
53
54 async def query(name, qtype):
55 return await resolver.query(name, qtype)
56
57
58 try:
59 result = await query(name, 'TXT')
60 except aiodns.error.DNSError:
61 result = None
62
63 if result:
64 return result[0].text
65 else:
66 return None
67
68
73
74 -class DKIM(dkim.DKIM):
75
76
77
78
79
80
81
82
83
84
85 - async def verify_sig(self, sig, include_headers, sig_header, dnsfunc):
86 name = sig[b's'] + b"._domainkey." + sig[b'd'] + b"."
87 try:
88 self.pk, self.keysize, self.ktag, self.seqtlsrpt = await load_pk_from_dns_async(name,
89 dnsfunc, timeout=self.timeout)
90 except dkim.KeyFormatError as e:
91 self.logger.error("%s" % e)
92 return False
93 return self.verify_sig_process(sig, include_headers, sig_header, dnsfunc)
94
95
96 - async def verify(self,idx=0,dnsfunc=get_txt_async):
99
100
101 -async def verify_async(message, logger=None, dnsfunc=None, minkey=1024,
102 timeout=5, tlsrpt=False):
103 """Verify the first (topmost) DKIM signature on an RFC822 formatted message in an asyncio contxt.
104 @param message: an RFC822 formatted message (with either \\n or \\r\\n line endings)
105 @param logger: a logger to which debug info will be written (default None)
106 @param timeout: number of seconds for DNS lookup timeout (default = 5)
107 @param tlsrpt: message is an RFC 8460 TLS report (default False)
108 False: Not a tlsrpt, True: Is a tlsrpt, 'strict': tlsrpt, invalid if
109 service type is missing. For signing, if True, length is never used.
110 @return: True if signature verifies or False otherwise
111 """
112
113
114 loop = asyncio.get_event_loop()
115 if not dnsfunc:
116 dnsfunc=get_txt_async
117 d = DKIM(message,logger=logger,minkey=minkey,timeout=timeout,tlsrpt=tlsrpt)
118 try:
119 return await d.verify(dnsfunc=dnsfunc)
120 except dkim.DKIMException as x:
121 if logger is not None:
122 logger.error("%s" % x)
123 return False
124