Omitted 2.7 in the python shebang.
[toast/tdyndns.git] / cgi-bin / tdyndns.py
1 #!/usr/bin/python
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 DEBUG = False
17
18
19 # Just for debugging:
20 if DEBUG:
21         import cgitb
22         cgitb.enable()
23
24
25 # Base class for our exceptions
26 class DynDnsError(Exception):
27         pass
28
29 class AuthError(DynDnsError):
30         returncode = 'badauth'
31
32 class CredentialsMissing(AuthError):
33         pass
34
35 class UsernameMissing(AuthError):
36         pass
37
38 class UsernameInvalid(AuthError):
39         pass
40
41 class PasswordMissing(AuthError):
42         pass
43
44 class PasswordWrong(AuthError):
45         pass
46
47 class AuthWrongMethod(AuthError):
48         returncode = 'wrongauthmethod' # not documented at dyn.com
49
50 class AuthBasicError(AuthError):
51         returncode = 'authbasicerror' # not documented at dyn.com
52
53 class HostnameError(DynDnsError):
54         returncode = 'notfqdn'
55
56 class HostnameMissing(HostnameError):
57         pass
58
59 class PasswordWrong(HostnameError):
60         pass
61
62 class MyipError(DynDnsError):
63         returncode = 'badip' # not documented at dyn.com
64
65 class MyipMissing(MyipError):
66         pass
67
68 class MyipInvalid(MyipError):
69         pass
70
71 class OfflineInvalid(DynDnsError):
72         returncode = 'badparam' # not documented at dyn.com
73
74 class NsupdateError(DynDnsError):
75         returncode = 'nohost'
76
77
78 fields = cgi.FieldStorage()
79
80 # the following fields are supported by most dyndns providers
81 # if a parameter is not provided, the .getvalue method returns None
82 username = fields.getvalue('username')
83 password = fields.getvalue('password')
84 hostname = fields.getvalue('hostname')
85 myip     = fields.getvalue('myip')
86 wildcard = fields.getvalue('wildcard')
87 mx       = fields.getvalue('mx')
88 backmx   = fields.getvalue('backmx')
89 offline  = fields.getvalue('offline')
90 system   = fields.getvalue('system')
91 url      = fields.getvalue('url')
92
93
94 try:
95         # Optional Auth Basic
96         auth = os.environ.get('HTTP_AUTHORIZATION') # auth == 'Basic cGhpbGlwcDpka2ZhamRrZg=='
97         if auth: # empty string if HTTP_AUTHORIZATION not present
98                 auth_parts = auth.split(' ')
99                 auth_method = 'Basic'
100                 if len(auth_parts) != 2 or auth_parts[0] != auth_method:
101                         raise AuthWrongMethod()
102                 try:
103                         auth_decoded = base64.b64decode(auth_parts[1]) # auth_decoded == 'philipp:dkfajdkf'
104                 except TypeError:
105                         raise AuthBasicError()
106                 auth_decoded_parts = auth_decoded.split(':')
107                 if len(auth_decoded_parts) != 2:
108                         raise AuthBasicError()
109                 username, password = auth_decoded_parts
110
111         # check username and password
112         if username is None and password is None:
113                 raise CredentialsMissing()
114
115         # check username
116         if username is None:
117                 raise UsernameMissing()
118         try:
119                 user_info = pwd.getpwnam(username)
120         except KeyError:
121                 raise UsernameInvalid()
122         if user_info.pw_uid < 1000:
123                 raise UsernameInvalid()
124
125         # check password
126         if password is None:
127                 raise PasswordMissing()
128         if password != PASSWORD:
129                 raise PasswordWrong()
130
131         # check hostname
132         if hostname is None:
133                 raise HostnameMissing()
134         if re.match(r'[-0-9a-z]+(\.[-0-9a-z]+)*$', hostname) is None:
135                 raise HostnameInvalid()
136
137         # strip zone
138         hostname = hostname.strip()
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                         # try HTTP_X_FORWARDED_FOR
152                         myip = os.environ.get('HTTP_X_FORWARDED_FOR')
153                         if not myip: # empty string if not present
154                                 # try REMOTE_ADDR
155                                 myip = os.environ.get('REMOTE_ADDR')
156                                 if not myip: # empty string if not present
157                                         raise MyipMissing()
158         if not myip is None:
159                 try:
160                         ipaddr.IPAddress(myip) # throws an exception if the IP address is not valid
161                 except ValueError:
162                         raise MyipInvalid()
163
164         # update bind
165         call_params = ['sudo', 'tdyndns_update']
166         if offline:
167                 call_params.append('--delete')
168         if myip is not None:
169                 call_params.extend(['--ip', myip])
170         call_params.append(hostname)
171         retcode = call(call_params)
172         if retcode != 0:
173                 raise NsupdateError()
174
175         # return success
176         print "Content-Type: text/html"
177         print
178         print "good"
179         # Note: we should return 'nochg' in case the IP has not changed, however we don't know yet.
180
181
182 except CredentialsMissing as error:
183         print "Content-Type: text/html"
184         print "Status: 401 Unauthorized"
185         print "WWW-Authenticate: Basic realm='tdyndns'"
186         print
187
188 except DynDnsError as error:
189         print "Content-Type: text/html"
190         print "Status: 200 OK"
191         print
192         print error.returncode
193