server.py 20 KB

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