1
0

server.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. #!/usr/bin/env python3
  2. import re
  3. import os
  4. import sys
  5. import time
  6. import atexit
  7. import signal
  8. import ipaddress
  9. from collections import Counter
  10. from random import randint
  11. from threading import Thread
  12. from threading import Lock
  13. import redis
  14. import json
  15. import iptc
  16. import dns.resolver
  17. import dns.exception
  18. while True:
  19. try:
  20. redis_slaveof_ip = os.getenv('REDIS_SLAVEOF_IP', '')
  21. redis_slaveof_port = os.getenv('REDIS_SLAVEOF_PORT', '')
  22. if "".__eq__(redis_slaveof_ip):
  23. r = redis.StrictRedis(host=os.getenv('IPV4_NETWORK', '172.22.1') + '.249', decode_responses=True, port=6379, db=0)
  24. else:
  25. r = redis.StrictRedis(host=redis_slaveof_ip, decode_responses=True, port=redis_slaveof_port, db=0)
  26. r.ping()
  27. except Exception as ex:
  28. print('%s - trying again in 3 seconds' % (ex))
  29. time.sleep(3)
  30. else:
  31. break
  32. pubsub = r.pubsub()
  33. WHITELIST = []
  34. BLACKLIST= []
  35. bans = {}
  36. quit_now = False
  37. exit_code = 0
  38. lock = Lock()
  39. def log(priority, message):
  40. tolog = {}
  41. tolog['time'] = int(round(time.time()))
  42. tolog['priority'] = priority
  43. tolog['message'] = message
  44. r.lpush('NETFILTER_LOG', json.dumps(tolog, ensure_ascii=False))
  45. print(message)
  46. def logWarn(message):
  47. log('warn', message)
  48. def logCrit(message):
  49. log('crit', message)
  50. def logInfo(message):
  51. log('info', message)
  52. def refreshF2boptions():
  53. global f2boptions
  54. global quit_now
  55. global exit_code
  56. if not r.get('F2B_OPTIONS'):
  57. f2boptions = {}
  58. f2boptions['ban_time'] = int
  59. f2boptions['max_attempts'] = int
  60. f2boptions['retry_window'] = int
  61. f2boptions['netban_ipv4'] = int
  62. f2boptions['netban_ipv6'] = int
  63. f2boptions['ban_time'] = r.get('F2B_BAN_TIME') or 1800
  64. f2boptions['max_attempts'] = r.get('F2B_MAX_ATTEMPTS') or 10
  65. f2boptions['retry_window'] = r.get('F2B_RETRY_WINDOW') or 600
  66. f2boptions['netban_ipv4'] = r.get('F2B_NETBAN_IPV4') or 32
  67. f2boptions['netban_ipv6'] = r.get('F2B_NETBAN_IPV6') or 128
  68. r.set('F2B_OPTIONS', json.dumps(f2boptions, ensure_ascii=False))
  69. else:
  70. try:
  71. f2boptions = {}
  72. f2boptions = json.loads(r.get('F2B_OPTIONS'))
  73. except ValueError:
  74. print('Error loading F2B options: F2B_OPTIONS is not json')
  75. quit_now = True
  76. exit_code = 2
  77. def refreshF2bregex():
  78. global f2bregex
  79. global quit_now
  80. global exit_code
  81. if not r.get('F2B_REGEX'):
  82. f2bregex = {}
  83. f2bregex[1] = 'warning: .*\[([0-9a-f\.:]+)\]: SASL .+ authentication failed'
  84. f2bregex[2] = '-login: Disconnected \(auth failed, .+\): user=.*, method=.+, rip=([0-9a-f\.:]+),'
  85. f2bregex[3] = '-login: Aborted login \(tried to use disallowed .+\): user=.+, rip=([0-9a-f\.:]+), lip.+'
  86. f2bregex[4] = 'SOGo.+ Login from \'([0-9a-f\.:]+)\' for user .+ might not have worked'
  87. f2bregex[5] = 'mailcow UI: Invalid password for .+ by ([0-9a-f\.:]+)'
  88. f2bregex[6] = '([0-9a-f\.:]+) \"GET \/SOGo\/.* HTTP.+\" 403 .+'
  89. f2bregex[7] = 'Rspamd UI: Invalid password by ([0-9a-f\.:]+)'
  90. f2bregex[8] = '-login: Aborted login \(auth failed .+\): user=.+, rip=([0-9a-f\.:]+), lip.+'
  91. r.set('F2B_REGEX', json.dumps(f2bregex, ensure_ascii=False))
  92. else:
  93. try:
  94. f2bregex = {}
  95. f2bregex = json.loads(r.get('F2B_REGEX'))
  96. except ValueError:
  97. print('Error loading F2B options: F2B_REGEX is not json')
  98. quit_now = True
  99. exit_code = 2
  100. if r.exists('F2B_LOG'):
  101. r.rename('F2B_LOG', 'NETFILTER_LOG')
  102. def mailcowChainOrder():
  103. global lock
  104. global quit_now
  105. global exit_code
  106. while not quit_now:
  107. time.sleep(10)
  108. with lock:
  109. filter4_table = iptc.Table(iptc.Table.FILTER)
  110. filter6_table = iptc.Table6(iptc.Table6.FILTER)
  111. filter4_table.refresh()
  112. filter6_table.refresh()
  113. for f in [filter4_table, filter6_table]:
  114. forward_chain = iptc.Chain(f, 'FORWARD')
  115. input_chain = iptc.Chain(f, 'INPUT')
  116. for chain in [forward_chain, input_chain]:
  117. target_found = False
  118. for position, item in enumerate(chain.rules):
  119. if item.target.name == 'MAILCOW':
  120. target_found = True
  121. if position > 2:
  122. logCrit('Error in %s chain order: MAILCOW on position %d, restarting container' % (chain.name, position))
  123. quit_now = True
  124. exit_code = 2
  125. if not target_found:
  126. logCrit('Error in %s chain: MAILCOW target not found, restarting container' % (chain.name))
  127. quit_now = True
  128. exit_code = 2
  129. def ban(address):
  130. global lock
  131. refreshF2boptions()
  132. BAN_TIME = int(f2boptions['ban_time'])
  133. MAX_ATTEMPTS = int(f2boptions['max_attempts'])
  134. RETRY_WINDOW = int(f2boptions['retry_window'])
  135. NETBAN_IPV4 = '/' + str(f2boptions['netban_ipv4'])
  136. NETBAN_IPV6 = '/' + str(f2boptions['netban_ipv6'])
  137. ip = ipaddress.ip_address(address)
  138. if type(ip) is ipaddress.IPv6Address and ip.ipv4_mapped:
  139. ip = ip.ipv4_mapped
  140. address = str(ip)
  141. if ip.is_private or ip.is_loopback:
  142. return
  143. self_network = ipaddress.ip_network(address)
  144. with lock:
  145. temp_whitelist = set(WHITELIST)
  146. if temp_whitelist:
  147. for wl_key in temp_whitelist:
  148. wl_net = ipaddress.ip_network(wl_key, False)
  149. if wl_net.overlaps(self_network):
  150. logInfo('Address %s is whitelisted by rule %s' % (self_network, wl_net))
  151. return
  152. net = ipaddress.ip_network((address + (NETBAN_IPV4 if type(ip) is ipaddress.IPv4Address else NETBAN_IPV6)), strict=False)
  153. net = str(net)
  154. if not net in bans or time.time() - bans[net]['last_attempt'] > RETRY_WINDOW:
  155. bans[net] = { 'attempts': 0 }
  156. active_window = RETRY_WINDOW
  157. else:
  158. active_window = time.time() - bans[net]['last_attempt']
  159. bans[net]['attempts'] += 1
  160. bans[net]['last_attempt'] = time.time()
  161. active_window = time.time() - bans[net]['last_attempt']
  162. if bans[net]['attempts'] >= MAX_ATTEMPTS:
  163. cur_time = int(round(time.time()))
  164. logCrit('Banning %s for %d minutes' % (net, BAN_TIME / 60))
  165. if type(ip) is ipaddress.IPv4Address:
  166. with lock:
  167. chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW')
  168. rule = iptc.Rule()
  169. rule.src = net
  170. target = iptc.Target(rule, "REJECT")
  171. rule.target = target
  172. if rule not in chain.rules:
  173. chain.insert_rule(rule)
  174. else:
  175. with lock:
  176. chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW')
  177. rule = iptc.Rule6()
  178. rule.src = net
  179. target = iptc.Target(rule, "REJECT")
  180. rule.target = target
  181. if rule not in chain.rules:
  182. chain.insert_rule(rule)
  183. r.hset('F2B_ACTIVE_BANS', '%s' % net, cur_time + BAN_TIME)
  184. else:
  185. logWarn('%d more attempts in the next %d seconds until %s is banned' % (MAX_ATTEMPTS - bans[net]['attempts'], RETRY_WINDOW, net))
  186. def unban(net):
  187. global lock
  188. if not net in bans:
  189. logInfo('%s is not banned, skipping unban and deleting from queue (if any)' % net)
  190. r.hdel('F2B_QUEUE_UNBAN', '%s' % net)
  191. return
  192. logInfo('Unbanning %s' % net)
  193. if type(ipaddress.ip_network(net)) is ipaddress.IPv4Network:
  194. with lock:
  195. chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW')
  196. rule = iptc.Rule()
  197. rule.src = net
  198. target = iptc.Target(rule, "REJECT")
  199. rule.target = target
  200. if rule in chain.rules:
  201. chain.delete_rule(rule)
  202. else:
  203. with lock:
  204. chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW')
  205. rule = iptc.Rule6()
  206. rule.src = net
  207. target = iptc.Target(rule, "REJECT")
  208. rule.target = target
  209. if rule in chain.rules:
  210. chain.delete_rule(rule)
  211. r.hdel('F2B_ACTIVE_BANS', '%s' % net)
  212. r.hdel('F2B_QUEUE_UNBAN', '%s' % net)
  213. if net in bans:
  214. del bans[net]
  215. def permBan(net, unban=False):
  216. global lock
  217. if type(ipaddress.ip_network(net, strict=False)) is ipaddress.IPv4Network:
  218. with lock:
  219. chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW')
  220. rule = iptc.Rule()
  221. rule.src = net
  222. target = iptc.Target(rule, "REJECT")
  223. rule.target = target
  224. if rule not in chain.rules and not unban:
  225. logCrit('Add host/network %s to blacklist' % net)
  226. chain.insert_rule(rule)
  227. r.hset('F2B_PERM_BANS', '%s' % net, int(round(time.time())))
  228. elif rule in chain.rules and unban:
  229. logCrit('Remove host/network %s from blacklist' % net)
  230. chain.delete_rule(rule)
  231. r.hdel('F2B_PERM_BANS', '%s' % net)
  232. else:
  233. with lock:
  234. chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW')
  235. rule = iptc.Rule6()
  236. rule.src = net
  237. target = iptc.Target(rule, "REJECT")
  238. rule.target = target
  239. if rule not in chain.rules and not unban:
  240. logCrit('Add host/network %s to blacklist' % net)
  241. chain.insert_rule(rule)
  242. r.hset('F2B_PERM_BANS', '%s' % net, int(round(time.time())))
  243. elif rule in chain.rules and unban:
  244. logCrit('Remove host/network %s from blacklist' % net)
  245. chain.delete_rule(rule)
  246. r.hdel('F2B_PERM_BANS', '%s' % net)
  247. def quit(signum, frame):
  248. global quit_now
  249. quit_now = True
  250. def clear():
  251. global lock
  252. logInfo('Clearing all bans')
  253. for net in bans.copy():
  254. unban(net)
  255. with lock:
  256. filter4_table = iptc.Table(iptc.Table.FILTER)
  257. filter6_table = iptc.Table6(iptc.Table6.FILTER)
  258. for filter_table in [filter4_table, filter6_table]:
  259. filter_table.autocommit = False
  260. forward_chain = iptc.Chain(filter_table, "FORWARD")
  261. input_chain = iptc.Chain(filter_table, "INPUT")
  262. mailcow_chain = iptc.Chain(filter_table, "MAILCOW")
  263. if mailcow_chain in filter_table.chains:
  264. for rule in mailcow_chain.rules:
  265. mailcow_chain.delete_rule(rule)
  266. for rule in forward_chain.rules:
  267. if rule.target.name == 'MAILCOW':
  268. forward_chain.delete_rule(rule)
  269. for rule in input_chain.rules:
  270. if rule.target.name == 'MAILCOW':
  271. input_chain.delete_rule(rule)
  272. filter_table.delete_chain("MAILCOW")
  273. filter_table.commit()
  274. filter_table.refresh()
  275. filter_table.autocommit = True
  276. r.delete('F2B_ACTIVE_BANS')
  277. r.delete('F2B_PERM_BANS')
  278. pubsub.unsubscribe()
  279. def watch():
  280. logInfo('Watching Redis channel F2B_CHANNEL')
  281. pubsub.subscribe('F2B_CHANNEL')
  282. while not quit_now:
  283. for item in pubsub.listen():
  284. try:
  285. refreshF2bregex()
  286. for rule_id, rule_regex in f2bregex.items():
  287. if item['data'] and item['type'] == 'message':
  288. try:
  289. result = re.search(rule_regex, item['data'])
  290. except re.error:
  291. result = False
  292. if result:
  293. addr = result.group(1)
  294. ip = ipaddress.ip_address(addr)
  295. if ip.is_private or ip.is_loopback:
  296. continue
  297. logWarn('%s matched rule id %s (%s)' % (addr, rule_id, item['data']))
  298. ban(addr)
  299. except Exception as ex:
  300. logWarn('Could not read logline from pubsub, skipping...')
  301. continue
  302. def snat4(snat_target):
  303. global lock
  304. global quit_now
  305. def get_snat4_rule():
  306. rule = iptc.Rule()
  307. rule.src = os.getenv('IPV4_NETWORK', '172.22.1') + '.0/24'
  308. rule.dst = '!' + rule.src
  309. target = rule.create_target("SNAT")
  310. target.to_source = snat_target
  311. return rule
  312. while not quit_now:
  313. time.sleep(10)
  314. with lock:
  315. try:
  316. table = iptc.Table('nat')
  317. table.refresh()
  318. chain = iptc.Chain(table, 'POSTROUTING')
  319. table.autocommit = False
  320. if get_snat4_rule() not in chain.rules:
  321. logCrit('Added POSTROUTING rule for source network %s to SNAT target %s' % (get_snat4_rule().src, snat_target))
  322. chain.insert_rule(get_snat4_rule())
  323. table.commit()
  324. else:
  325. for position, item in enumerate(chain.rules):
  326. if item == get_snat4_rule():
  327. if position != 0:
  328. chain.delete_rule(get_snat4_rule())
  329. table.commit()
  330. table.autocommit = True
  331. except:
  332. print('Error running SNAT4, retrying...')
  333. def snat6(snat_target):
  334. global lock
  335. global quit_now
  336. def get_snat6_rule():
  337. rule = iptc.Rule6()
  338. rule.src = os.getenv('IPV6_NETWORK', 'fd4d:6169:6c63:6f77::/64')
  339. rule.dst = '!' + rule.src
  340. target = rule.create_target("SNAT")
  341. target.to_source = snat_target
  342. return rule
  343. while not quit_now:
  344. time.sleep(10)
  345. with lock:
  346. try:
  347. table = iptc.Table6('nat')
  348. table.refresh()
  349. chain = iptc.Chain(table, 'POSTROUTING')
  350. table.autocommit = False
  351. if get_snat6_rule() not in chain.rules:
  352. logInfo('Added POSTROUTING rule for source network %s to SNAT target %s' % (get_snat6_rule().src, snat_target))
  353. chain.insert_rule(get_snat6_rule())
  354. table.commit()
  355. else:
  356. for position, item in enumerate(chain.rules):
  357. if item == get_snat6_rule():
  358. if position != 0:
  359. chain.delete_rule(get_snat6_rule())
  360. table.commit()
  361. table.autocommit = True
  362. except:
  363. print('Error running SNAT6, retrying...')
  364. def autopurge():
  365. while not quit_now:
  366. time.sleep(10)
  367. refreshF2boptions()
  368. BAN_TIME = int(f2boptions['ban_time'])
  369. MAX_ATTEMPTS = int(f2boptions['max_attempts'])
  370. QUEUE_UNBAN = r.hgetall('F2B_QUEUE_UNBAN')
  371. if QUEUE_UNBAN:
  372. for net in QUEUE_UNBAN:
  373. unban(str(net))
  374. for net in bans.copy():
  375. if bans[net]['attempts'] >= MAX_ATTEMPTS:
  376. if time.time() - bans[net]['last_attempt'] > BAN_TIME:
  377. unban(net)
  378. def isIpNetwork(address):
  379. try:
  380. ipaddress.ip_network(address, False)
  381. except ValueError:
  382. return False
  383. return True
  384. def genNetworkList(list):
  385. resolver = dns.resolver.Resolver()
  386. hostnames = []
  387. networks = []
  388. for key in list:
  389. if isIpNetwork(key):
  390. networks.append(key)
  391. else:
  392. hostnames.append(key)
  393. for hostname in hostnames:
  394. hostname_ips = []
  395. for rdtype in ['A', 'AAAA']:
  396. try:
  397. answer = resolver.resolve(qname=hostname, rdtype=rdtype, lifetime=3)
  398. except dns.exception.Timeout:
  399. logInfo('Hostname %s timedout on resolve' % hostname)
  400. break
  401. except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
  402. continue
  403. except dns.exception.DNSException as dnsexception:
  404. logInfo('%s' % dnsexception)
  405. continue
  406. for rdata in answer:
  407. hostname_ips.append(rdata.to_text())
  408. networks.extend(hostname_ips)
  409. return set(networks)
  410. def whitelistUpdate():
  411. global lock
  412. global quit_now
  413. global WHITELIST
  414. while not quit_now:
  415. start_time = time.time()
  416. list = r.hgetall('F2B_WHITELIST')
  417. new_whitelist = []
  418. if list:
  419. new_whitelist = genNetworkList(list)
  420. with lock:
  421. if Counter(new_whitelist) != Counter(WHITELIST):
  422. WHITELIST = new_whitelist
  423. logInfo('Whitelist was changed, it has %s entries' % len(WHITELIST))
  424. time.sleep(60.0 - ((time.time() - start_time) % 60.0))
  425. def blacklistUpdate():
  426. global quit_now
  427. global BLACKLIST
  428. while not quit_now:
  429. start_time = time.time()
  430. list = r.hgetall('F2B_BLACKLIST')
  431. new_blacklist = []
  432. if list:
  433. new_blacklist = genNetworkList(list)
  434. if Counter(new_blacklist) != Counter(BLACKLIST):
  435. addban = set(new_blacklist).difference(BLACKLIST)
  436. delban = set(BLACKLIST).difference(new_blacklist)
  437. BLACKLIST = new_blacklist
  438. logInfo('Blacklist was changed, it has %s entries' % len(BLACKLIST))
  439. if addban:
  440. for net in addban:
  441. permBan(net=net)
  442. if delban:
  443. for net in delban:
  444. permBan(net=net, unban=True)
  445. time.sleep(60.0 - ((time.time() - start_time) % 60.0))
  446. def initChain():
  447. # Is called before threads start, no locking
  448. print("Initializing mailcow netfilter chain")
  449. # IPv4
  450. if not iptc.Chain(iptc.Table(iptc.Table.FILTER), "MAILCOW") in iptc.Table(iptc.Table.FILTER).chains:
  451. iptc.Table(iptc.Table.FILTER).create_chain("MAILCOW")
  452. for c in ['FORWARD', 'INPUT']:
  453. chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), c)
  454. rule = iptc.Rule()
  455. rule.src = '0.0.0.0/0'
  456. rule.dst = '0.0.0.0/0'
  457. target = iptc.Target(rule, "MAILCOW")
  458. rule.target = target
  459. if rule not in chain.rules:
  460. chain.insert_rule(rule)
  461. # IPv6
  462. if not iptc.Chain(iptc.Table6(iptc.Table6.FILTER), "MAILCOW") in iptc.Table6(iptc.Table6.FILTER).chains:
  463. iptc.Table6(iptc.Table6.FILTER).create_chain("MAILCOW")
  464. for c in ['FORWARD', 'INPUT']:
  465. chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), c)
  466. rule = iptc.Rule6()
  467. rule.src = '::/0'
  468. rule.dst = '::/0'
  469. target = iptc.Target(rule, "MAILCOW")
  470. rule.target = target
  471. if rule not in chain.rules:
  472. chain.insert_rule(rule)
  473. if __name__ == '__main__':
  474. # In case a previous session was killed without cleanup
  475. clear()
  476. # Reinit MAILCOW chain
  477. initChain()
  478. watch_thread = Thread(target=watch)
  479. watch_thread.daemon = True
  480. watch_thread.start()
  481. if os.getenv('SNAT_TO_SOURCE') and os.getenv('SNAT_TO_SOURCE') != 'n':
  482. try:
  483. snat_ip = os.getenv('SNAT_TO_SOURCE')
  484. snat_ipo = ipaddress.ip_address(snat_ip)
  485. if type(snat_ipo) is ipaddress.IPv4Address:
  486. snat4_thread = Thread(target=snat4,args=(snat_ip,))
  487. snat4_thread.daemon = True
  488. snat4_thread.start()
  489. except ValueError:
  490. print(os.getenv('SNAT_TO_SOURCE') + ' is not a valid IPv4 address')
  491. if os.getenv('SNAT6_TO_SOURCE') and os.getenv('SNAT6_TO_SOURCE') != 'n':
  492. try:
  493. snat_ip = os.getenv('SNAT6_TO_SOURCE')
  494. snat_ipo = ipaddress.ip_address(snat_ip)
  495. if type(snat_ipo) is ipaddress.IPv6Address:
  496. snat6_thread = Thread(target=snat6,args=(snat_ip,))
  497. snat6_thread.daemon = True
  498. snat6_thread.start()
  499. except ValueError:
  500. print(os.getenv('SNAT6_TO_SOURCE') + ' is not a valid IPv6 address')
  501. autopurge_thread = Thread(target=autopurge)
  502. autopurge_thread.daemon = True
  503. autopurge_thread.start()
  504. mailcowchainwatch_thread = Thread(target=mailcowChainOrder)
  505. mailcowchainwatch_thread.daemon = True
  506. mailcowchainwatch_thread.start()
  507. blacklistupdate_thread = Thread(target=blacklistUpdate)
  508. blacklistupdate_thread.daemon = True
  509. blacklistupdate_thread.start()
  510. whitelistupdate_thread = Thread(target=whitelistUpdate)
  511. whitelistupdate_thread.daemon = True
  512. whitelistupdate_thread.start()
  513. signal.signal(signal.SIGTERM, quit)
  514. atexit.register(clear)
  515. while not quit_now:
  516. time.sleep(0.5)
  517. sys.exit(exit_code)