]> git.samba.org - obnox/samba/samba-obnox.git/blob - source4/scripting/bin/samba_dnsupdate
s4-dns: added --update-list option to samba_dnsupdate
[obnox/samba/samba-obnox.git] / source4 / scripting / bin / samba_dnsupdate
1 #!/usr/bin/env 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 os
22 import fcntl
23 import sys
24 import tempfile
25
26 # ensure we get messages out immediately, so they get in the samba logs,
27 # and don't get swallowed by a timeout
28 os.putenv('PYTHONUNBUFFERED', '1')
29
30 # Find right directory when running from source tree
31 sys.path.insert(0, "bin/python")
32
33 import samba
34 import optparse
35 from samba import getopt as options
36 from ldb import SCOPE_BASE
37 from samba.auth import system_session
38 from samba.samdb import SamDB
39 from samba.dcerpc import netlogon, winbind
40
41 samba.ensure_external_module("dns", "dnspython")
42 import dns.resolver as resolver
43
44 default_ttl = 900
45 am_rodc = False
46
47 parser = optparse.OptionParser("samba_dnsupdate")
48 sambaopts = options.SambaOptions(parser)
49 parser.add_option_group(sambaopts)
50 parser.add_option_group(options.VersionOptions(parser))
51 parser.add_option("--verbose", action="store_true")
52 parser.add_option("--all-names", action="store_true")
53 parser.add_option("--all-interfaces", action="store_true")
54 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
55 parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
56
57 creds = None
58 ccachename = None
59
60 opts, args = parser.parse_args()
61
62 if len(args) != 0:
63     parser.print_usage()
64     sys.exit(1)
65
66 lp = sambaopts.get_loadparm()
67
68 domain = lp.get("realm")
69 host = lp.get("netbios name")
70 if opts.all_interfaces:
71     all_interfaces = True
72 else:
73     all_interfaces = False
74
75 IPs = samba.interface_ips(lp, all_interfaces)
76 nsupdate_cmd = lp.get('nsupdate command')
77
78 if len(IPs) == 0:
79     print "No IP interfaces - skipping DNS updates"
80     sys.exit(0)
81
82 if opts.verbose:
83     print "IPs: %s" % IPs
84
85 ########################################################
86 # get credentials if we haven't got them already
87 def get_credentials(lp):
88     from samba import credentials
89     global ccachename, creds
90     if creds is not None:
91         return
92     creds = credentials.Credentials()
93     creds.guess(lp)
94     creds.set_machine_account(lp)
95     creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
96     (tmp_fd, ccachename) = tempfile.mkstemp()
97     creds.get_named_ccache(lp, ccachename)
98
99
100 #############################################
101 # an object to hold a parsed DNS line
102 class dnsobj(object):
103     def __init__(self, string_form):
104         list = string_form.split()
105         self.dest = None
106         self.port = None
107         self.ip = None
108         self.existing_port = None
109         self.existing_weight = None
110         self.type = list[0]
111         self.name = list[1].lower()
112         if self.type == 'SRV':
113             self.dest = list[2].lower()
114             self.port = list[3]
115         elif self.type == 'A':
116             self.ip   = list[2] # usually $IP, which gets replaced
117         elif self.type == 'CNAME':
118             self.dest = list[2].lower()
119         else:
120             print "Received unexpected DNS reply of type %s" % self.type
121             raise
122
123     def __str__(self):
124         if d.type == "A":     return "%s %s %s" % (self.type, self.name, self.ip)
125         if d.type == "SRV":   return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
126         if d.type == "CNAME": return "%s %s %s" % (self.type, self.name, self.dest)
127
128
129 ################################################
130 # parse a DNS line from
131 def parse_dns_line(line, sub_vars):
132     subline = samba.substitute_var(line, sub_vars)
133     d = dnsobj(subline)
134     return d
135
136 ############################################
137 # see if two hostnames match
138 def hostname_match(h1, h2):
139     h1 = str(h1)
140     h2 = str(h2)
141     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
142
143
144 ############################################
145 # check that a DNS entry exists
146 def check_dns_name(d):
147     normalised_name = d.name.rstrip('.') + '.'
148     if opts.verbose:
149         print "Looking for DNS entry %s as %s" % (d, normalised_name)
150  
151     if opts.use_file is not None:
152         try:
153             dns_file = open(opts.use_file, "r")
154         except IOError:
155             return False
156         
157         for line in dns_file:
158             line = line.strip()
159             if line == '' or line[0] == "#":
160                 continue
161             if line.lower() == str(d).lower():
162                 return True
163         return False
164
165     try:
166         ans = resolver.query(normalised_name, d.type)
167     except resolver.NXDOMAIN:
168         return False
169     if d.type == 'A':
170         # we need to be sure that our IP is there
171         for rdata in ans:
172             if str(rdata) == str(d.ip):
173                 return True
174     if d.type == 'CNAME':
175         for i in range(len(ans)):
176             if hostname_match(ans[i].target, d.dest):
177                 return True
178     if d.type == 'SRV':
179         for rdata in ans:
180             if opts.verbose:
181                 print "Checking %s against %s" % (rdata, d)
182             if hostname_match(rdata.target, d.dest):
183                 if str(rdata.port) == str(d.port):
184                     return True
185                 else:
186                     d.existing_port     = str(rdata.port)
187                     d.existing_weight = str(rdata.weight)
188     if opts.verbose:
189         print "Failed to find DNS entry %s" % d
190
191     return False
192
193
194 ###########################################
195 # get the list of substitution vars
196 def get_subst_vars():
197     global lp, am_rodc
198     vars = {}
199
200     samdb = SamDB(url=lp.get("sam database"), session_info=system_session(),
201                   lp=lp)
202
203     vars['DNSDOMAIN'] = lp.get('realm').lower()
204     vars['DNSFOREST'] = lp.get('realm').lower()
205     vars['HOSTNAME']  = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
206     vars['NTDSGUID']  = samdb.get_ntds_GUID()
207     vars['SITE']      = samdb.server_site_name()
208     res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
209     guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
210     vars['DOMAINGUID'] = guid
211     am_rodc = samdb.am_rodc()
212
213     return vars
214
215
216 ############################################
217 # call nsupdate for an entry
218 def call_nsupdate(d):
219     global ccachename, nsupdate_cmd
220
221     if opts.verbose:
222         print "Calling nsupdate for %s" % d
223
224     if opts.use_file is not None:
225         wfile = open(opts.use_file, 'a')
226         fcntl.lockf(wfile, fcntl.LOCK_EX)
227         wfile.write(str(d)+"\n")
228         fcntl.lockf(wfile, fcntl.LOCK_UN)
229         return
230
231     normalised_name = d.name.rstrip('.') + '.'
232
233     (tmp_fd, tmpfile) = tempfile.mkstemp()
234     f = os.fdopen(tmp_fd, 'w')
235     if d.type == "A":
236         f.write("update add %s %u A %s\n" % (normalised_name, default_ttl, d.ip))
237     if d.type == "SRV":
238         if d.existing_port is not None:
239             f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
240                                                            d.existing_port, d.dest))
241         f.write("update add %s %u SRV 0 100 %s %s\n" % (normalised_name, default_ttl, d.port, d.dest))
242     if d.type == "CNAME":
243         f.write("update add %s %u CNAME %s\n" % (normalised_name, default_ttl, d.dest))
244     if opts.verbose:
245         f.write("show\n")
246     f.write("send\n")
247     f.close()
248
249     os.putenv("KRB5CCNAME", ccachename)
250     os.system("%s %s" % (nsupdate_cmd, tmpfile))
251     os.unlink(tmpfile)
252
253
254
255 def rodc_dns_update(d, t):
256     '''a single DNS update via the RODC netlogon call'''
257     global sub_vars
258
259     if opts.verbose:
260         print "Calling netlogon RODC update for %s" % d
261
262     typemap = {
263         netlogon.NlDnsLdapAtSite       : netlogon.NlDnsInfoTypeNone,
264         netlogon.NlDnsGcAtSite         : netlogon.NlDnsDomainNameAlias,
265         netlogon.NlDnsDsaCname         : netlogon.NlDnsDomainNameAlias,
266         netlogon.NlDnsKdcAtSite        : netlogon.NlDnsInfoTypeNone,
267         netlogon.NlDnsDcAtSite         : netlogon.NlDnsInfoTypeNone,
268         netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
269         netlogon.NlDnsGenericGcAtSite  : netlogon.NlDnsDomainNameAlias
270         }
271
272     w = winbind.winbind("irpc:winbind_server", lp)
273     dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
274     dns_names.count = 1
275     name = netlogon.NL_DNS_NAME_INFO()
276     name.type = t
277     name.dns_domain_info_type = typemap[t]
278     name.priority = 0
279     name.weight   = 0
280     if d.port is not None:
281         name.port = int(d.port)
282     name.dns_register = True
283     dns_names.names = [ name ]
284     site_name = sub_vars['SITE'].decode('utf-8')
285
286     try:
287         ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
288         if ret_names.names[0].status != 0:
289             print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
290     except RuntimeError, reason:
291         print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
292
293
294 def call_rodc_update(d):
295     '''RODCs need to use the netlogon API for nsupdate'''
296     global lp, sub_vars
297
298     # we expect failure for 3268 if we aren't a GC
299     if d.port is not None and int(d.port) == 3268:
300         return
301
302     # map the DNS request to a netlogon update type
303     map = {
304         netlogon.NlDnsLdapAtSite       : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
305         netlogon.NlDnsGcAtSite         : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
306         netlogon.NlDnsDsaCname         : '${NTDSGUID}._msdcs.${DNSFOREST}',
307         netlogon.NlDnsKdcAtSite        : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
308         netlogon.NlDnsDcAtSite         : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
309         netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
310         netlogon.NlDnsGenericGcAtSite  : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
311         }
312
313     for t in map:
314         subname = samba.substitute_var(map[t], sub_vars)
315         if subname.lower() == d.name.lower():
316             # found a match - do the update
317             rodc_dns_update(d, t)
318             return
319     if opts.verbose:
320         print("Unable to map to netlogon DNS update: %s" % d)
321
322
323 # get the list of DNS entries we should have
324 if opts.update_list:
325     dns_update_list = opts.update_list
326 else:
327     dns_update_list = lp.private_path('dns_update_list')
328
329 # use our private krb5.conf to avoid problems with the wrong domain
330 # bind9 nsupdate wants the default domain set
331 krb5conf = lp.private_path('krb5.conf')
332 os.putenv('KRB5_CONFIG', krb5conf)
333
334 file = open(dns_update_list, "r")
335
336 # get the substitution dictionary
337 sub_vars = get_subst_vars()
338
339 # build up a list of update commands to pass to nsupdate
340 update_list = []
341 dns_list = []
342
343 # read each line, and check that the DNS name exists
344 for line in file:
345     line = line.strip()
346     if line == '' or line[0] == "#":
347         continue
348     d = parse_dns_line(line, sub_vars)
349     dns_list.append(d)
350
351 # now expand the entries, if any are A record with ip set to $IP
352 # then replace with multiple entries, one for each interface IP
353 for d in dns_list:
354     if d.type == 'A' and d.ip == "$IP":
355         d.ip = IPs[0]
356         for i in range(len(IPs)-1):
357             d2 = d
358             d2.ip = IPs[i+1]
359             dns_list.append(d2)
360
361 # now check if the entries already exist on the DNS server
362 for d in dns_list:
363     if opts.all_names or not check_dns_name(d):
364         update_list.append(d)
365
366 if len(update_list) == 0:
367     if opts.verbose:
368         print "No DNS updates needed"
369     sys.exit(0)
370
371 # get our krb5 creds
372 get_credentials(lp)
373
374 # ask nsupdate to add entries as needed
375 for d in update_list:
376     if am_rodc:
377         call_rodc_update(d)
378     else:
379         call_nsupdate(d)
380
381 # delete the ccache if we created it
382 if ccachename is not None:
383     os.unlink(ccachename)