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