-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathdyndns53.py
181 lines (146 loc) · 4.38 KB
/
dyndns53.py
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import print_function
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
import json
import re
import sys
import boto3
class AuthorizationMissing(Exception):
status = 401
response = {"WWW-Authenticate":"Basic realm=dyndns53"}
class HostnameException(Exception):
status = 404
response = "nohost"
class AuthorizationException(Exception):
status = 403
response = "badauth"
class FQDNException(Exception):
status = 400
response = "notfqdn"
class BadAgentException(Exception):
status = 400
response = "badagent"
class AbuseException(Exception):
status = 403
response = "abuse"
conf = {
'<username>:<password>': {
'hosts': {
'<host.example.com.>': {
'aws_region': 'us-west-2',
'zone_id': '<MY_ZONE_ID>',
'record': {
'ttl': 60,
'type': 'A',
},
'last_update': None,
},
},
},
}
re_ip = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$")
def _parse_ip(ipstring):
m = re_ip.match(ipstring)
if bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups())):
return ipstring
else:
raise BadAgentException("Invalid IP string: {}".format(ipstring))
client53 = boto3.client('route53','us-west-2')
def r53_upsert(host, hostconf, ip):
record_type = hostconf['record']['type']
record_set = client53.list_resource_record_sets(
HostedZoneId=hostconf['zone_id'],
StartRecordName=host,
StartRecordType=record_type,
MaxItems='1'
)
old_ip = None
if not record_set:
msg = "No existing record found for host {} in zone {}"
logger.info(msg.format(host, hostconf['zone_id']))
else:
record = record_set['ResourceRecordSets'][0]
if record['Name'] == host and record['Type'] == record_type:
if len(record['ResourceRecords']) == 1:
for subrecord in record['ResourceRecords']:
old_ip = subrecord['Value']
else:
msg = "Multiple existing records found for host {} in zone {}"
raise ValueError(msg.format(host, hostconf['zone_id']))
else:
msg = "No existing record found for host {} in zone {}"
logger.info(msg.format(host, hostconf['zone_id']))
if old_ip == ip:
logger.debug("Old IP same as new IP: {}".format(ip))
return False
logger.debug("Old IP was: {}".format(old_ip))
return_status = client53.change_resource_record_sets(
HostedZoneId=hostconf['zone_id'],
ChangeBatch={
'Changes': [
{
'Action': 'UPSERT',
'ResourceRecordSet': {
'Name': host,
'Type': hostconf['record']['type'],
'TTL': hostconf['record']['ttl'],
'ResourceRecords': [
{
'Value': ip
}
]
}
}
]
}
)
return True
def _handler(event, context):
if 'header' not in event:
msg = "Headers not populated properly. Check API Gateway configuration."
raise KeyError(msg)
try:
auth_header = event['header']['Authorization']
except KeyError as e:
raise AuthorizationMissing("Authorization required but not provided.")
try:
auth_user, auth_pass = (
auth_header[len('Basic '):].decode('base64').split(':') )
except Exception as e:
msg = "Malformed basicauth string: {}"
raise BadAgentException(msg.format(event['header']['Authorization']))
auth_string = ':'.join([auth_user,auth_pass])
if auth_string not in conf:
raise AuthorizationException("Bad username/password.")
try:
hosts = set( h if h.endswith('.') else h+'.' for h in
event['querystring']['hostname'].split(',') )
except KeyError as e:
raise BadAgentException("Hostname(s) required but not provided.")
if any(host not in conf[auth_string]['hosts'] for host in hosts):
raise HostnameException()
try:
ip = _parse_ip(event['querystring']['myip'])
logger.debug("User supplied IP address: {}".format(ip))
except KeyError as e:
ip = _parse_ip(event['context']['source-ip'])
msg = "User omitted IP address, using best-guess from $context: {}"
logger.debug(msg.format(ip))
if any(r53_upsert(host,conf[auth_string]['hosts'][host],ip) for host in hosts):
return "good {}".format(ip)
else:
return "nochg {}".format(ip)
def lambda_handler(event, context):
try:
response = _handler(event, context)
except Exception as e:
try:
j = {'status':e.status, 'response':e.response, 'additional':e.message}
except AttributeError as f:
j = {'status':500, 'response':"911", 'additional':str(e)}
finally:
raise type(e), type(e)(json.dumps(j)), sys.exc_info()[2]
return { 'status': 200, 'response': response }