s4-dns: fixed CNAME automatic DNS updates
[samba.git] / source4 / scripting / bin / samba_dnsupdate
1 #!/usr/bin/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 getopt
22 import os
23 import sys
24 import dns.resolver
25 import tempfile
26
27 # Find right directory when running from source tree
28 sys.path.insert(0, "bin/python")
29
30 import samba
31 import optparse
32 from samba import getopt as options, Ldb
33 from ldb import SCOPE_SUBTREE, SCOPE_BASE, LdbError
34 import ldb
35 from samba import glue
36 from samba.auth import system_session
37 from samba.samdb import SamDB
38
39 default_ttl = 900
40
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")
46
47 creds = None
48 ccachename = None
49
50 opts, args = parser.parse_args()
51
52 if len(args) != 0:
53     parser.print_usage()
54     sys.exit(1)
55
56 lp = sambaopts.get_loadparm()
57
58 domain = lp.get("realm")
59 host = lp.get("netbios name")
60 IPs = glue.interface_ips(lp)
61 nsupdate_cmd = lp.get('nsupdate command')
62
63 if len(IPs) == 0:
64     print "No IP interfaces - skipping DNS updates"
65     sys.exit(0)
66
67
68
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
74     if creds is not None:
75         return
76     creds = Credentials()
77     creds.guess(lp)
78     try:
79         creds.set_machine_account(lp)
80     except:
81         print "Failed to set machine account"
82         raise
83
84     (tmp_fd, ccachename) = tempfile.mkstemp()
85     creds.get_named_ccache(lp, ccachename)
86
87
88 #############################################
89 # an object to hold a parsed DNS line
90 class dnsobj(object):
91     def __init__(self):
92         self.type = None
93         self.name = None
94         self.dest = None
95         self.port = None
96         self.ip = None
97         self.existing_port = None
98         self.existing_weight = None
99     def __str__(self):
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)
103
104
105 ################################################
106 # parse a DNS line from
107 def parse_dns_line(line, sub_vars):
108     d = dnsobj()
109     subline = samba.substitute_var(line, sub_vars)
110     list = subline.split()
111     d.type = list[0]
112     d.name = list[1]
113     if d.type == 'SRV':
114         d.dest = list[2]
115         d.port = list[3]
116     elif d.type == 'A':
117         d.ip   = list[2] # usually $IP, which gets replaced
118     elif d.type == 'CNAME':
119         d.dest = list[2]
120     else:
121         print "Received unexpected DNS reply of type %s" % d.type
122         raise
123     return d
124
125 ############################################
126 # see if two hostnames match
127 def hostname_match(h1, h2):
128     h1 = str(h1)
129     h2 = str(h2)
130     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
131
132
133 ############################################
134 # check that a DNS entry exists
135 def check_dns_name(d):
136     normalised_name = d.name.rstrip('.') + '.'
137     if opts.verbose:
138         print "Looking for DNS entry %s as %s" % (d, normalised_name)
139     try:
140         ans = dns.resolver.query(normalised_name, d.type)
141     except dns.resolver.NXDOMAIN:
142         return False
143     if d.type == 'A':
144         # we need to be sure that our IP is there
145         for rdata in ans:
146             if str(rdata) == str(d.ip):
147                 return True
148     if d.type == 'CNAME':
149         for i in range(len(ans)):
150             if hostname_match(ans[i].target, d.dest):
151                 return True
152     if d.type == 'SRV':
153         for rdata in ans:
154             if opts.verbose:
155                 print "Checking %s against %s" % (rdata, d)
156             if hostname_match(rdata.target, d.dest):
157                 if str(rdata.port) == str(d.port):
158                     return True
159                 else:
160                     d.existing_port     = str(rdata.port)
161                     d.existing_weight = str(rdata.weight)
162     if opts.verbose:
163         print "Failed to find DNS entry %s" % d
164     return False
165
166
167 ###########################################
168 # get the list of substitution vars
169 def get_subst_vars():
170     global lp
171     vars = {}
172
173     samdb = SamDB(url=lp.get("sam database"), session_info=system_session(), lp=lp)
174
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
182     return vars
183
184
185 ############################################
186 # call nsupdate for an entry
187 def call_nsupdate(d):
188     global ccachename, nsupdate_cmd
189
190     if opts.verbose:
191         print "Calling nsupdate for %s" % d
192     (tmp_fd, tmpfile) = tempfile.mkstemp()
193     f = os.fdopen(tmp_fd, 'w')
194     if d.type == "A":
195         f.write("update add %s %u A %s\n" % (d.name, default_ttl, d.ip))
196     if d.type == "SRV":
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 CNAME %s\n" % (d.name, default_ttl, d.dest))
203     if opts.verbose:
204         f.write("show\n")
205     f.write("send\n")
206     f.close()
207
208     os.putenv("KRB5CCNAME", ccachename)
209     os.system("%s %s" % (nsupdate_cmd, tmpfile))
210     os.unlink(tmpfile)
211
212
213 # get the list of DNS entries we should have
214 dns_update_list = lp.private_path('dns_update_list')
215
216 file = open(dns_update_list, "r")
217
218 # get the substitution dictionary
219 sub_vars = get_subst_vars()
220
221 # build up a list of update commands to pass to nsupdate
222 update_list = []
223 dns_list = []
224
225 # read each line, and check that the DNS name exists
226 line = file.readline()
227 while line:
228     line = line.rstrip().lstrip()
229     if line[0] == "#":
230         line = file.readline()
231         continue
232     d = parse_dns_line(line, sub_vars)
233     dns_list.append(d)
234     line = file.readline()
235
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
238 for d in dns_list:
239     if d.type == 'A' and d.ip == "$IP":
240         d.ip = IPs[0]
241         for i in range(len(IPs)-1):
242             d2 = d
243             d2.ip = IPs[i+1]
244             dns_list.append(d2)
245
246 # now check if the entries already exist on the DNS server
247 for d in dns_list:
248     if not check_dns_name(d):
249         update_list.append(d)
250
251 if len(update_list) == 0:
252     if opts.verbose:
253         print "No DNS updates needed"
254     sys.exit(0)
255
256 # get our krb5 creds
257 get_credentials(lp)
258
259 # ask nsupdate to add entries as needed
260 for d in update_list:
261     call_nsupdate(d)
262
263 # delete the ccache if we created it
264 if ccachename is not None:
265     os.unlink(ccachename)
266
267