4 # update our DNS names using TSIG-GSS
6 # Copyright (C) Andrew Tridgell 2010
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
28 # ensure we get messages out immediately, so they get in the samba logs,
29 # and don't get swallowed by a timeout
30 os
.environ
['PYTHONUNBUFFERED'] = '1'
32 # forcing GMT avoids a problem in some timezones with kerberos. Both MIT
33 # heimdal can get mutual authentication errors due to the 24 second difference
34 # between UTC and GMT when using some zone files (eg. the PDT zone from
36 os
.environ
["TZ"] = "GMT"
38 # Find right directory when running from source tree
39 sys
.path
.insert(0, "bin/python")
43 from samba
import getopt
as options
44 from ldb
import SCOPE_BASE
45 from samba
.auth
import system_session
46 from samba
.samdb
import SamDB
47 from samba
.dcerpc
import netlogon
, winbind
49 samba
.ensure_external_module("dns", "dnspython")
57 parser
= optparse
.OptionParser("samba_dnsupdate")
58 sambaopts
= options
.SambaOptions(parser
)
59 parser
.add_option_group(sambaopts
)
60 parser
.add_option_group(options
.VersionOptions(parser
))
61 parser
.add_option("--verbose", action
="store_true")
62 parser
.add_option("--all-names", action
="store_true")
63 parser
.add_option("--all-interfaces", action
="store_true")
64 parser
.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
65 parser
.add_option("--update-list", type="string", help="Add DNS names from the given file")
66 parser
.add_option("--update-cache", type="string", help="Cache database of already registered records")
67 parser
.add_option("--fail-immediately", action
='store_true', help="Exit on first failure")
68 parser
.add_option("--no-credentials", dest
='nocreds', action
='store_true', help="don't try and get credentials")
69 parser
.add_option("--no-substiutions", dest
='nosubs', action
='store_true', help="don't try and expands variables in file specified by --update-list")
74 opts
, args
= parser
.parse_args()
80 lp
= sambaopts
.get_loadparm()
82 domain
= lp
.get("realm")
83 host
= lp
.get("netbios name")
84 if opts
.all_interfaces
:
87 all_interfaces
= False
89 IPs
= samba
.interface_ips(lp
, all_interfaces
)
90 nsupdate_cmd
= lp
.get('nsupdate command')
93 print "No IP interfaces - skipping DNS updates"
106 print "IPs: %s" % IPs
109 def get_credentials(lp
):
110 """# get credentials if we haven't got them already."""
111 from samba
import credentials
112 global ccachename
, creds
113 if creds
is not None:
115 creds
= credentials
.Credentials()
117 creds
.set_machine_account(lp
)
118 creds
.set_krb_forwardable(credentials
.NO_KRB_FORWARDABLE
)
119 (tmp_fd
, ccachename
) = tempfile
.mkstemp()
121 creds
.get_named_ccache(lp
, ccachename
)
122 except RuntimeError as e
:
123 os
.unlink(ccachename
)
127 class dnsobj(object):
128 """an object to hold a parsed DNS line"""
130 def __init__(self
, string_form
):
131 list = string_form
.split()
133 raise Exception("Invalid DNS entry %r" % string_form
)
137 self
.existing_port
= None
138 self
.existing_weight
= None
141 if self
.type == 'SRV':
143 raise Exception("Invalid DNS entry %r" % string_form
)
146 elif self
.type in ['A', 'AAAA']:
147 self
.ip
= list[2] # usually $IP, which gets replaced
148 elif self
.type == 'CNAME':
150 elif self
.type == 'NS':
153 raise Exception("Received unexpected DNS reply of type %s: %s" % (self
.type, string_form
))
157 return "%s %s %s" % (self
.type, self
.name
, self
.ip
)
158 if self
.type == "AAAA":
159 return "%s %s %s" % (self
.type, self
.name
, self
.ip
)
160 if self
.type == "SRV":
161 return "%s %s %s %s" % (self
.type, self
.name
, self
.dest
, self
.port
)
162 if self
.type == "CNAME":
163 return "%s %s %s" % (self
.type, self
.name
, self
.dest
)
164 if self
.type == "NS":
165 return "%s %s %s" % (self
.type, self
.name
, self
.dest
)
168 def parse_dns_line(line
, sub_vars
):
169 """parse a DNS line from."""
170 if line
.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb
.am_pdc():
172 print "Skipping PDC entry (%s) as we are not a PDC" % line
174 subline
= samba
.substitute_var(line
, sub_vars
)
175 return dnsobj(subline
)
178 def hostname_match(h1
, h2
):
179 """see if two hostnames match."""
182 return h1
.lower().rstrip('.') == h2
.lower().rstrip('.')
185 def check_dns_name(d
):
186 """check that a DNS entry exists."""
187 normalised_name
= d
.name
.rstrip('.') + '.'
189 print "Looking for DNS entry %s as %s" % (d
, normalised_name
)
191 if opts
.use_file
is not None:
193 dns_file
= open(opts
.use_file
, "r")
197 for line
in dns_file
:
199 if line
== '' or line
[0] == "#":
201 if line
.lower() == str(d
).lower():
205 resolver
= dns
.resolver
.Resolver()
208 if getattr(d
, 'nameservers', None):
209 resolver
.nameservers
= list(d
.nameservers
)
210 ans
= resolver
.query(normalised_name
, d
.type)
211 except dns
.exception
.DNSException
:
213 print "Failed to find DNS entry %s" % d
215 if d
.type in ['A', 'AAAA']:
216 # we need to be sure that our IP is there
218 if str(rdata
) == str(d
.ip
):
220 elif d
.type == 'CNAME':
221 for i
in range(len(ans
)):
222 if hostname_match(ans
[i
].target
, d
.dest
):
225 for i
in range(len(ans
)):
226 if hostname_match(ans
[i
].target
, d
.dest
):
228 elif d
.type == 'SRV':
231 print "Checking %s against %s" % (rdata
, d
)
232 if hostname_match(rdata
.target
, d
.dest
):
233 if str(rdata
.port
) == str(d
.port
):
236 d
.existing_port
= str(rdata
.port
)
237 d
.existing_weight
= str(rdata
.weight
)
240 print "Failed to find matching DNS entry %s" % d
245 def get_subst_vars(samdb
):
246 """get the list of substitution vars."""
250 vars['DNSDOMAIN'] = samdb
.domain_dns_name()
251 vars['DNSFOREST'] = samdb
.forest_dns_name()
252 vars['HOSTNAME'] = samdb
.host_dns_name()
253 vars['NTDSGUID'] = samdb
.get_ntds_GUID()
254 vars['SITE'] = samdb
.server_site_name()
255 res
= samdb
.search(base
=samdb
.get_default_basedn(), scope
=SCOPE_BASE
, attrs
=["objectGUID"])
256 guid
= samdb
.schema_format_value("objectGUID", res
[0]['objectGUID'][0])
257 vars['DOMAINGUID'] = guid
258 am_rodc
= samdb
.am_rodc()
263 def call_nsupdate(d
, op
="add"):
264 """call nsupdate for an entry."""
265 global ccachename
, nsupdate_cmd
, krb5conf
267 assert(op
in ["add", "delete"])
270 print "Calling nsupdate for %s (%s)" % (d
, op
)
272 if opts
.use_file
is not None:
274 rfile
= open(opts
.use_file
, 'r+')
277 rfile
= open(opts
.use_file
, 'w+')
278 # Open it for reading again, in case someone else got to it first
279 rfile
= open(opts
.use_file
, 'r+')
280 fcntl
.lockf(rfile
, fcntl
.LOCK_EX
)
281 (file_dir
, file_name
) = os
.path
.split(opts
.use_file
)
282 (tmp_fd
, tmpfile
) = tempfile
.mkstemp(dir=file_dir
, prefix
=file_name
, suffix
="XXXXXX")
283 wfile
= os
.fdopen(tmp_fd
, 'a')
287 l
= parse_dns_line(line
, {})
288 if str(l
).lower() == str(d
).lower():
292 wfile
.write(str(d
)+"\n")
293 os
.rename(tmpfile
, opts
.use_file
)
294 fcntl
.lockf(rfile
, fcntl
.LOCK_UN
)
297 normalised_name
= d
.name
.rstrip('.') + '.'
299 (tmp_fd
, tmpfile
) = tempfile
.mkstemp()
300 f
= os
.fdopen(tmp_fd
, 'w')
301 if getattr(d
, 'nameservers', None):
302 f
.write('server %s\n' % d
.nameservers
[0])
304 f
.write("update %s %s %u A %s\n" % (op
, normalised_name
, default_ttl
, d
.ip
))
306 f
.write("update %s %s %u AAAA %s\n" % (op
, normalised_name
, default_ttl
, d
.ip
))
308 if op
== "add" and d
.existing_port
is not None:
309 f
.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name
, d
.existing_weight
,
310 d
.existing_port
, d
.dest
))
311 f
.write("update %s %s %u SRV 0 100 %s %s\n" % (op
, normalised_name
, default_ttl
, d
.port
, d
.dest
))
312 if d
.type == "CNAME":
313 f
.write("update %s %s %u CNAME %s\n" % (op
, normalised_name
, default_ttl
, d
.dest
))
315 f
.write("update %s %s %u NS %s\n" % (op
, normalised_name
, default_ttl
, d
.dest
))
323 os
.environ
["KRB5CCNAME"] = ccachename
325 cmd
= nsupdate_cmd
[:]
329 env
["KRB5_CONFIG"] = krb5conf
331 env
["KRB5CCNAME"] = ccachename
332 ret
= subprocess
.call(cmd
, shell
=False, env
=env
)
334 if opts
.fail_immediately
:
336 print("Failed update with %s" % tmpfile
)
338 error_count
= error_count
+ 1
340 print("Failed nsupdate: %d" % ret
)
341 except Exception, estr
:
342 if opts
.fail_immediately
:
344 error_count
= error_count
+ 1
346 print("Failed nsupdate: %s : %s" % (str(d
), estr
))
351 def rodc_dns_update(d
, t
, op
):
352 '''a single DNS update via the RODC netlogon call'''
355 assert(op
in ["add", "delete"])
358 print "Calling netlogon RODC update for %s" % d
361 netlogon
.NlDnsLdapAtSite
: netlogon
.NlDnsInfoTypeNone
,
362 netlogon
.NlDnsGcAtSite
: netlogon
.NlDnsDomainNameAlias
,
363 netlogon
.NlDnsDsaCname
: netlogon
.NlDnsDomainNameAlias
,
364 netlogon
.NlDnsKdcAtSite
: netlogon
.NlDnsInfoTypeNone
,
365 netlogon
.NlDnsDcAtSite
: netlogon
.NlDnsInfoTypeNone
,
366 netlogon
.NlDnsRfc1510KdcAtSite
: netlogon
.NlDnsInfoTypeNone
,
367 netlogon
.NlDnsGenericGcAtSite
: netlogon
.NlDnsDomainNameAlias
370 w
= winbind
.winbind("irpc:winbind_server", lp
)
371 dns_names
= netlogon
.NL_DNS_NAME_INFO_ARRAY()
373 name
= netlogon
.NL_DNS_NAME_INFO()
375 name
.dns_domain_info_type
= typemap
[t
]
378 if d
.port
is not None:
379 name
.port
= int(d
.port
)
381 name
.dns_register
= True
383 name
.dns_register
= False
384 dns_names
.names
= [ name
]
385 site_name
= sub_vars
['SITE'].decode('utf-8')
390 ret_names
= w
.DsrUpdateReadOnlyServerDnsRecords(site_name
, default_ttl
, dns_names
)
391 if ret_names
.names
[0].status
!= 0:
392 print("Failed to set DNS entry: %s (status %u)" % (d
, ret_names
.names
[0].status
))
393 error_count
= error_count
+ 1
394 except RuntimeError, reason
:
395 print("Error setting DNS entry of type %u: %s: %s" % (t
, d
, reason
))
396 error_count
= error_count
+ 1
398 if error_count
!= 0 and opts
.fail_immediately
:
402 def call_rodc_update(d
, op
="add"):
403 '''RODCs need to use the netlogon API for nsupdate'''
406 assert(op
in ["add", "delete"])
408 # we expect failure for 3268 if we aren't a GC
409 if d
.port
is not None and int(d
.port
) == 3268:
412 # map the DNS request to a netlogon update type
414 netlogon
.NlDnsLdapAtSite
: '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
415 netlogon
.NlDnsGcAtSite
: '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
416 netlogon
.NlDnsDsaCname
: '${NTDSGUID}._msdcs.${DNSFOREST}',
417 netlogon
.NlDnsKdcAtSite
: '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
418 netlogon
.NlDnsDcAtSite
: '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
419 netlogon
.NlDnsRfc1510KdcAtSite
: '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
420 netlogon
.NlDnsGenericGcAtSite
: '_gc._tcp.${SITE}._sites.${DNSFOREST}'
424 subname
= samba
.substitute_var(map[t
], sub_vars
)
425 if subname
.lower() == d
.name
.lower():
426 # found a match - do the update
427 rodc_dns_update(d
, t
, op
)
430 print("Unable to map to netlogon DNS update: %s" % d
)
433 # get the list of DNS entries we should have
435 dns_update_list
= opts
.update_list
437 dns_update_list
= lp
.private_path('dns_update_list')
439 if opts
.update_cache
:
440 dns_update_cache
= opts
.update_cache
442 dns_update_cache
= lp
.private_path('dns_update_cache')
444 # use our private krb5.conf to avoid problems with the wrong domain
445 # bind9 nsupdate wants the default domain set
446 krb5conf
= lp
.private_path('krb5.conf')
447 os
.environ
['KRB5_CONFIG'] = krb5conf
449 file = open(dns_update_list
, "r")
454 samdb
= SamDB(url
=lp
.samdb_url(), session_info
=system_session(), lp
=lp
)
456 # get the substitution dictionary
457 sub_vars
= get_subst_vars(samdb
)
459 # build up a list of update commands to pass to nsupdate
468 rebuild_cache
= False
470 cfile
= open(dns_update_cache
, 'r+')
473 cfile
= open(dns_update_cache
, 'w+')
474 # Open it for reading again, in case someone else got to it first
475 cfile
= open(dns_update_cache
, 'r+')
476 fcntl
.lockf(cfile
, fcntl
.LOCK_EX
)
479 if line
== '' or line
[0] == "#":
481 c
= parse_dns_line(line
, {})
484 if str(c
) not in cache_set
:
486 cache_set
.add(str(c
))
488 # read each line, and check that the DNS name exists
491 if line
== '' or line
[0] == "#":
493 d
= parse_dns_line(line
, sub_vars
)
496 if d
.type == 'A' and len(IP4s
) == 0:
498 if d
.type == 'AAAA' and len(IP6s
) == 0:
500 if str(d
) not in dup_set
:
504 # now expand the entries, if any are A record with ip set to $IP
505 # then replace with multiple entries, one for each interface IP
511 for i
in range(len(IP4s
)-1):
517 for i
in range(len(IP6s
)-1):
522 # now check if the entries already exist on the DNS server
526 if str(c
).lower() == str(d
).lower():
531 if opts
.all_names
or not check_dns_name(d
):
532 update_list
.append(d
)
537 if str(c
).lower() == str(d
).lower():
543 if not opts
.all_names
and not check_dns_name(c
):
545 delete_list
.append(c
)
547 if len(delete_list
) == 0 and len(update_list
) == 0 and not rebuild_cache
:
549 print "No DNS updates needed"
553 if len(delete_list
) != 0 or len(update_list
) != 0:
557 # ask nsupdate to delete entries as needed
558 for d
in delete_list
:
560 if d
.name
.lower() == domain
.lower():
562 if not d
.type in [ 'A', 'AAAA' ]:
563 call_rodc_update(d
, op
="delete")
565 call_nsupdate(d
, op
="delete")
567 call_nsupdate(d
, op
="delete")
569 # ask nsupdate to add entries as needed
570 for d
in update_list
:
572 if d
.name
.lower() == domain
.lower():
574 if not d
.type in [ 'A', 'AAAA' ]:
582 (file_dir
, file_name
) = os
.path
.split(dns_update_cache
)
583 (tmp_fd
, tmpfile
) = tempfile
.mkstemp(dir=file_dir
, prefix
=file_name
, suffix
="XXXXXX")
584 wfile
= os
.fdopen(tmp_fd
, 'a')
586 wfile
.write(str(d
)+"\n")
587 os
.rename(tmpfile
, dns_update_cache
)
588 fcntl
.lockf(cfile
, fcntl
.LOCK_UN
)
590 # delete the ccache if we created it
591 if ccachename
is not None:
592 os
.unlink(ccachename
)
595 print("Failed update of %u entries" % error_count
)
596 sys
.exit(error_count
)