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/>.
27 # Find right directory when running from source tree
28 sys.path.insert(0, "bin/python")
32 from samba import getopt as options, Ldb
33 from ldb import SCOPE_SUBTREE, SCOPE_BASE, LdbError
35 from samba import glue
36 from samba.auth import system_session
37 from samba.samdb import SamDB
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")
50 opts, args = parser.parse_args()
56 lp = sambaopts.get_loadparm()
58 domain = lp.get("realm")
59 host = lp.get("netbios name")
60 IPs = glue.interface_ips(lp)
61 nsupdate_cmd = lp.get('nsupdate command')
64 print "No IP interfaces - skipping DNS updates"
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
79 creds.set_machine_account(lp)
81 print "Failed to set machine account"
84 (tmp_fd, ccachename) = tempfile.mkstemp()
85 creds.get_named_ccache(lp, ccachename)
88 #############################################
89 # an object to hold a parsed DNS line
97 self.existing_port = None
98 self.existing_weight = None
100 if d.type == "A": return "%s:%s:%s" % (self.type, self.name, self.ip)
101 if d.type == "SRV": return "%s:%s:%s:%s" % (self.type, self.name, self.dest, self.port)
102 if d.type == "CNAME": return "%s:%s:%s" % (self.type, self.name, self.dest)
105 ################################################
106 # parse a DNS line from
107 def parse_dns_line(line, sub_vars):
109 subline = samba.substitute_var(line, sub_vars)
110 list = subline.split()
117 d.ip = list[2] # usually $IP, which gets replaced
118 elif d.type == 'CNAME':
121 print "Received unexpected DNS reply of type %s" % d.type
125 ############################################
126 # see if two hostnames match
127 def hostname_match(h1, h2):
130 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
133 ############################################
134 # check that a DNS entry exists
135 def check_dns_name(d):
136 normalised_name = d.name.rstrip('.') + '.'
138 print "Looking for DNS entry %s as %s" % (d, normalised_name)
140 ans = dns.resolver.query(normalised_name, d.type)
141 except dns.resolver.NXDOMAIN:
144 # we need to be sure that our IP is there
146 if str(rdata) == str(d.ip):
148 if d.type == 'CNAME':
149 for i in range(len(ans)):
150 if hostname_match(ans[i].target, d.dest):
155 print "Checking %s against %s" % (rdata, d)
156 if hostname_match(rdata.target, d.dest):
157 if str(rdata.port) == str(d.port):
160 d.existing_port = str(rdata.port)
161 d.existing_weight = str(rdata.weight)
163 print "Failed to find DNS entry %s" % d
167 ###########################################
168 # get the list of substitution vars
169 def get_subst_vars():
173 samdb = SamDB(url=lp.get("sam database"), session_info=system_session(), lp=lp)
175 vars['DNSDOMAIN'] = lp.get('realm').lower()
176 vars['HOSTNAME'] = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
177 vars['NTDSGUID'] = samdb.get_ntds_GUID()
178 vars['SITE'] = samdb.server_site_name()
179 res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
180 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
181 vars['DOMAINGUID'] = guid
185 ############################################
186 # call nsupdate for an entry
187 def call_nsupdate(d):
188 global ccachename, nsupdate_cmd
191 print "Calling nsupdate for %s" % d
192 (tmp_fd, tmpfile) = tempfile.mkstemp()
193 f = os.fdopen(tmp_fd, 'w')
195 f.write("update add %s %u A %s\n" % (d.name, default_ttl, d.ip))
197 if d.existing_port is not None:
198 f.write("update delete %s SRV 0 %s %s %s\n" % (d.name, d.existing_weight,
199 d.existing_port, d.dest))
200 f.write("update add %s %u SRV 0 100 %s %s\n" % (d.name, default_ttl, d.port, d.dest))
201 if d.type == "CNAME":
202 f.write("update add %s %u SRV %s\n" % (d.name, default_ttl, d.dest))
208 os.putenv("KRB5CCNAME", ccachename)
209 os.system("%s %s" % (nsupdate_cmd, tmpfile))
213 # get the list of DNS entries we should have
214 dns_update_list = lp.private_path('dns_update_list')
216 file = open(dns_update_list, "r")
218 # get the substitution dictionary
219 sub_vars = get_subst_vars()
221 # build up a list of update commands to pass to nsupdate
225 # read each line, and check that the DNS name exists
226 line = file.readline()
228 line = line.rstrip().lstrip()
230 line = file.readline()
232 d = parse_dns_line(line, sub_vars)
234 line = file.readline()
236 # now expand the entries, if any are A record with ip set to $IP
237 # then replace with multiple entries, one for each interface IP
239 if d.type == 'A' and d.ip == "$IP":
241 for i in range(len(IPs)-1):
246 # now check if the entries already exist on the DNS server
248 if not check_dns_name(d):
249 update_list.append(d)
251 if len(update_list) == 0:
253 print "No DNS updates needed"
259 # ask nsupdate to add entries as needed
260 for d in update_list:
263 # delete the ccache if we created it
264 if ccachename is not None:
265 os.unlink(ccachename)