Debian Codegraph @

lualib/lua_auth_results.lua

raw
1 --[[
2 Copyright (c) 2016, Andrew Lewis <[email protected]>
3 Copyright (c) 2022, Vsevolod Stakhov <[email protected]>
4
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16 ]]--
17
18 local rspamd_util = require "rspamd_util"
19 local lua_util = require "lua_util"
20
21 local default_settings = {
22 spf_symbols = {
23 pass = 'R_SPF_ALLOW',
24 fail = 'R_SPF_FAIL',
25 softfail = 'R_SPF_SOFTFAIL',
26 neutral = 'R_SPF_NEUTRAL',
27 temperror = 'R_SPF_DNSFAIL',
28 none = 'R_SPF_NA',
29 permerror = 'R_SPF_PERMFAIL',
30 },
31 dmarc_symbols = {
32 pass = 'DMARC_POLICY_ALLOW',
33 permerror = 'DMARC_BAD_POLICY',
34 temperror = 'DMARC_DNSFAIL',
35 none = 'DMARC_NA',
36 reject = 'DMARC_POLICY_REJECT',
37 softfail = 'DMARC_POLICY_SOFTFAIL',
38 quarantine = 'DMARC_POLICY_QUARANTINE',
39 },
40 arc_symbols = {
41 pass = 'ARC_ALLOW',
42 permerror = 'ARC_INVALID',
43 temperror = 'ARC_DNSFAIL',
44 none = 'ARC_NA',
45 reject = 'ARC_REJECT',
46 },
47 dkim_symbols = {
48 none = 'R_DKIM_NA',
49 },
50 add_smtp_user = true,
51 }
52
53 local exports = {
54 default_settings = default_settings
55 }
56
57 local local_hostname = rspamd_util.get_hostname()
58
59 local function gen_auth_results(task, settings)
60 local auth_results, hdr_parts = {}, {}
61
62 if not settings then
63 settings = default_settings
64 end
65
66 local auth_types = {
67 dkim = settings.dkim_symbols,
68 dmarc = settings.dmarc_symbols,
69 spf = settings.spf_symbols,
70 arc = settings.arc_symbols,
71 }
72
73 local common = {
74 symbols = {}
75 }
76
77 local mta_hostname = task:get_request_header('MTA-Name') or
78 task:get_request_header('MTA-Tag')
79 if mta_hostname then
80 mta_hostname = tostring(mta_hostname)
81 else
82 mta_hostname = local_hostname
83 end
84
85 table.insert(hdr_parts, mta_hostname)
86
87 for auth_type, symbols in pairs(auth_types) do
88 for key, sym in pairs(symbols) do
89 if not common.symbols.sym then
90 local s = task:get_symbol(sym)
91 if not s then
92 common.symbols[sym] = false
93 else
94 common.symbols[sym] = s
95 if not auth_results[auth_type] then
96 auth_results[auth_type] = { key }
97 else
98 table.insert(auth_results[auth_type], key)
99 end
100
101 if auth_type ~= 'dkim' then
102 break
103 end
104 end
105 end
106 end
107 end
108
109 local dkim_results = task:get_dkim_results()
110 -- For each signature we set authentication results
111 -- dkim=neutral (body hash did not verify) header.d=example.com header.s=sel header.b=fA8VVvJ8;
112 -- dkim=neutral (body hash did not verify) header.d=example.com header.s=sel header.b=f8pM8o90;
113
114 for _, dres in ipairs(dkim_results) do
115 local ar_string = 'none'
116
117 if dres.result == 'reject' then
118 ar_string = 'fail' -- imply failure, not neutral
119 elseif dres.result == 'allow' then
120 ar_string = 'pass'
121 elseif dres.result == 'bad record' or dres.result == 'permerror' then
122 ar_string = 'permerror'
123 elseif dres.result == 'tempfail' then
124 ar_string = 'temperror'
125 end
126 local hdr = {}
127
128 hdr[1] = string.format('dkim=%s', ar_string)
129
130 if dres.fail_reason then
131 hdr[#hdr + 1] = string.format('(%s)', lua_util.maybe_smtp_quote_value(dres.fail_reason))
132 end
133
134 if dres.domain then
135 hdr[#hdr + 1] = string.format('header.d=%s', lua_util.maybe_smtp_quote_value(dres.domain))
136 end
137
138 if dres.selector then
139 hdr[#hdr + 1] = string.format('header.s=%s', lua_util.maybe_smtp_quote_value(dres.selector))
140 end
141
142 if dres.bhash then
143 hdr[#hdr + 1] = string.format('header.b=%s', lua_util.maybe_smtp_quote_value(dres.bhash))
144 end
145
146 table.insert(hdr_parts, table.concat(hdr, ' '))
147 end
148
149 if #dkim_results == 0 then
150 -- We have no dkim results, so check for DKIM_NA symbol
151 if common.symbols[settings.dkim_symbols.none] then
152 table.insert(hdr_parts, 'dkim=none')
153 end
154 end
155
156 for auth_type, keys in pairs(auth_results) do
157 for _, key in ipairs(keys) do
158 local hdr = ''
159 if auth_type == 'dmarc' then
160 local opts = common.symbols[auth_types['dmarc'][key]][1]['options'] or {}
161 hdr = hdr .. 'dmarc='
162 if key == 'reject' or key == 'quarantine' or key == 'softfail' then
163 hdr = hdr .. 'fail'
164 else
165 hdr = hdr .. lua_util.maybe_smtp_quote_value(key)
166 end
167 if key == 'pass' then
168 hdr = hdr .. ' (policy=' .. lua_util.maybe_smtp_quote_value(opts[2]) .. ')'
169 hdr = hdr .. ' header.from=' .. lua_util.maybe_smtp_quote_value(opts[1])
170 elseif key ~= 'none' then
171 local t = { opts[1]:match('^([^%s]+) : (.*)$') }
172 if #t > 0 then
173 local dom = t[1]
174 local rsn = t[2]
175 if rsn then
176 hdr = string.format('%s reason=%s', hdr, lua_util.maybe_smtp_quote_value(rsn))
177 end
178 hdr = string.format('%s header.from=%s', hdr, lua_util.maybe_smtp_quote_value(dom))
179 end
180 if key == 'softfail' then
181 hdr = hdr .. ' (policy=none)'
182 else
183 hdr = hdr .. ' (policy=' .. lua_util.maybe_smtp_quote_value(key) .. ')'
184 end
185 end
186 table.insert(hdr_parts, hdr)
187 elseif auth_type == 'arc' then
188 if common.symbols[auth_types['arc'][key]][1] then
189 local opts = common.symbols[auth_types['arc'][key]][1]['options'] or {}
190 for _, v in ipairs(opts) do
191 hdr = string.format('%s%s=%s (%s)', hdr, auth_type,
192 lua_util.maybe_smtp_quote_value(key), lua_util.maybe_smtp_quote_value(v))
193 table.insert(hdr_parts, hdr)
194 end
195 end
196 elseif auth_type == 'spf' then
197 -- Main type
198 local sender
199 local sender_type
200 local smtp_from = task:get_from({ 'smtp', 'orig' })
201
202 if smtp_from and
203 smtp_from[1] and
204 smtp_from[1]['addr'] ~= '' and
205 smtp_from[1]['addr'] ~= nil then
206 sender = lua_util.maybe_smtp_quote_value(smtp_from[1]['addr'])
207 sender_type = 'smtp.mailfrom'
208 else
209 local helo = task:get_helo()
210 if helo then
211 sender = lua_util.maybe_smtp_quote_value(helo)
212 sender_type = 'smtp.helo'
213 end
214 end
215
216 if sender and sender_type then
217 -- Comment line
218 local comment = ''
219 if key == 'pass' then
220 comment = string.format('%s: domain of %s designates %s as permitted sender',
221 mta_hostname, sender, tostring(task:get_from_ip() or 'unknown'))
222 elseif key == 'fail' then
223 comment = string.format('%s: domain of %s does not designate %s as permitted sender',
224 mta_hostname, sender, tostring(task:get_from_ip() or 'unknown'))
225 elseif key == 'neutral' or key == 'softfail' then
226 comment = string.format('%s: %s is neither permitted nor denied by domain of %s',
227 mta_hostname, tostring(task:get_from_ip() or 'unknown'), sender)
228 elseif key == 'permerror' then
229 comment = string.format('%s: domain of %s uses mechanism not recognized by this client',
230 mta_hostname, sender)
231 elseif key == 'temperror' then
232 comment = string.format('%s: error in processing during lookup of %s: DNS error',
233 mta_hostname, sender)
234 elseif key == 'none' then
235 comment = string.format('%s: domain of %s has no SPF policy when checking %s',
236 mta_hostname, sender, tostring(task:get_from_ip() or 'unknown'))
237 end
238 hdr = string.format('%s=%s (%s) %s=%s', auth_type, key,
239 comment, sender_type, sender)
240 else
241 hdr = string.format('%s=%s', auth_type, key)
242 end
243
244 table.insert(hdr_parts, hdr)
245 end
246 end
247 end
248
249 local u = task:get_user()
250 local smtp_from = task:get_from({ 'smtp', 'orig' })
251
252 if u and smtp_from then
253 local hdr = { [1] = 'auth=pass' }
254
255 if settings['add_smtp_user'] then
256 table.insert(hdr, 'smtp.auth=' .. lua_util.maybe_smtp_quote_value(u))
257 end
258 if smtp_from[1]['addr'] then
259 table.insert(hdr, 'smtp.mailfrom=' .. lua_util.maybe_smtp_quote_value(smtp_from[1]['addr']))
260 end
261
262 table.insert(hdr_parts, table.concat(hdr, ' '))
263 end
264
265 if #hdr_parts > 0 then
266 if #hdr_parts == 1 then
267 hdr_parts[2] = 'none'
268 end
269 return table.concat(hdr_parts, '; ')
270 end
271
272 return nil
273 end
274
275 exports.gen_auth_results = gen_auth_results
276
277 -- Shared LPeg primitives for AR/AAR parsing (built once on first use)
278 local ar_lpeg_atoms
279
280 local function get_ar_lpeg_atoms()
281 if ar_lpeg_atoms then
282 return ar_lpeg_atoms
283 end
284
285 local lpeg = require "lpeg"
286 local P, S, V, C, Ct, Cg, Cf = lpeg.P, lpeg.S, lpeg.V, lpeg.C, lpeg.Ct, lpeg.Cg, lpeg.Cf
287
288 local space = S(" \t") ^ 0
289 local doublequoted = space * P '"' * ((1 - S '"\r\n\f\\') + (P '\\' * 1)) ^ 0 * '"' * space
290 local comment = space * P { "(" * ((1 - S "()") + V(1)) ^ 0 * ")" } * space
291 local name = C((1 - S('=(" \t')) ^ 1) * space
292 local pair = Cg(name * "=" * space * name) * space
293
294 -- Single AR element grammar: "dkim=pass (comment) header.d=example.com" → table
295 local elt_grammar = Cf(Ct("") * (pair + comment + doublequoted) ^ 1, rawset)
296
297 -- AAR header split grammar: splits on ";" while respecting comments and quotes.
298 -- Each captured element is the raw text between semicolons (trimmed).
299 local safe_char = (comment + doublequoted + (1 - S ";")) -- consume one "safe" token
300 local element = C(safe_char ^ 1) -- capture the raw text of one element
301 local sep = P ";" * space
302 local aar_split_grammar = Ct(space * element * (sep * element) ^ 0)
303
304 ar_lpeg_atoms = {
305 elt_grammar = elt_grammar,
306 aar_split_grammar = aar_split_grammar,
307 }
308 return ar_lpeg_atoms
309 end
310
311 -- Parse a single AR element (e.g. "dkim=pass header.d=example.com") into a kv table
312 local function parse_ar_element(elt)
313 return get_ar_lpeg_atoms().elt_grammar:match(elt)
314 end
315 exports.parse_ar_element = parse_ar_element
316
317 -- Split an AAR header value into elements by ";" while respecting comments and
318 -- quoted strings, then parse each element. Returns { i = <number>,
319 -- ar = { {method=result, ...}, ... } } or nil on failure.
320 local function parse_aar_header(decoded)
321 local atoms = get_ar_lpeg_atoms()
322 local elts = atoms.aar_split_grammar:match(decoded)
323 if not elts or #elts == 0 then
324 return nil
325 end
326
327 local result = {}
328
329 for _, raw_elt in ipairs(elts) do
330 local trimmed = raw_elt:match("^%s*(.-)%s*$")
331 if trimmed and #trimmed > 0 and trimmed:match("^i%s*=%s*%d+$") then
332 -- ARC instance tag
333 local v = trimmed:match("^i%s*=%s*(%d+)$")
334 result.i = v
335 else
336 -- Try to parse as an AR element (method=result prop=value ...)
337 local ar_elt = atoms.elt_grammar:match(trimmed)
338 if ar_elt then
339 if not result.ar then
340 result.ar = {}
341 end
342 table.insert(result.ar, ar_elt)
343 end
344 -- Elements without '=' (like authserv-id) are silently skipped
345 end
346 end
347
348 return result
349 end
350 exports.parse_aar_header = parse_aar_header
351
352 local function get_ar_hostname(ar_value)
353 if not ar_value or ar_value == '' then
354 return nil
355 end
356
357 local hostname = ar_value:match('^%s*([^;%s%(]+)')
358
359 if hostname then
360 return hostname:lower()
361 end
362
363 return nil
364 end
365 exports.get_ar_hostname = get_ar_hostname
366
367 return exports