s4-dns: add automatic dynamic DNS updating script
[obnox/samba/samba-obnox.git] / source4 / scripting / bin / samba_dnsupdate
1 #!/usr/bin/python
2 #
3 # update our DNS names using TSIG-GSS
4 #
5 # Copyright (C) Andrew Tridgell 2010
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20
21 import getopt
22 import os
23 import sys
24 import dns.resolver
25 import tempfile
26
27 # Find right directory when running from source tree
28 sys.path.insert(0, "bin/python")
29
30 import samba
31 import optparse
32 from samba import getopt as options, Ldb
33 from ldb import SCOPE_SUBTREE, SCOPE_BASE, LdbError
34 import ldb
35 from samba import glue
36 from samba.auth import system_session
37 from samba.samdb import SamDB
38
39 default_ttl = 900
40
41 parser = optparse.OptionParser("samba_dnsupdate")
42 sambaopts = options.SambaOptions(parser)
43 parser.add_option_group(sambaopts)
44 parser.add_option_group(options.VersionOptions(parser))
45 parser.add_option("--verbose", action="store_true")
46
47 creds = None
48 ccachename = None
49
50 opts, args = parser.parse_args()
51
52 if len(args) != 0:
53     parser.print_usage()
54     sys.exit(1)
55
56 lp = sambaopts.get_loadparm()
57
58 domain = lp.get("realm")
59 host = lp.get("netbios name")
60 IPs = glue.interface_ips(lp)
61 nsupdate_cmd = lp.get('nsupdate command')
62
63 if len(IPs) == 0:
64     print "No IP interfaces - skipping DNS updates"
65     sys.exit(0)
66
67
68
69 ########################################################
70 # get credentials if we haven't got them already
71 def get_credentials(lp):
72     from samba.credentials import Credentials
73     global ccachename, creds
74     if creds is not None:
75         return
76     creds = Credentials()
77     creds.guess(lp)
78     try:
79         creds.set_machine_account(lp)
80     except:
81         print "Failed to set machine account"
82         raise
83
84     (tmp_fd, ccachename) = tempfile.mkstemp()
85     creds.get_named_ccache(lp, ccachename)
86
87
88 #############################################
89 # an object to hold a parsed DNS line
90 class dnsobj(object):
91     def __init__(self):
92         self.type = None
93         self.name = None
94         self.dest = None
95         self.port = None
96         self.ip = None
97     def __str__(self):
98         if d.type == "A":     return "%s:%s:%s" % (self.type, self.name, self.ip)
99         if d.type == "SRV":   return "%s:%s:%s:%s" % (self.type, self.name, self.dest, self.port)
100         if d.type == "CNAME": return "%s:%s:%s" % (self.type, self.name, self.dest)
101
102
103 ################################################
104 # parse a DNS line from
105 def parse_dns_line(line, sub_vars):
106     d = dnsobj()
107     subline = samba.substitute_var(line, sub_vars)
108     list = subline.split()
109     d.type = list[0]
110     d.name = list[1]
111     if d.type == 'SRV':
112         d.dest = list[2]
113         d.port = list[3]
114     elif d.type == 'A':
115         d.ip   = list[2] # usually $IP, which gets replaced
116     elif d.type == 'CNAME':
117         d.dest = list[2]
118     else:
119         print "Received unexpected DNS reply of type %s" % d.type
120         raise
121     return d
122
123 ############################################
124 # see if two hostnames match
125 def hostname_match(h1, h2):
126     h1 = str(h1)
127     h2 = str(h2)
128     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
129
130
131 ############################################
132 # check that a DNS entry exists
133 def check_dns_name(d):
134     if opts.verbose:
135         print "Looking for DNS entry %s" % d
136     try:
137         ans = dns.resolver.query(d.name, d.type)
138     except dns.resolver.NXDOMAIN:
139         return False
140     if d.type == 'A':
141         # we need to be sure that our IP is there
142         for rdata in ans:
143             if str(rdata) == str(d.ip):
144                 return True
145     if d.type == 'CNAME':
146         for i in range(len(ans)):
147             if hostname_match(ans[i].target, d.dest):
148                 return True
149     if d.type == 'SRV':
150         if opts.verbose:
151             print "Got %u replies in SRV lookup for %s" % (len(ans), d.name)
152         for i in range(len(ans)):
153             rdata = ans[i]
154             if opts.verbose:
155                 print "Checking %s against %s" % (rdata, d)
156             if str(rdata.port) == str(d.port) and hostname_match(rdata.target, d.dest):
157                 return True
158     if opts.verbose:
159         print "Failed to find DNS entry %s" % d
160     return False
161
162
163 ###########################################
164 # get the list of substitution vars
165 def get_subst_vars():
166     global lp
167     vars = {}
168
169     samdb = SamDB(url=lp.get("sam database"), session_info=system_session(), lp=lp)
170
171     vars['DNSDOMAIN'] = lp.get('realm').lower()
172     vars['HOSTNAME']  = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
173     vars['NTDSGUID']  = samdb.get_ntds_GUID()
174     vars['SITE']      = samdb.server_site_name()
175     res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
176     guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
177     vars['DOMAINGUID'] = guid
178     return vars
179
180
181 ############################################
182 # call nsupdate for an entry
183 def call_nsupdate(d):
184     global ccachename, nsupdate_cmd
185
186     if opts.verbose:
187         print "Calling nsupdate for %s" % d
188     (tmp_fd, tmpfile) = tempfile.mkstemp()
189     f = os.fdopen(tmp_fd, 'w')
190     if d.type == "A":
191         f.write("update add %s %u A %s\n" % (d.name, default_ttl, d.ip))
192     if d.type == "SRV":
193         f.write("update add %s %u SRV 0 100 %s %s\n" % (d.name, default_ttl, d.port, d.dest))
194     if d.type == "CNAME":
195         f.write("update add %s %u SRV %s\n" % (d.name, default_ttl, d.dest))
196     if opts.verbose:
197         f.write("show\n")
198     f.write("send\n")
199     f.close()
200
201     os.putenv("KRB5CCNAME", ccachename)
202     os.system("%s %s" % (nsupdate_cmd, tmpfile))
203     os.unlink(tmpfile)
204
205
206 # get the list of DNS entries we should have
207 dns_update_list = lp.private_path('dns_update_list')
208
209 file = open(dns_update_list, "r")
210
211 # get the substitution dictionary
212 sub_vars = get_subst_vars()
213
214 # build up a list of update commands to pass to nsupdate
215 update_list = []
216 dns_list = []
217
218 # read each line, and check that the DNS name exists
219 line = file.readline()
220 while line:
221     line = line.rstrip().lstrip()
222     if line[0] == "#":
223         line = file.readline()
224         continue
225     d = parse_dns_line(line, sub_vars)
226     dns_list.append(d)
227     line = file.readline()
228
229 # now expand the entries, if any are A record with ip set to $IP
230 # then replace with multiple entries, one for each interface IP
231 for d in dns_list:
232     if d.type == 'A' and d.ip == "$IP":
233         d.ip = IPs[0]
234         for i in range(len(IPs)-1):
235             d2 = d
236             d2.ip = IPs[i+1]
237             dns_list.append(d2)
238
239 # now check if the entries already exist on the DNS server
240 for d in dns_list:
241     if not check_dns_name(d):
242         update_list.append(d)
243
244 if len(update_list) == 0:
245     if opts.verbose:
246         print "No DNS updates needed"
247     sys.exit(0)
248
249 # get our krb5 creds
250 get_credentials(lp)
251
252 # ask nsupdate to add entries as needed
253 for d in update_list:
254     call_nsupdate(d)
255
256 # delete the ccache if we created it
257 if ccachename is not None:
258     os.unlink(ccachename)
259
260