Moved hostname handling into try block to avoid an unhandled exception in case of...
[toast/tdyndns.git] / cgi-bin / dyndns.py
1 #!/usr/bin/python2.7
2 """Dynamic DNS script. Expects URLs from routers in the form
3 https://info.colgarra.priv.at/dyndns/dyndns.py?username=<username>&password=<pass>&hostname=<domain>&myip=<ipaddr>
4 """
5
6 import re
7 import cgi
8 import pwd
9 from subprocess import call
10 import ipaddr
11
12
13 # Configuration
14 PASSWORD = 'hygCithOrs5'
15 ZONE = '.dyn.colgarra.priv.at'
16
17
18 # Just for debugging:
19 # import cgitb
20 # cgitb.enable()
21
22
23 fields = cgi.FieldStorage()
24
25 # the following fields are supported by most dyndns providers
26 # if a parameter is not provided, the .getvalue method returns None
27 username = fields.getvalue('username')
28 password = fields.getvalue('password')
29 hostname = fields.getvalue('hostname')
30 myip     = fields.getvalue('myip')
31 wildcard = fields.getvalue('wildcard')
32 mx       = fields.getvalue('mx')
33 backmx   = fields.getvalue('backmx')
34 offline  = fields.getvalue('offline')
35
36
37 try:
38         # check username
39         user_info = pwd.getpwnam(username) # returns a key error if the user does not exist
40         if user_info.pw_uid < 1000:
41                 raise RuntimeError('Invalid user name')
42
43         # check password
44         if password != PASSWORD:
45                 raise RuntimeError('Invalid password')
46
47         # check hostname
48         if re.match(r'[-0-9a-z]+(\.[-0-9a-z]+)*$', hostname) is None:
49                 raise RuntimeError('Invalid host name')
50
51         # strip zone
52         hostname = hostname.strip()
53         if hostname.endswith(ZONE):
54                 hostname = hostname[:-len(ZONE)]
55
56         # check IP address
57         ip = ipaddr.IPAddress(myip) # throws axception if the IP address is not valid
58         if isinstance(ip, ipaddr.IPv4Address):
59                 type = 'A'
60         elif isinstance(ip, ipaddr.IPv6Address):
61                 type = 'AAAA'
62         else:
63                 raise RuntimeError('Unknown IP address type')
64
65         # access granted
66         print "Content-Type: text/html"
67         print
68         call(['sudo', '/usr/local/bin/nsupdate_dyndns', hostname, myip, type])
69         print "OK"
70
71
72 except:
73         # access denied
74         print "Content-Type: text/html"
75         print "Status: 403 Forbidden"
76         print
77         print "Denied"
78