s4-python: Move samdb_ntds_objectGUID to pydsdb.
[obnox/samba/samba-obnox.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
40 samba.ensure_external_module("dns", "dnspython")
41 import dns.resolver as resolver
42
43 default_ttl = 900
44
45 parser = optparse.OptionParser("samba_dnsupdate")
46 sambaopts = options.SambaOptions(parser)
47 parser.add_option_group(sambaopts)
48 parser.add_option_group(options.VersionOptions(parser))
49 parser.add_option("--verbose", action="store_true")
50 parser.add_option("--all-interfaces", action="store_true")
51 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
52
53 creds = None
54 ccachename = None
55
56 opts, args = parser.parse_args()
57
58 if len(args) != 0:
59     parser.print_usage()
60     sys.exit(1)
61
62 lp = sambaopts.get_loadparm()
63
64 domain = lp.get("realm")
65 host = lp.get("netbios name")
66 if opts.all_interfaces:
67     all_interfaces = True
68 else:
69     all_interfaces = False
70
71 IPs = samba.interface_ips(lp, all_interfaces)
72 nsupdate_cmd = lp.get('nsupdate command')
73
74 if len(IPs) == 0:
75     print "No IP interfaces - skipping DNS updates"
76     sys.exit(0)
77
78
79
80 ########################################################
81 # get credentials if we haven't got them already
82 def get_credentials(lp):
83     from samba.credentials import Credentials
84     global ccachename, creds
85     if creds is not None:
86         return
87     creds = Credentials()
88     creds.guess(lp)
89     try:
90         creds.set_machine_account(lp)
91     except:
92         print "Failed to set machine account"
93         raise
94
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         line = dns_file.readline()
157         while line:
158             line = line.rstrip().lstrip()
159             if line[0] == "#":
160                 line = dns_file.readline()
161                 continue
162             if line.lower() == str(d).lower():
163                 return True
164             line = dns_file.readline()
165         return False
166
167     try:
168         ans = resolver.query(normalised_name, d.type)
169     except resolver.NXDOMAIN:
170         return False
171     if d.type == 'A':
172         # we need to be sure that our IP is there
173         for rdata in ans:
174             if str(rdata) == str(d.ip):
175                 return True
176     if d.type == 'CNAME':
177         for i in range(len(ans)):
178             if hostname_match(ans[i].target, d.dest):
179                 return True
180     if d.type == 'SRV':
181         for rdata in ans:
182             if opts.verbose:
183                 print "Checking %s against %s" % (rdata, d)
184             if hostname_match(rdata.target, d.dest):
185                 if str(rdata.port) == str(d.port):
186                     return True
187                 else:
188                     d.existing_port     = str(rdata.port)
189                     d.existing_weight = str(rdata.weight)
190     if opts.verbose:
191         print "Failed to find DNS entry %s" % d
192
193     return False
194
195
196 ###########################################
197 # get the list of substitution vars
198 def get_subst_vars():
199     global lp
200     vars = {}
201
202     samdb = SamDB(url=lp.get("sam database"), session_info=system_session(),
203                               lp=lp)
204
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
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 # get the list of DNS entries we should have
252 dns_update_list = lp.private_path('dns_update_list')
253
254 file = open(dns_update_list, "r")
255
256 # get the substitution dictionary
257 sub_vars = get_subst_vars()
258
259 # build up a list of update commands to pass to nsupdate
260 update_list = []
261 dns_list = []
262
263 # read each line, and check that the DNS name exists
264 line = file.readline()
265 while line:
266     line = line.rstrip().lstrip()
267     if line[0] == "#":
268         line = file.readline()
269         continue
270     d = parse_dns_line(line, sub_vars)
271     dns_list.append(d)
272     line = file.readline()
273
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
276 for d in dns_list:
277     if d.type == 'A' and d.ip == "$IP":
278         d.ip = IPs[0]
279         for i in range(len(IPs)-1):
280             d2 = d
281             d2.ip = IPs[i+1]
282             dns_list.append(d2)
283
284 # now check if the entries already exist on the DNS server
285 for d in dns_list:
286     if not check_dns_name(d):
287         update_list.append(d)
288
289 if len(update_list) == 0:
290     if opts.verbose:
291         print "No DNS updates needed"
292     sys.exit(0)
293
294 # get our krb5 creds
295 get_credentials(lp)
296
297 # ask nsupdate to add entries as needed
298 for d in update_list:
299     call_nsupdate(d)
300
301 # delete the ccache if we created it
302 if ccachename is not None:
303     os.unlink(ccachename)
304
305