forked from haraka/haraka-plugin-limit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
628 lines (504 loc) · 16.7 KB
/
index.js
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
const constants = require('haraka-constants')
const ipaddr = require('ipaddr.js')
exports.register = function () {
this.inherits('haraka-plugin-redis')
this.load_limit_ini()
let needs_redis = 0
if (this.cfg.concurrency.enabled) {
needs_redis++
this.register_hook('connect_init', 'conn_concur_incr')
this.register_hook('connect', 'check_concurrency')
this.register_hook('disconnect', 'conn_concur_decr')
}
if (this.cfg.errors.enabled) {
for (const hook of ['helo', 'ehlo', 'mail', 'rcpt', 'data']) {
this.register_hook(hook, 'max_errors')
}
}
if (this.cfg.recipients.enabled) {
this.register_hook('rcpt', 'max_recipients')
}
if (this.cfg.unrecognized_commands.enabled) {
this.register_hook('unrecognized_command', 'max_unrecognized_commands')
}
if (this.cfg.rate_conn.enabled) {
needs_redis++
this.register_hook('connect_init', 'rate_conn_incr')
this.register_hook('connect', 'rate_conn_enforce')
}
if (this.cfg.rate_rcpt_host.enabled) {
needs_redis++
this.register_hook('connect', 'rate_rcpt_host_enforce')
this.register_hook('rcpt', 'rate_rcpt_host_incr')
}
if (this.cfg.rate_rcpt_sender.enabled) {
needs_redis++
this.register_hook('rcpt', 'rate_rcpt_sender')
}
if (this.cfg.rate_rcpt_null.enabled) {
needs_redis++
this.register_hook('rcpt', 'rate_rcpt_null')
}
if (this.cfg.rate_rcpt.enabled) {
needs_redis++
this.register_hook('rcpt', 'rate_rcpt')
}
if (this.cfg.outbound.enabled) {
needs_redis++
this.register_hook('send_email', 'outbound_increment')
this.register_hook('delivered', 'outbound_decrement')
this.register_hook('deferred', 'outbound_decrement')
this.register_hook('bounce', 'outbound_decrement')
}
if (needs_redis) {
this.register_hook('init_master', 'init_redis_plugin')
this.register_hook('init_child', 'init_redis_plugin')
}
}
exports.load_limit_ini = function () {
this.cfg = this.config.get(
'limit.ini',
{
booleans: [
'-outbound.enabled',
'-recipients.enabled',
'-unrecognized_commands.enabled',
'-errors.enabled',
'-rate_conn.enabled',
'-rate_rcpt.enabled',
'-rate_rcpt_host.enabled',
'-rate_rcpt_sender.enabled',
'-rate_rcpt_null.enabled',
'-concurrency_history.enabled',
'-recipients_history.enabled',
'-rate_conn_history.enabled',
],
},
() => {
this.load_limit_ini()
},
)
if (!this.cfg.concurrency) {
// no config file
this.cfg.concurrency = {}
}
this.merge_redis_ini()
}
exports.shutdown = function () {
if (this.db) this.db.quit()
}
exports.max_unrecognized_commands = function (next, connection, cmd) {
if (!this.cfg.unrecognized_commands) return next()
connection.results.push(this, { unrec_cmds: cmd, emit: true })
const max = parseFloat(this.cfg.unrecognized_commands.max)
if (!max || isNaN(max)) return next()
const uc = connection.results.get(this).unrec_cmds
if (!uc || !uc.length) return next()
if (uc.length <= max) return next()
connection.results.add(this, { fail: 'unrec_cmds.max' })
this.penalize(connection, true, 'Too many unrecognized commands', next)
}
exports.max_errors = function (next, connection) {
if (!this.cfg.errors) return next() // disabled in config
const max = parseFloat(this.cfg.errors.max)
if (!max || isNaN(max)) return next()
if (connection.errors <= max) return next()
connection.results.add(this, { fail: 'errors.max' })
this.penalize(connection, true, 'Too many errors', next)
}
exports.max_recipients = function (next, connection, params) {
if (!this.cfg.recipients) return next() // disabled in config
const max = this.get_limit('recipients', connection)
if (!max || isNaN(max)) return next()
const c = connection.rcpt_count
const count = c.accept + c.tempfail + c.reject + 1
if (count <= max) return next()
connection.results.add(this, { fail: 'recipients.max' })
this.penalize(connection, false, 'Too many recipient attempts', next)
}
exports.get_history_limit = function (type, connection) {
const history_cfg = `${type}_history`
if (!this.cfg[history_cfg] || !this.cfg[history_cfg].enabled) return
const history_plugin = this.cfg[history_cfg].plugin
if (!history_plugin) return
const results = connection.results.get(history_plugin)
if (!results) {
connection.logerror(
this,
`no ${history_plugin} results, disabling history due to misconfiguration`,
)
delete this.cfg[history_cfg]
return
}
if (results.history === undefined) {
connection.logdebug(this, `no history from : ${history_plugin}`)
return
}
const history = parseFloat(results.history)
connection.logdebug(this, `history: ${history}`)
if (isNaN(history)) return
if (history > 0) return this.cfg[history_cfg].good
if (history < 0) return this.cfg[history_cfg].bad
return this.cfg[history_cfg].none
}
exports.get_limit = function (type, connection) {
if (type === 'recipients') {
if (connection.relaying && this.cfg.recipients.max_relaying) {
return this.cfg.recipients.max_relaying
}
}
if (this.cfg[`${type}_history`]) {
const history = this.get_history_limit(type, connection)
if (history) return history
}
return this.cfg[type].max || this.cfg[type].default
}
exports.conn_concur_incr = async function (next, connection) {
if (!this.db) return next()
if (!this.cfg.concurrency) return next()
const dbkey = this.get_concurrency_key(connection)
try {
const count = await this.db.incr(dbkey)
if (isNaN(count)) {
connection.results.add(this, { err: 'conn_concur_incr got isNaN' })
return next()
}
connection.results.add(this, { concurrent_count: count })
// repair negative concurrency counters
if (count < 1) {
connection.results.add(this, {
msg: `resetting concurrent ${count} to 1`,
})
this.db.set(dbkey, 1)
}
this.db.expire(dbkey, 3 * 60) // 3 minute lifetime
} catch (err) {
connection.results.add(this, { err: `conn_concur_incr:${err}` })
}
next()
}
exports.get_concurrency_key = function (connection) {
return `concurrency|${connection.remote.ip}`
}
exports.check_concurrency = function (next, connection) {
const max = this.get_limit('concurrency', connection)
if (!max || isNaN(max)) {
connection.results.add(this, { err: 'concurrency: no limit?!' })
return next()
}
const count = parseInt(connection.results.get(this.name).concurrent_count)
if (isNaN(count)) {
connection.results.add(this, { err: 'concurrent.unset' })
return next()
}
connection.results.add(this, { concurrent: `${count}/${max}` })
if (count <= max) return next()
connection.results.add(this, { fail: 'concurrency.max' })
this.penalize(connection, true, 'Too many concurrent connections', next)
}
exports.penalize = function (connection, disconnect, msg, next) {
const code = disconnect ? constants.DENYSOFTDISCONNECT : constants.DENYSOFT
if (!this.cfg.main.tarpit_delay) return next(code, msg)
const delay = this.cfg.main.tarpit_delay
connection.loginfo(this, `tarpitting for ${delay}s`)
setTimeout(() => {
if (!connection) return
next(code, msg)
}, delay * 1000)
}
exports.conn_concur_decr = async function (next, connection) {
if (!this.db) return next()
if (!this.cfg.concurrency) return next()
try {
const dbkey = this.get_concurrency_key(connection)
await this.db.incrBy(dbkey, -1)
} catch (err) {
connection.results.add(this, { err: `conn_concur_decr:${err}` })
}
next()
}
exports.get_host_key = function (type, connection) {
if (!this.cfg[type]) {
connection.results.add(this, { err: `${type}: not configured` })
return
}
let ip
try {
ip = ipaddr.parse(connection.remote.ip)
if (ip.kind === 'ipv6') {
ip = ipaddr.toNormalizedString()
} else {
ip = ip.toString()
}
} catch (err) {
connection.results.add(this, { err: `${type}: ${err.message}` })
return
}
const ip_array = ip.kind === 'ipv6' ? ip.split(':') : ip.split('.')
while (ip_array.length) {
const part = ip.kind === 'ipv6' ? ip_array.join(':') : ip_array.join('.')
if (this.cfg[type][part] || this.cfg[type][part] === 0) {
return [part, this.cfg[type][part]]
}
ip_array.pop()
}
// rDNS
if (connection.remote.host) {
const rdns_array = connection.remote.host.toLowerCase().split('.')
while (rdns_array.length) {
const part2 = rdns_array.join('.')
if (this.cfg[type][part2] || this.cfg[type][part2] === 0) {
return [part2, this.cfg[type][part2]]
}
rdns_array.pop()
}
}
if (this.cfg[`${type}_history`]) {
const history = this.get_history_limit(type, connection)
if (history) return [ip, history]
}
// Custom Default
if (this.cfg[type].default) {
return [ip, this.cfg[type].default]
}
// Default 0 = unlimited
return [ip, 0]
}
exports.get_mail_key = function (type, mail) {
if (!this.cfg[type] || !mail) return
// Full e-mail address (e.g. [email protected])
const email = mail.address()
if (this.cfg[type][email] || this.cfg[type][email] === 0) {
return [email, this.cfg[type][email]]
}
// RHS parts e.g. host.sub.sub.domain.com
if (mail.host) {
const rhs_split = mail.host.toLowerCase().split('.')
while (rhs_split.length) {
const part = rhs_split.join('.')
if (this.cfg[type][part] || this.cfg[type][part] === 0) {
return [part, this.cfg[type][part]]
}
rhs_split.pop()
}
}
// Custom Default
if (this.cfg[type].default) {
return [email, this.cfg[type].default]
}
// Default 0 = unlimited
return [email, 0]
}
function getTTL(value) {
const match = /^(\d+)(?:\/(\d+)(\S)?)?$/.exec(value)
if (!match) return
const qty = match[2]
const units = match[3]
let ttl = qty ? qty : 60 // Default 60s
if (!units) return ttl
// Unit
switch (units.toLowerCase()) {
case 's': // Default is seconds
break
case 'm':
ttl *= 60 // minutes
break
case 'h':
ttl *= 60 * 60 // hours
break
case 'd':
ttl *= 60 * 60 * 24 // days
break
default:
return ttl
}
return ttl
}
function getLimit(value) {
const match = /^([\d]+)/.exec(value)
if (!match) return 0
return parseInt(match[1], 10)
}
exports.rate_limit = async function (connection, key, value) {
if (value === 0) {
// Limit disabled for this host
connection.loginfo(this, `rate limit disabled for: ${key}`)
return false
}
// CAUTION: !value would match that 0 value -^
if (!key || !value) return
if (!this.db) return
const limit = getLimit(value)
const ttl = getTTL(value)
if (!limit || !ttl) {
connection.results.add(this, {
err: `syntax error: key=${key} value=${value}`,
})
return
}
connection.logdebug(this, `key=${key} limit=${limit} ttl=${ttl}`)
try {
const newval = await this.db.incr(key)
if (newval === 1) this.db.expire(key, ttl)
return parseInt(newval, 10) > limit // boolean
} catch (err) {
connection.results.add(this, { err: `${key}:${err}` })
}
}
exports.rate_rcpt_host_incr = async function (next, connection) {
if (!this.db) return next()
const [key, value] = this.get_host_key('rate_rcpt_host', connection)
if (!key || !value) return next()
try {
const newval = await this.db.incr(`rate_rcpt_host:${key}`)
if (newval === 1)
await this.db.expire(`rate_rcpt_host:${key}`, getTTL(value))
} catch (err) {
connection.results.add(this, { err })
}
next()
}
exports.rate_rcpt_host_enforce = async function (next, connection) {
if (!this.db) return next()
const [key, value] = this.get_host_key('rate_rcpt_host', connection)
if (!key || !value) return next()
const match = /^(\d+)/.exec(value)
const limit = parseInt(match[0], 10)
if (!limit) return next()
try {
const result = await this.db.get(`rate_rcpt_host:${key}`)
if (!result) return next()
connection.results.add(this, {
rate_rcpt_host: `${key}:${result}:${value}`,
})
if (result <= limit) return next()
connection.results.add(this, { fail: 'rate_rcpt_host' })
this.penalize(connection, false, 'recipient rate limit exceeded', next)
} catch (err) {
connection.results.add(this, { err: `rate_rcpt_host:${err}` })
next()
}
}
exports.rate_conn_incr = async function (next, connection) {
if (!this.db) return next()
const [key, value] = this.get_host_key('rate_conn', connection)
if (!key || !value) return next()
try {
await this.db.hIncrBy(`rate_conn:${key}`, (+new Date()).toString(), 1)
// extend key expiration on every new connection
await this.db.expire(`rate_conn:${key}`, getTTL(value) * 2)
} catch (err) {
console.error(err)
connection.results.add(this, { err })
}
next()
}
exports.rate_conn_enforce = async function (next, connection) {
if (!this.db) return next()
const [key, value] = this.get_host_key('rate_conn', connection)
if (!key || !value) return next()
const limit = getLimit(value)
if (!limit) {
connection.results.add(this, { err: `rate_conn:syntax:${value}` })
return next()
}
try {
const tstamps = await this.db.hGetAll(`rate_conn:${key}`)
if (!tstamps) {
connection.results.add(this, { err: 'rate_conn:no_tstamps' })
return next()
}
const d = new Date()
d.setMinutes(d.getMinutes() - getTTL(value) / 60)
const periodStartTs = +d // date as integer
let connections_in_ttl_period = 0
for (const ts of Object.keys(tstamps)) {
if (parseInt(ts, 10) < periodStartTs) continue // older than ttl
connections_in_ttl_period =
connections_in_ttl_period + parseInt(tstamps[ts], 10)
}
connection.results.add(this, {
rate_conn: `${connections_in_ttl_period}:${value}`,
})
if (connections_in_ttl_period <= limit) return next()
connection.results.add(this, { fail: 'rate_conn' })
this.penalize(connection, true, 'connection rate limit exceeded', next)
} catch (err) {
connection.results.add(this, { err: `rate_conn:${err}` })
next()
}
}
exports.rate_rcpt_sender = async function (next, connection, params) {
const [key, value] = this.get_mail_key(
'rate_rcpt_sender',
connection.transaction.mail_from,
)
connection.results.add(this, { rate_rcpt_sender: value })
const over = await this.rate_limit(
connection,
`rate_rcpt_sender:${key}`,
value,
)
if (!over) return next()
connection.results.add(this, { fail: 'rate_rcpt_sender' })
this.penalize(connection, false, 'rcpt rate limit exceeded', next)
}
exports.rate_rcpt_null = async function (next, connection, params) {
if (!params) return next()
if (Array.isArray(params)) params = params[0]
if (params.user) return next()
// Message from the null sender
const [key, value] = this.get_mail_key('rate_rcpt_null', params)
connection.results.add(this, { rate_rcpt_null: value })
const over = await this.rate_limit(connection, `rate_rcpt_null:${key}`, value)
if (!over) return next()
connection.results.add(this, { fail: 'rate_rcpt_null' })
this.penalize(connection, false, 'null recip rate limit', next)
}
exports.rate_rcpt = async function (next, connection, params) {
const plugin = this
if (Array.isArray(params)) params = params[0]
const [key, value] = plugin.get_mail_key('rate_rcpt', params)
connection.results.add(plugin, { rate_rcpt: value })
const over = await plugin.rate_limit(connection, `rate_rcpt:${key}`, value)
if (!over) return next()
connection.results.add(plugin, { fail: 'rate_rcpt' })
plugin.penalize(connection, false, 'rate limit exceeded', next)
}
/*
* Outbound Rate Limits
*
*/
function getOutDom(hmail) {
// outbound isn't internally consistent using hmail.domain and hmail.todo.domain.
// TODO: fix haraka/Haraka/outbound/HMailItem to be internally consistent.
return hmail?.todo?.domain || hmail.domain
}
function getOutKey(domain) {
return `outbound-rate:${domain}`
}
exports.outbound_increment = async function (next, hmail) {
if (!this.db) return next()
const outDom = getOutDom(hmail)
const outKey = getOutKey(outDom)
try {
let count = await this.db.hIncrBy(outKey, 'TOTAL', 1)
this.db.expire(outKey, 300) // 5 min expire
if (!this.cfg.outbound[outDom]) return next()
const limit = parseInt(this.cfg.outbound[outDom], 10)
if (!limit) return next()
count = parseInt(count, 10)
if (count <= limit) return next()
this.db.hIncrBy(outKey, 'TOTAL', -1) // undo the increment
const delay = this.cfg.outbound.delay || 30
next(constants.delay, delay)
} catch (err) {
this.logerror(`outbound_increment: ${err}`)
next() // just deliver
}
}
exports.outbound_decrement = function (next, hmail) {
if (!this.db) return next()
this.db.hIncrBy(getOutKey(getOutDom(hmail)), 'TOTAL', -1)
next()
}