272998f8ccce56e494c949fcca7017fe4fb96251
[dmarc.git] / dmarc_to_database.py
1 #!/usr/bin/python3
2
3 import configparser
4 import imaplib
5 import email
6 import io
7 import zipfile
8 import xml.etree.ElementTree
9 import psycopg2
10 import re
11 import datetime
12
13 def fetch_msg(num):
14 return mailbox.uid('FETCH', num, '(RFC822)')[1][0][1]
15
16 def xml_of_part(part):
17 with zipfile.ZipFile(io.BytesIO(part.get_payload(decode=True))) as zf:
18 fn = zf.infolist()[0].filename
19 contents = zf.read(fn).decode('utf-8')
20 return xml.etree.ElementTree.fromstring(contents)
21
22
23 def xml_of(message):
24 reports = []
25 if message.is_multipart():
26 for p in message.get_payload():
27 if 'zip' in p.get_content_type():
28 reports += [xml_of_part(p)]
29 else:
30 reports = [xml_of_part(message)]
31 return reports
32
33 def extract_report(msg):
34 pmsg = email.message_from_bytes(msg)
35 return xml_of(pmsg)
36
37 def maybe_strip(text):
38 if text:
39 return text.strip()
40 else:
41 return ''
42
43 field_maps = {
44 './policy_published/adkim':
45 {'pg_field_name': 'policy_published_adkim',
46 'pg_table': 'reports', 'pg_type': 'varchar'},
47 './policy_published/aspf':
48 {'pg_field_name': 'policy_published_aspf',
49 'pg_table': 'reports', 'pg_type': 'varchar'},
50 './policy_published/domain':
51 {'pg_field_name': 'policy_published_domain',
52 'pg_table': 'reports', 'pg_type': 'varchar'},
53 './policy_published/p':
54 {'pg_field_name': 'policy_published_p',
55 'pg_table': 'reports', 'pg_type': 'varchar'},
56 './policy_published/pct':
57 {'pg_field_name': 'policy_published_pct',
58 'pg_table': 'reports', 'pg_type': 'int'},
59 './record[{}]/auth_results/dkim/domain':
60 {'pg_field_name': 'auth_results_dkim_domain',
61 'pg_table': 'report_items', 'pg_type': 'varchar'},
62 './record[{}]/auth_results/dkim/result':
63 {'pg_field_name': 'auth_results_dkim_result',
64 'pg_table': 'report_items', 'pg_type': 'varchar'},
65 './record[{}]/auth_results/spf/domain':
66 {'pg_field_name': 'auth_results_spf_domain',
67 'pg_table': 'report_items', 'pg_type': 'varchar'},
68 './record[{}]/auth_results/spf/result':
69 {'pg_field_name': 'auth_results_spf_result',
70 'pg_table': 'report_items', 'pg_type': 'varchar'},
71 './record[{}]/identifiers/header_from':
72 {'pg_field_name': 'identifiers_header_from',
73 'pg_table': 'report_items', 'pg_type': 'varchar'},
74 './record[{}]/row/count':
75 {'pg_field_name': 'count',
76 'pg_table': 'report_items', 'pg_type': 'int'},
77 './record[{}]/row/policy_evaluated/disposition':
78 {'pg_field_name': 'policy_evaluated_disposition',
79 'pg_table': 'report_items', 'pg_type': 'varchar'},
80 './record[{}]/row/policy_evaluated/dkim':
81 {'pg_field_name': 'policy_evaluated_dkim',
82 'pg_table': 'report_items', 'pg_type': 'varchar'},
83 './record[{}]/row/policy_evaluated/spf':
84 {'pg_field_name': 'policy_evaluated_spf',
85 'pg_table': 'report_items', 'pg_type': 'varchar'},
86 './record[{}]/row/source_ip':
87 {'pg_field_name': 'source_ip',
88 'pg_table': 'report_items', 'pg_type': 'inet'},
89 './report_metadata/date_range/begin':
90 {'pg_field_name': 'report_metadata_date_range_begin',
91 'pg_table': 'reports', 'pg_type': 'timestamp'},
92 './report_metadata/date_range/end':
93 {'pg_field_name': 'report_metadata_date_range_end',
94 'pg_table': 'reports', 'pg_type': 'timestamp'},
95 './report_metadata/email':
96 {'pg_field_name': 'report_metadata_email',
97 'pg_table': 'reports', 'pg_type': 'varchar'},
98 './report_metadata/org_name':
99 {'pg_field_name': 'report_metadata_org_name',
100 'pg_table': 'reports', 'pg_type': 'varchar'},
101 './report_metadata/report_id':
102 {'pg_field_name': 'report_metadata_report_id',
103 'pg_table': 'reports', 'pg_type': 'varchar'}}
104
105
106
107 def build_insert_command(table_name, report, preamble_values=None, i=None):
108 field_names = []
109 if preamble_values:
110 values = preamble_values.copy()
111 else:
112 values = {}
113 for f in [f for f in field_maps if field_maps[f]['pg_table'] == table_name]:
114 if i:
115 fp = f.format(i)
116 else:
117 fp = f
118 field_names += [field_maps[f]['pg_field_name']]
119 if field_maps[f]['pg_type'] == 'int':
120 values[field_maps[f]['pg_field_name']] = int(report.find(fp).text)
121 elif field_maps[f]['pg_type'] == 'timestamp':
122 values[field_maps[f]['pg_field_name']] = datetime.datetime.utcfromtimestamp(int(report.find(fp).text))
123 elif field_maps[f]['pg_type'] == 'inet':
124 values[field_maps[f]['pg_field_name']] = maybe_strip(report.find(fp).text)
125 else:
126 values[field_maps[f]['pg_field_name']] = maybe_strip(report.find(fp).text)
127 insert_string = 'insert into {} ('.format(table_name)
128 if preamble_values:
129 insert_string += ', '.join(sorted(preamble_values.keys())) + ', '
130 insert_string += ', '.join(field_names) + ') '
131 insert_string += 'values ('
132 if preamble_values:
133 insert_string += ', '.join('%({})s'.format(fn) for fn in sorted(preamble_values.keys())) + ', '
134 insert_string += ', '.join('%({})s'.format(f) for f in field_names) + ');'
135 return insert_string, values
136
137
138 def write_report(connection, cursor, report):
139 insert_string, values = build_insert_command('reports', report)
140 # print(insert_string, values)
141 cursor.execute(insert_string, values)
142
143 for i in range(1, len(report.findall('./record'))+1):
144 field_names = []
145 cursor.execute('select id, report_metadata_report_id from reports where report_metadata_report_id = %s;',
146 [report.find('./report_metadata/report_id').text])
147 results = cursor.fetchall()
148 if len(results) != 1:
149 raise RuntimeError('Could not find report record for report item')
150 else:
151 report_id = results[0][0]
152 insert_string, values = build_insert_command('report_items', report, i=i,
153 preamble_values={'report_id': report_id})
154 # print(insert_string, values)
155 cursor.execute(insert_string, values)
156 connection.commit()
157
158 config = configparser.ConfigParser()
159 config.read('dmarc.ini')
160
161 conn = psycopg2.connect(host=config['database']['server'],
162 database=config['database']['database'],
163 user=config['database']['username'],
164 password=config['database']['password'])
165
166 cur = conn.cursor()
167 cur.execute('select max(report_metadata_date_range_end) from reports')
168 results = cur.fetchall()
169 most_recent_date = results[0][0]
170
171 mailbox = imaplib.IMAP4(host=config['imap']['server'],
172 port=config['imap']['port'])
173 mailbox.starttls()
174 mailbox.login(config['imap']['username'], config['imap']['password'])
175 mailbox.select('INBOX', readonly=True)
176
177
178 if most_recent_date:
179 mails_from = "SINCE " + (most_recent_date - datetime.timedelta(days=2)).strftime("%d-%b-%Y")
180 else:
181 mails_from = "ALL"
182 resp, nums = mailbox.uid('SEARCH', None, mails_from)
183
184
185 dmarc_reports = [report for report_set in [extract_report(fetch_msg(n)) for n in nums[0].split()]
186 for report in report_set]
187
188 mailbox.close()
189 mailbox.logout()
190
191 for report in dmarc_reports:
192 cur.execute('select id, report_metadata_report_id from reports where report_metadata_report_id = %s;',
193 [report.find('./report_metadata/report_id').text])
194 results = cur.fetchall()
195 if not results:
196 print('write', report.find('./report_metadata/report_id').text)
197 write_report(conn, cur, report)
198
199 conn.close()