Fixed bug: Some exceptions were not caught.
[toast/tdyndns.git] / cgi-bin / dyndns.py
1 #!/usr/bin/python2.7
2 """Dynamic DNS script. Expects URLs from routers in the form
3 http://dyndns.colgarra.priv.at/nic/update?username=<username>&password=<pass>&hostname=<domain>&myip=<ipaddr>
4 """
5 import os
6 import re
7 import cgi
8 import pwd
9 import base64
10 from subprocess import call
11 import ipaddr
12
13
14 # Configuration
15 PASSWORD = 'hygCithOrs5'
16 ZONE = '.dyn.colgarra.priv.at'
17 DEBUG = False
18
19
20 # Just for debugging:
21 if DEBUG:
22         import cgitb
23         cgitb.enable()
24
25
26 # Base class for our exceptions
27 class DynDnsError(Exception):
28         pass
29
30 class AuthError(DynDnsError):
31         returncode = 'badauth'
32
33 class CredentialsMissing(AuthError):
34         pass
35
36 class UsernameMissing(AuthError):
37         pass
38
39 class UsernameInvalid(AuthError):
40         pass
41
42 class PasswordMissing(AuthError):
43         pass
44
45 class PasswordWrong(AuthError):
46         pass
47
48 class AuthWrongMethod(AuthError):
49         returncode = 'wrongauthmethod' # not documented at dyn.com
50
51 class AuthBasicError(AuthError):
52         returncode = 'authbasicerror' # not documented at dyn.com
53
54 class HostnameError(DynDnsError):
55         returncode = 'notfqdn'
56
57 class HostnameMissing(HostnameError):
58         pass
59
60 class PasswordWrong(HostnameError):
61         pass
62
63 class MyipError(DynDnsError):
64         returncode = 'badip' # not documented at dyn.com
65
66 class MyipMissing(MyipError):
67         pass
68
69 class MyipInvalid(MyipError):
70         pass
71
72 class OfflineInvalid(DynDnsError):
73         returncode = 'badparam' # not documented at dyn.com
74
75
76 fields = cgi.FieldStorage()
77
78 # the following fields are supported by most dyndns providers
79 # if a parameter is not provided, the .getvalue method returns None
80 username = fields.getvalue('username')
81 password = fields.getvalue('password')
82 hostname = fields.getvalue('hostname')
83 myip     = fields.getvalue('myip')
84 wildcard = fields.getvalue('wildcard')
85 mx       = fields.getvalue('mx')
86 backmx   = fields.getvalue('backmx')
87 offline  = fields.getvalue('offline')
88 system   = fields.getvalue('system')
89 url      = fields.getvalue('url')
90
91
92 try:
93         # Optional Auth Basic
94         auth = os.environ.get('HTTP_AUTHORIZATION') # auth == 'Basic cGhpbGlwcDpka2ZhamRrZg=='
95         if auth: # empty string if HTTP_AUTHORIZATION not present
96                 auth_parts = auth.split(' ')
97                 auth_method = 'Basic'
98                 if len(auth_parts) != 2 or auth_parts[0] != auth_method:
99                         raise AuthWrongMethod()
100                 try:
101                         auth_decoded = base64.b64decode(auth_parts[1]) # auth_decoded == 'philipp:dkfajdkf'
102                 except TypeError:
103                         raise AuthBasicError()
104                 auth_decoded_parts = auth_decoded.split(':')
105                 if len(auth_decoded_parts) != 2:
106                         raise AuthBasicError()
107                 username, password = auth_decoded_parts
108
109         # check username and password
110         if username is None and password is None:
111                 raise CredentialsMissing()
112
113         # check username
114         if username is None:
115                 raise UsernameMissing()
116         try:
117                 user_info = pwd.getpwnam(username)
118         except KeyError:
119                 raise UsernameInvalid()
120         if user_info.pw_uid < 1000:
121                 raise UsernameInvalid()
122
123         # check password
124         if password is None:
125                 raise PasswordMissing()
126         if password != PASSWORD:
127                 raise PasswordWrong()
128
129         # check hostname
130         if hostname is None:
131                 raise HostnameMissing()
132         if re.match(r'[-0-9a-z]+(\.[-0-9a-z]+)*$', hostname) is None:
133                 raise HostnameInvalid()
134
135         # strip zone
136         hostname = hostname.strip()
137         if hostname.endswith(ZONE):
138                 hostname = hostname[:-len(ZONE)]
139
140         # check offline
141         if offline is None or offline.lower() == 'no':
142                 offline = False
143         elif offline.lower() == 'yes':
144                 offline = True
145         else:
146                 raise OfflineInvalid()
147
148         # check IP address
149         if not offline:
150                 if myip is None:
151                         raise MyipMissing()
152                 try:
153                         ip = ipaddr.IPAddress(myip) # throws an exception if the IP address is not valid
154                 except ValueError:
155                         raise MyipInvalid()
156                 if isinstance(ip, ipaddr.IPv4Address):
157                         iptype = 'A'
158                 elif isinstance(ip, ipaddr.IPv6Address):
159                         iptype = 'AAAA'
160                 else:
161                         raise MyipInvalid() # should never happen
162
163         # update bind
164         if offline:
165                 call(['sudo', '/usr/local/bin/nsupdate_dyndns', '--delete', hostname])
166         else:
167                 call(['sudo', '/usr/local/bin/nsupdate_dyndns', '--ip', myip, hostname])
168
169         # return success
170         print "Content-Type: text/html"
171         print
172         print "good"
173         # Note: we should return 'nochg' in case the IP has not changed, however we don't know yet.
174
175
176 except CredentialsMissing as error:
177         print "Content-Type: text/html"
178         print "Status: 401 Unauthorized"
179         print "WWW-Authenticate: Basic realm='tdyndns'"
180         print
181
182 except DynDnsError as error:
183         print "Content-Type: text/html"
184         print "Status: 200 OK"
185         print
186         print error.returncode
187