aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/lua/greylist.lua
blob: 1493ad96fdf3a5f759238053c11f92b226707703 (plain)
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
--[[
Copyright (c) 2016, Vsevolod Stakhov <vsevolod@highsecure.ru>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--

-- A plugin that implements greylisting using redis

-- Default port for redis upstreams
local default_port = 6379
local upstreams
local whitelisted_ip
local settings = {
  expire = 86400, -- 1 day by default
  timeout = 300, -- 5 minutes by default
  key_prefix = 'rg', -- default hash name
  max_data_len = 10240, -- default data limit to hash
  message = 'Try again later', -- default greylisted message
  symbol = 'GREYLIST',
  ipv4_mask = 19, -- Mask bits for ipv4
  ipv6_mask = 64, -- Mask bits for ipv6
}

local rspamd_logger = require "rspamd_logger"
local rspamd_redis = require "rspamd_redis"
local upstream_list = require "rspamd_upstream_list"
local rspamd_util = require "rspamd_util"
local fun = require "fun"
local rspamd_cryptobox = require "rspamd_cryptobox"
local hash = require "rspamd_cryptobox_hash"

local function data_key(task)
  local cached = task:get_mempool():get_variable("grey_bodyhash")
  if cached then
    return cached
  end

  local body = task:get_rawbody()

  if not body then return nil end

  local len = body:len()
  if len > settings['max_data_len'] then
    len = settings['max_data_len']
  end

  local h = hash.create()
  h:update(body, len)

  local b32 = settings['key_prefix'] .. 'b' .. h:base32():sub(1, 20)
  task:get_mempool():set_variable("grey_bodyhash", b32)
  return b32
end

local function envelope_key(task)
  local cached = task:get_mempool():get_variable("grey_metahash")
  if cached then
    return cached
  end

  local from = task:get_from('smtp')
  local h = hash.create()

  local addr = '<>'
  if from and from[1] then
    addr = from[1]['addr']
  end

  h:update(addr)
  local rcpt = task:get_recipients('smtp')
  if rcpt then
    table.sort(rcpt, function(r1, r2)
      return r1['addr'] < r2['addr']
    end)

    fun.each(function(r)
      h:update(r['addr'])
    end, rcpt)
  end

  local ip = task:get_from_ip()

  if ip and ip:is_valid() then
    local s
    if ip:get_version() == 4 then
      s = tostring(ip:apply_mask(settings['ipv4_mask']))
    else
      s = tostring(ip:apply_mask(settings['ipv6_mask']))
    end
    h:update(s)
  end

  local b32 = settings['key_prefix'] .. 'm' .. h:base32():sub(1, 20)
  task:get_mempool():set_variable("grey_metahash", b32)
  return b32
end

-- Returns pair of booleans: found,greylisted
local function check_time(task, tm, type)
  local t = tonumber(tm)

  if not t then
    rspamd_logger.infox(task, 'not a valid number: %s', tm)
    return false,false
  end

  local now = rspamd_util.get_time()
  if now - t < settings['timeout'] then
    return true,true
  else
    -- We just set variable to pass when in post-filter stage
    task:get_mempool():set_variable("grey_whitelisted", type)

    return true,false
  end

  return false,false
end

local function greylist_check(task)
  local body_key = data_key(task)
  local meta_key = envelope_key(task)
  local upstream = upstreams:get_upstream_by_hash(body_key .. meta_key)
  local addr = upstream:get_addr()

  local function redis_get_cb(task, err, data)
    local ret_body = false
    local greylisted_body = false
    local ret_meta = false
    local greylisted_meta = false
    local time
    local greylist_type

    if data then
      if data[1] and type(data[1]) ~= 'userdata' then
        ret_body,greylisted_body = check_time(task, data[1], 'body')
        if greylisted_body then
          local end_time = rspamd_util.time_to_string(rspamd_util.get_time()
            + settings['timeout'])
          task:get_mempool():set_variable("grey_greylisted_body", end_time)
        end
      end
      if data[2] and type(data[2]) ~= 'userdata' then
        if not ret_body or greylisted_body then
          ret_meta,greylisted_meta = check_time(task, data[2], 'meta')

          if greylisted_meta then
            local end_time = rspamd_util.time_to_string(rspamd_util.get_time()
               + settings['timeout'])
            task:get_mempool():set_variable("grey_greylisted_meta", end_time)
          end
        end
      end
      upstream:ok()

      if not ret_body and not ret_meta then
        local t = tostring(math.floor(rspamd_util.get_time()))
        local end_time = rspamd_util.time_to_string(t + settings['timeout'])
        rspamd_logger.infox(task, 'greylisted till "%s", new record', end_time)
        task:insert_result(settings['symbol'], 0.0, 'greylisted', end_time,
          'new record')
        task:set_pre_result('soft reject', settings['message'])
        -- Create new record
        if addr then
          local conn = rspamd_redis.connect({
            task = task,
            host = addr
          })

          if conn then
            conn:add_cmd('SETEX', {
              body_key, tostring(settings['expire']), t
            })
            conn:add_cmd('SETEX', {
              meta_key, tostring(settings['expire']), t
            })
            local end_time = rspamd_util.time_to_string(rspamd_util.get_time()
               + settings['timeout'])
            task:get_mempool():set_variable("grey_greylisted", end_time)
          else
            rspamd_logger.infox(task, 'got error while connecting to redis: %1', addr)
            upstream:fail()
          end
        elseif greylisted_body and greylisted_meta then
          local end_time = rspamd_util.time_to_string(time + settings['timeout'])
          rspamd_logger.infox(task, 'greylisted till "%s" using %s key',
            end_time, type)
          task:insert_result(settings['symbol'], 0.0, 'greylisted', end_time,
            greylist_type)
          task:set_pre_result('soft reject', settings['message'])
          task:get_mempool():set_variable("grey_greylisted", end_time)
        end
      end
    elseif err then
      rspamd_logger.infox(task, 'got error while getting greylisting keys: %1', err)
      upstream:fail()
    end
  end

  if addr then
    if not rspamd_redis.make_request(task, addr, redis_get_cb, 'MGET',
        {body_key, meta_key}) then
      rspamd_logger.errx(task, 'cannot make redis request to check results')
    end
  end
end

local function greylist_set(task)
  local is_whitelisted = task:get_mempool():get_variable("grey_whitelisted")

  local action = task:get_metric_action('default')
  local body_key = data_key(task)
  local meta_key = envelope_key(task)
  local upstream = upstreams:get_upstream_by_hash(body_key .. meta_key)
  local addr = upstream:get_addr()

  if is_whitelisted then
    if action == 'greylist' then
      -- We are going to accept message
      task:set_metric_action('default', 'no action')
    end

    task:insert_result(settings['symbol'], 0.0, 'pass', is_whitelisted)
    rspamd_logger.infox(task, 'greylisting pass (%s) till %s',
      is_whitelisted,
      rspamd_util.time_to_string(rspamd_util.get_time() + settings['expire']))

    -- Update greylisting record expire
    if addr then
      local conn = rspamd_redis.connect({
        task = task,
        host = addr
      })

      if conn then
        conn:add_cmd('EXPIRE', {
          body_key, tostring(settings['expire'])
        })
        conn:add_cmd('EXPIRE', {
          meta_key, tostring(settings['expire'])
        })
      else
        rspamd_logger.infox(task, 'got error while connecting to redis: %1', addr)
        upstream:fail()
      end
    end
  else
    if action ~= 'no action' then
      local grey_res = task:get_mempool():get_variable("grey_greylisted_body")

      if grey_res then
        -- We need to delay message, hence set a temporary result
        task:insert_result(settings['symbol'], 0.0, grey_res, 'body')
        rspamd_logger.infox(task, 'greylisting delayed till "%s": body', grey_res)
      else
        grey_res = task:get_mempool():get_variable("grey_greylisted_meta")

        if grey_res then
          task:insert_result(settings['symbol'], 0.0, grey_res, 'meta')
          rspamd_logger.infox(task, 'greylisting delayed till "%s": meta', grey_res)
        else
          task:insert_result(settings['symbol'], 0.0, 'unknown')
          rspamd_logger.infox(task, 'greylisting delayed: unknown, internal error')
        end
      end
      task:set_metric_action('default', 'soft reject')
      task:set_pre_result('soft reject', settings['message'])
    else
      task:insert_result(settings['symbol'], 0.0, 'greylisted', 'passed')
    end
  end
end

local opts =  rspamd_config:get_all_opt('greylist')
if opts then
  if opts['whitelisted_ip'] then
    whitelisted_ip = rspamd_config:add_radix_map(opts['whitelisted_ip'],
      'Greylist whitelist ip map')
  end
  if not opts['servers'] then
    rspamd_logger.infox(rspamd_config, 'no servers are specified, disabling module')
  else
    upstreams = upstream_list.create(rspamd_config, opts['servers'], default_port)
    if not upstreams then
      rspamd_logger.infox(rspamd_config, 'no servers are specified, disabling module')
    else
      rspamd_config:register_pre_filter(greylist_check)
      rspamd_config:register_post_filter(greylist_set, 10)
    end
  end

  for k,v in pairs(opts) do
    settings[k] = v
  end
end