server.py 16 KB

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