Skip to content

Instantly share code, notes, and snippets.

@ACK-J
Last active February 4, 2025 16:34
Show Gist options
  • Save ACK-J/8a189bafbb54e00fb1b3f3e22dcd81c9 to your computer and use it in GitHub Desktop.
Save ACK-J/8a189bafbb54e00fb1b3f3e22dcd81c9 to your computer and use it in GitHub Desktop.
import dns.resolver
import sys
from tld import get_fld
def get_root_domain(domain):
return get_fld(domain, fix_protocol=True)
def check_dmarc(domain):
try:
answers = dns.resolver.resolve(f'_dmarc.{domain}', 'TXT')
for rdata in answers:
if 'DMARC1' in str(rdata):
return str(rdata)
return None
except dns.resolver.NXDOMAIN:
return None
except Exception as e:
return None
def check_spf(domain):
try:
answers = dns.resolver.resolve(f'{domain}', 'TXT')
for rdata in answers:
if 'v=spf1' in str(rdata).lower():
spf_record = str(rdata)
if "+all" in spf_record or "?all" in spf_record:
return spf_record
return None
except dns.resolver.NXDOMAIN:
return None
except Exception as e:
return None
def analyze_dmarc(original_domain, root_domain, dmarc_record, spf_record):
# Consistently formatting the domain to be 40 characters wide
domain_width = 40
#print(f"{original_domain:<{domain_width}}", end="")
if dmarc_record is None:
print(f"{original_domain:<{domain_width}}No DMARC record found")
else:
record_parts = dmarc_record.split(';')
for part in record_parts:
part = part.strip().lower()
if part.startswith('p=none') or part.startswith('sp=none'):
print(f"{original_domain:<{domain_width}}DMARC policy is 'none' (p=none or sp=none)")
return
if part.startswith('pct='):
try:
pct = int(part.split('=')[1])
if pct < 100:
print(f"{original_domain:<{domain_width}}DMARC percentage is less than 100% (pct={pct})")
return
except ValueError:
pass
if spf_record is not None:
print(f"{original_domain:<{domain_width}}SPF record contains '+all' or '?all': {spf_record}")
def main(input_file):
with open(input_file, 'r') as file:
for line in file:
original_domain = line.strip()
if original_domain:
root_domain = get_root_domain(original_domain)
dmarc_record = check_dmarc(root_domain)
spf_record = check_spf(root_domain)
analyze_dmarc(original_domain, root_domain, dmarc_record, spf_record)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python script.py <input_file>")
sys.exit(1)
input_file = sys.argv[1]
main(input_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment