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 # ensure we get messages out immediately, so they get in the samba logs,
28 # and don't get swallowed by a timeout
29 os
.putenv('PYTHONUNBUFFERED', '1')
31 # Find right directory when running from source tree
32 sys
.path
.insert(0, "bin/python")
36 from samba
import getopt
as options
, Ldb
37 from ldb
import SCOPE_SUBTREE
, SCOPE_BASE
, LdbError
39 from samba
import glue
40 from samba
.auth
import system_session
41 from samba
.samdb
import SamDB
44 resolver
= samba
.external
.samba_external_dns_resolver()
48 parser
= optparse
.OptionParser("samba_dnsupdate")
49 sambaopts
= options
.SambaOptions(parser
)
50 parser
.add_option_group(sambaopts
)
51 parser
.add_option_group(options
.VersionOptions(parser
))
52 parser
.add_option("--verbose", 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")
59 opts
, args
= parser
.parse_args()
65 lp
= sambaopts
.get_loadparm()
67 domain
= lp
.get("realm")
68 host
= lp
.get("netbios name")
69 if opts
.all_interfaces
:
72 all_interfaces
= False
74 IPs
= glue
.interface_ips(lp
, all_interfaces
)
75 nsupdate_cmd
= lp
.get('nsupdate command')
78 print "No IP interfaces - skipping DNS updates"
83 ########################################################
84 # get credentials if we haven't got them already
85 def get_credentials(lp
):
86 from samba
.credentials
import Credentials
87 global ccachename
, creds
93 creds
.set_machine_account(lp
)
95 print "Failed to set machine account"
98 (tmp_fd
, ccachename
) = tempfile
.mkstemp()
99 creds
.get_named_ccache(lp
, ccachename
)
102 #############################################
103 # an object to hold a parsed DNS line
104 class dnsobj(object):
105 def __init__(self
, string_form
):
106 list = string_form
.split()
110 self
.existing_port
= None
111 self
.existing_weight
= None
114 if self
.type == 'SRV':
117 elif self
.type == 'A':
118 self
.ip
= list[2] # usually $IP, which gets replaced
119 elif self
.type == 'CNAME':
122 print "Received unexpected DNS reply of type %s" % self
.type
126 if d
.type == "A": return "%s %s %s" % (self
.type, self
.name
, self
.ip
)
127 if d
.type == "SRV": return "%s %s %s %s" % (self
.type, self
.name
, self
.dest
, self
.port
)
128 if d
.type == "CNAME": return "%s %s %s" % (self
.type, self
.name
, self
.dest
)
131 ################################################
132 # parse a DNS line from
133 def parse_dns_line(line
, sub_vars
):
134 subline
= samba
.substitute_var(line
, sub_vars
)
138 ############################################
139 # see if two hostnames match
140 def hostname_match(h1
, h2
):
143 return h1
.lower().rstrip('.') == h2
.lower().rstrip('.')
146 ############################################
147 # check that a DNS entry exists
148 def check_dns_name(d
):
149 normalised_name
= d
.name
.rstrip('.') + '.'
151 print "Looking for DNS entry %s as %s" % (d
, normalised_name
)
153 if opts
.use_file
is not None:
155 dns_file
= open(opts
.use_file
, "r")
159 line
= dns_file
.readline()
161 line
= line
.rstrip().lstrip()
163 line
= dns_file
.readline()
165 if line
.lower() == str(d
).lower():
167 line
= dns_file
.readline()
171 ans
= resolver
.query(normalised_name
, d
.type)
172 except resolver
.NXDOMAIN
:
175 # we need to be sure that our IP is there
177 if str(rdata
) == str(d
.ip
):
179 if d
.type == 'CNAME':
180 for i
in range(len(ans
)):
181 if hostname_match(ans
[i
].target
, d
.dest
):
186 print "Checking %s against %s" % (rdata
, d
)
187 if hostname_match(rdata
.target
, d
.dest
):
188 if str(rdata
.port
) == str(d
.port
):
191 d
.existing_port
= str(rdata
.port
)
192 d
.existing_weight
= str(rdata
.weight
)
194 print "Failed to find DNS entry %s" % d
199 ###########################################
200 # get the list of substitution vars
201 def get_subst_vars():
205 samdb
= SamDB(url
=lp
.get("sam database"), session_info
=system_session(), lp
=lp
)
207 vars['DNSDOMAIN'] = lp
.get('realm').lower()
208 vars['HOSTNAME'] = lp
.get('netbios name').lower() + "." + vars['DNSDOMAIN']
209 vars['NTDSGUID'] = samdb
.get_ntds_GUID()
210 vars['SITE'] = samdb
.server_site_name()
211 res
= samdb
.search(base
=None, scope
=SCOPE_BASE
, attrs
=["objectGUID"])
212 guid
= samdb
.schema_format_value("objectGUID", res
[0]['objectGUID'][0])
213 vars['DOMAINGUID'] = guid
217 ############################################
218 # call nsupdate for an entry
219 def call_nsupdate(d
):
220 global ccachename
, nsupdate_cmd
223 print "Calling nsupdate for %s" % d
225 if opts
.use_file
is not None:
226 wfile
= open(opts
.use_file
, 'a')
227 fcntl
.lockf(wfile
, fcntl
.LOCK_EX
)
228 wfile
.write(str(d
)+"\n")
229 fcntl
.lockf(wfile
, fcntl
.LOCK_UN
)
232 (tmp_fd
, tmpfile
) = tempfile
.mkstemp()
233 f
= os
.fdopen(tmp_fd
, 'w')
235 f
.write("update add %s %u A %s\n" % (d
.name
, default_ttl
, d
.ip
))
237 if d
.existing_port
is not None:
238 f
.write("update delete %s SRV 0 %s %s %s\n" % (d
.name
, d
.existing_weight
,
239 d
.existing_port
, d
.dest
))
240 f
.write("update add %s %u SRV 0 100 %s %s\n" % (d
.name
, default_ttl
, d
.port
, d
.dest
))
241 if d
.type == "CNAME":
242 f
.write("update add %s %u CNAME %s\n" % (d
.name
, default_ttl
, d
.dest
))
248 os
.putenv("KRB5CCNAME", ccachename
)
249 os
.system("%s %s" % (nsupdate_cmd
, tmpfile
))
253 # get the list of DNS entries we should have
254 dns_update_list
= lp
.private_path('dns_update_list')
256 file = open(dns_update_list
, "r")
258 # get the substitution dictionary
259 sub_vars
= get_subst_vars()
261 # build up a list of update commands to pass to nsupdate
265 # read each line, and check that the DNS name exists
266 line
= file.readline()
268 line
= line
.rstrip().lstrip()
270 line
= file.readline()
272 d
= parse_dns_line(line
, sub_vars
)
274 line
= file.readline()
276 # now expand the entries, if any are A record with ip set to $IP
277 # then replace with multiple entries, one for each interface IP
279 if d
.type == 'A' and d
.ip
== "$IP":
281 for i
in range(len(IPs
)-1):
286 # now check if the entries already exist on the DNS server
288 if not check_dns_name(d
):
289 update_list
.append(d
)
291 if len(update_list
) == 0:
293 print "No DNS updates needed"
299 # ask nsupdate to add entries as needed
300 for d
in update_list
:
303 # delete the ccache if we created it
304 if ccachename
is not None:
305 os
.unlink(ccachename
)