3 # update our DNS names using TSIG-GSS
5 # Copyright (C) Andrew Tridgell 2010
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.
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.
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/>.
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')
30 # Find right directory when running from source tree
31 sys.path.insert(0, "bin/python")
35 from samba import getopt as options
36 from ldb import SCOPE_BASE
37 from samba import glue
38 from samba.auth import system_session
39 from samba.samdb import SamDB
41 samba.ensure_external_module("dns.resolver", "dnspython")
42 import dns.resolver as resolver
46 parser = optparse.OptionParser("samba_dnsupdate")
47 sambaopts = options.SambaOptions(parser)
48 parser.add_option_group(sambaopts)
49 parser.add_option_group(options.VersionOptions(parser))
50 parser.add_option("--verbose", action="store_true")
51 parser.add_option("--all-interfaces", action="store_true")
52 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
57 opts, args = parser.parse_args()
63 lp = sambaopts.get_loadparm()
65 domain = lp.get("realm")
66 host = lp.get("netbios name")
67 if opts.all_interfaces:
70 all_interfaces = False
72 IPs = glue.interface_ips(lp, all_interfaces)
73 nsupdate_cmd = lp.get('nsupdate command')
76 print "No IP interfaces - skipping DNS updates"
81 ########################################################
82 # get credentials if we haven't got them already
83 def get_credentials(lp):
84 from samba.credentials import Credentials
85 global ccachename, creds
91 creds.set_machine_account(lp)
93 print "Failed to set machine account"
96 (tmp_fd, ccachename) = tempfile.mkstemp()
97 creds.get_named_ccache(lp, ccachename)
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()
108 self.existing_port = None
109 self.existing_weight = None
112 if self.type == 'SRV':
115 elif self.type == 'A':
116 self.ip = list[2] # usually $IP, which gets replaced
117 elif self.type == 'CNAME':
120 print "Received unexpected DNS reply of type %s" % self.type
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)
129 ################################################
130 # parse a DNS line from
131 def parse_dns_line(line, sub_vars):
132 subline = samba.substitute_var(line, sub_vars)
136 ############################################
137 # see if two hostnames match
138 def hostname_match(h1, h2):
141 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
144 ############################################
145 # check that a DNS entry exists
146 def check_dns_name(d):
147 normalised_name = d.name.rstrip('.') + '.'
149 print "Looking for DNS entry %s as %s" % (d, normalised_name)
151 if opts.use_file is not None:
153 dns_file = open(opts.use_file, "r")
157 line = dns_file.readline()
159 line = line.rstrip().lstrip()
161 line = dns_file.readline()
163 if line.lower() == str(d).lower():
165 line = dns_file.readline()
169 ans = resolver.query(normalised_name, d.type)
170 except resolver.NXDOMAIN:
173 # we need to be sure that our IP is there
175 if str(rdata) == str(d.ip):
177 if d.type == 'CNAME':
178 for i in range(len(ans)):
179 if hostname_match(ans[i].target, d.dest):
184 print "Checking %s against %s" % (rdata, d)
185 if hostname_match(rdata.target, d.dest):
186 if str(rdata.port) == str(d.port):
189 d.existing_port = str(rdata.port)
190 d.existing_weight = str(rdata.weight)
192 print "Failed to find DNS entry %s" % d
197 ###########################################
198 # get the list of substitution vars
199 def get_subst_vars():
203 samdb = SamDB(url=lp.get("sam database"), session_info=system_session(), lp=lp)
205 vars['DNSDOMAIN'] = lp.get('realm').lower()
206 vars['HOSTNAME'] = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
207 vars['NTDSGUID'] = samdb.get_ntds_GUID()
208 vars['SITE'] = samdb.server_site_name()
209 res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
210 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
211 vars['DOMAINGUID'] = guid
215 ############################################
216 # call nsupdate for an entry
217 def call_nsupdate(d):
218 global ccachename, nsupdate_cmd
221 print "Calling nsupdate for %s" % d
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)
230 (tmp_fd, tmpfile) = tempfile.mkstemp()
231 f = os.fdopen(tmp_fd, 'w')
233 f.write("update add %s %u A %s\n" % (d.name, default_ttl, d.ip))
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))
246 os.putenv("KRB5CCNAME", ccachename)
247 os.system("%s %s" % (nsupdate_cmd, tmpfile))
251 # get the list of DNS entries we should have
252 dns_update_list = lp.private_path('dns_update_list')
254 file = open(dns_update_list, "r")
256 # get the substitution dictionary
257 sub_vars = get_subst_vars()
259 # build up a list of update commands to pass to nsupdate
263 # read each line, and check that the DNS name exists
264 line = file.readline()
266 line = line.rstrip().lstrip()
268 line = file.readline()
270 d = parse_dns_line(line, sub_vars)
272 line = file.readline()
274 # now expand the entries, if any are A record with ip set to $IP
275 # then replace with multiple entries, one for each interface IP
277 if d.type == 'A' and d.ip == "$IP":
279 for i in range(len(IPs)-1):
284 # now check if the entries already exist on the DNS server
286 if not check_dns_name(d):
287 update_list.append(d)
289 if len(update_list) == 0:
291 print "No DNS updates needed"
297 # ask nsupdate to add entries as needed
298 for d in update_list:
301 # delete the ccache if we created it
302 if ccachename is not None:
303 os.unlink(ccachename)