#!/opt/imh-python/bin/python3 """Setup SpamAssassin on CWP. Configuration and postfix integration provided by Dakota P.""" import re from pathlib import Path from datetime import datetime from subprocess import run SA_ENV = """# Options to spamd SAHOME="/var/lib/spamassassin/" SPAMDOPTIONS="-c -m4 -H --username nobody -s" """ SA_RULES = """rewrite_header Subject [***SPAM***] required_hits 5.0 required_score 5.0 report_safe 0 use_bayes 1 bayes_ignore_header X-Bogosity bayes_ignore_header X-Spam-Flag bayes_ignore_header X-Spam-Status """ def rename_replace(path, content): rename_tstamp = datetime.now().strftime("%Y%m%d_%H%M") path.rename(f"{path}-{rename_tstamp}") with open(path, "w", encoding="utf-8") as new_file: new_file.write(content) def restart_service(service): ret_code = run(["systemctl", "restart", f"{service}"], check=True) if ret_code.returncode != 0: return f"{service} did not restart, check systemctl status output" return None def configure_spamassassin(): """Setup SpamAssassin""" env_path = Path("/etc/sysconfig/spamassassin") filter_path = Path("/etc/mail/spamassassin/local.cf") service_path = Path("/usr/lib/systemd/system/spamassassin.service") for f_path in env_path, filter_path, service_path: if not f_path.exists(): raise FileNotFoundError( f"Error! Missing or inaccessible path: {f_path} Bailing." ) try: rename_replace(env_path, SA_ENV) rename_replace(filter_path, SA_RULES) srv_new = re.sub( r"(\$SPAMDOPTIONS)\n", r"\1 ${SAHOME}spamd.log\nStartLimitBurst=0\n", service_path.read_text(encoding="utf-8"), ) rename_replace(service_path, srv_new) except: raise print("Reloading systemd daemon") if run(["systemctl", "daemon-reload"], check=True).returncode != 0: print("Non-Zero exit code returned from systemctl daemon-reload") restart_service("spamassassin") def configure_postfix(): """Setup Postfix""" post_path = Path("/etc/postfix/master.cf") if not post_path.exists(): raise FileNotFoundError( f"Error! Missing or inaccessible path: {post_path} Bailing." ) try: post_new = re.sub( '(receive_override_options=no_address_mappings\n)(#\n##)', r'\1 -o content_filter=spamassassin\n\2', post_path.read_text(encoding="utf-8"), ) post_fnl = re.sub( '(/usr/libexec/postfix/policyd-spf\n)', r'\1# SA enable\nspamassassin unix - n n - - pipe\n user=nobody argv=/usr/bin/spamc -f -e\n /usr/sbin/sendmail -oi -f ${sender} ${recipient}\n', post_new, ) rename_replace(post_path, post_fnl) except: raise restart_service("postfix") if __name__ == "__main__": try: configure_spamassassin() configure_postfix() print("SpamAssassin setup complete!") except Exception as e: exit(f"SpamAssassin setup failed with exception!\n{e}")