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
|
#!/usr/bin/env python
import os
import json
import boto3
import flask
import hashlib
import functools
# pip install flask boto3
# This is purely for documentation purposes
__REQUIRED_IAM_POLICY__ = """
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ssm:GetParameter",
"Resource": "arn:aws:ssm:us-west-2::parameter/DDNS_CLIENTS"
},
{
"Effect": "Allow",
"Action": [
"route53:ListHostedZones",
"route53:ChangeResourceRecordSets"
],
"Resource": "*"
}
]
}
"""
app = flask.Flask(__name__)
def returns_plain_text(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return flask.Response(f(*args, **kwargs), content_type="text/plain")
return wrapper
def get_ip():
if "X-Forwarded-For" in flask.request.headers:
return flask.request.headers["X-Forwarded-For"]
else:
return flask.request.remote_addr
def update_record(zone, record, ip):
client = boto3.client("route53")
zones = client.list_hosted_zones()["HostedZones"]
client.change_resource_record_sets(
HostedZoneId=[z["Id"] for z in zones if z["Name"] == zone][0],
ChangeBatch={
"Changes": [{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": ".".join((record, zone)),
"Type": "A",
"TTL": 60,
"ResourceRecords": [{
"Value": ip,
}]
}
}]
}
)
@app.errorhandler(404)
@app.errorhandler(405)
@app.errorhandler(500)
def handle_error(ex):
response = flask.Response("Error", content_type="text/plain")
response.status_code = getattr(ex, "code", 500)
return response
@app.route("/new-secret", methods=["GET"])
@returns_plain_text
def new_secret():
return hashlib.sha256(os.urandom(100)).hexdigest()
def get_client_config(client):
ssm = boto3.client("ssm")
clients = ssm.get_parameter(Name="DDNS_CLIENTS", WithDecryption=True)
config = json.loads(clients["Parameter"]["Value"])
return config.get(client)
@app.route("/update", methods=["POST"])
def update_ip():
key = flask.request.form.get("key")
config = get_client_config(key)
if not config:
flask.abort(404)
resource, zone = config.split(".", 1)
try:
update_record(zone, resource, get_ip())
return "OK"
except:
flask.abort(500)
@app.route("/", methods=["GET"])
@returns_plain_text
def handle_home():
return get_ip()
if __name__ == "__main__":
app.debug = True
app.run()
|