summaryrefslogtreecommitdiffstats
path: root/scripts/python/powerdns_caa_patcher.py
blob: 59855e5f42c928dee76e505f0bf4382c71006f63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/python3
"""
PowerDNS CAA Patching/Rollout script.

Created and Last modified: 13/09/2021 by Georg Pfuetzenreuter <georg@lysergic.dev>
"""
import requests
import sys
import os
from dotenv import load_dotenv

if len(sys.argv) > 1:
    domain = sys.argv[1]
else:
    print("Specify the domain name.")
    sys.exit(1)

load_dotenv()

# POWERDNS SETTINGS
ENDPOINT_PDNS = os.environ.get('ENDPOINT_PDNS')
APIKEY_PDNS = os.environ.get('APIKEY_PDNS')

# CAA SETTINGS
ca = 'letsencrypt.org'
iodef = 'system@lysergic.dev'

if None in (ENDPOINT_PDNS, APIKEY_PDNS):
    print("Could not load environment variables. Please check your .env file.")
    sys.exit(0)

print("Scanning " + domain)

# QUERY POWERDNS
URL = ENDPOINT_PDNS + '/api/v1/servers/localhost/zones/' + domain + './export'
try:
    response = requests.get(
    URL,
    headers = {'accept': 'text/plain', 'X-API-Key': APIKEY_PDNS},
    )
    data = response.text
    #print(data)
    for record in data.split('\n'):
        if '*' in record:
            #print(record)
            wildcard = True
            break
        else:
            wildcard = False
    print('Wildcards found: ', wildcard)
except requests.exceptions.ConnectionError as err:
    print("Connection failed.")
    sys.exit(1)
except requests.exceptions.HTTPError as err:
    print(err)
    sys.exit(1)
print("Patching CAA ...")
URL = ENDPOINT_PDNS + '/api/v1/servers/localhost/zones/' + domain + "."
if wildcard == True:
    issuewild = 'letsencrypt.org'
else:
    issuewild = ';'
payload = {
"rrsets": [{"name": domain + ".", "type": "CAA", "ttl": "3600", "changetype": "REPLACE", "records": [{"content": "0 iodef \"" + iodef + "\"", "disabled": False, "name": domain + "."}, {"content": "0 issue \"" + ca + "\"" , "disabled": False, "name": domain + "."}, {"content": "0 issuewild \"" + issuewild + "\""}]}]
}
response = requests.patch(
URL,
headers = {'accept': 'application/json', 'X-API-Key': APIKEY_PDNS, 'Content-Type': 'application/json'},
json = payload,
)
status = response.status_code
if status == 204:
    print("OK!")
elif status == 422:
    print("Failed:")
    print(response.json())
    sys.exit(1)
else:
    print("Unhandled error.")
    print(status)
    print(response.json())
    sys.exit(1)
sys.exit(0)