b295224ddc67f561d0ce2be706f3a6a9715feb82
[anatoliy/anatoliy.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 import credentials
84     global ccachename, creds
85     if creds is not None:
86         return
87     creds = credentials.Credentials()
88     creds.guess(lp)
89     creds.set_machine_account(lp)
90     creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
91     (tmp_fd, ccachename) = tempfile.mkstemp()
92     creds.get_named_ccache(lp, ccachename)
93
94
95 #############################################
96 # an object to hold a parsed DNS line
97 class dnsobj(object):
98     def __init__(self, string_form):
99         list = string_form.split()
100         self.dest = None
101         self.port = None
102         self.ip = None
103         self.existing_port = None
104         self.existing_weight = None
105         self.type = list[0]
106         self.name = list[1]
107         if self.type == 'SRV':
108             self.dest = list[2]
109             self.port = list[3]
110         elif self.type == 'A':
111             self.ip   = list[2] # usually $IP, which gets replaced
112         elif self.type == 'CNAME':
113             self.dest = list[2]
114         else:
115             print "Received unexpected DNS reply of type %s" % self.type
116             raise
117
118     def __str__(self):
119         if d.type == "A":     return "%s %s %s" % (self.type, self.name, self.ip)
120         if d.type == "SRV":   return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
121         if d.type == "CNAME": return "%s %s %s" % (self.type, self.name, self.dest)
122
123
124 ################################################
125 # parse a DNS line from
126 def parse_dns_line(line, sub_vars):
127     subline = samba.substitute_var(line, sub_vars)
128     d = dnsobj(subline)
129     return d
130
131 ############################################
132 # see if two hostnames match
133 def hostname_match(h1, h2):
134     h1 = str(h1)
135     h2 = str(h2)
136     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
137
138
139 ############################################
140 # check that a DNS entry exists
141 def check_dns_name(d):
142     normalised_name = d.name.rstrip('.') + '.'
143     if opts.verbose:
144         print "Looking for DNS entry %s as %s" % (d, normalised_name)
145  
146     if opts.use_file is not None:
147         try:
148             dns_file = open(opts.use_file, "r")
149         except IOError:
150             return False
151         
152         for line in dns_file:
153             line = line.strip()
154             if line == '' or line[0] == "#":
155                 continue
156             if line.lower() == str(d).lower():
157                 return True
158         return False
159
160     try:
161         ans = resolver.query(normalised_name, d.type)
162     except resolver.NXDOMAIN:
163         return False
164     if d.type == 'A':
165         # we need to be sure that our IP is there
166         for rdata in ans:
167             if str(rdata) == str(d.ip):
168                 return True
169     if d.type == 'CNAME':
170         for i in range(len(ans)):
171             if hostname_match(ans[i].target, d.dest):
172                 return True
173     if d.type == 'SRV':
174         for rdata in ans:
175             if opts.verbose:
176                 print "Checking %s against %s" % (rdata, d)
177             if hostname_match(rdata.target, d.dest):
178                 if str(rdata.port) == str(d.port):
179                     return True
180                 else:
181                     d.existing_port     = str(rdata.port)
182                     d.existing_weight = str(rdata.weight)
183     if opts.verbose:
184         print "Failed to find DNS entry %s" % d
185
186     return False
187
188
189 ###########################################
190 # get the list of substitution vars
191 def get_subst_vars():
192     global lp
193     vars = {}
194
195     samdb = SamDB(url=lp.get("sam database"), session_info=system_session(),
196                   lp=lp)
197
198     vars['DNSDOMAIN'] = lp.get('realm').lower()
199     vars['HOSTNAME']  = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
200     vars['NTDSGUID']  = samdb.get_ntds_GUID()
201     vars['SITE']      = samdb.server_site_name()
202     res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
203     guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
204     vars['DOMAINGUID'] = guid
205     return vars
206
207
208 ############################################
209 # call nsupdate for an entry
210 def call_nsupdate(d):
211     global ccachename, nsupdate_cmd
212
213     if opts.verbose:
214         print "Calling nsupdate for %s" % d
215
216     if opts.use_file is not None:
217         wfile = open(opts.use_file, 'a')
218         fcntl.lockf(wfile, fcntl.LOCK_EX)
219         wfile.write(str(d)+"\n")
220         fcntl.lockf(wfile, fcntl.LOCK_UN)
221         return
222
223     (tmp_fd, tmpfile) = tempfile.mkstemp()
224     f = os.fdopen(tmp_fd, 'w')
225     if d.type == "A":
226         f.write("update add %s %u A %s\n" % (d.name, default_ttl, d.ip))
227     if d.type == "SRV":
228         if d.existing_port is not None:
229             f.write("update delete %s SRV 0 %s %s %s\n" % (d.name, d.existing_weight,
230                                                            d.existing_port, d.dest))
231         f.write("update add %s %u SRV 0 100 %s %s\n" % (d.name, default_ttl, d.port, d.dest))
232     if d.type == "CNAME":
233         f.write("update add %s %u CNAME %s\n" % (d.name, default_ttl, d.dest))
234     if opts.verbose:
235         f.write("show\n")
236     f.write("send\n")
237     f.close()
238
239     os.putenv("KRB5CCNAME", ccachename)
240     os.system("%s %s" % (nsupdate_cmd, tmpfile))
241     os.unlink(tmpfile)
242
243
244 # get the list of DNS entries we should have
245 dns_update_list = lp.private_path('dns_update_list')
246
247 file = open(dns_update_list, "r")
248
249 # get the substitution dictionary
250 sub_vars = get_subst_vars()
251
252 # build up a list of update commands to pass to nsupdate
253 update_list = []
254 dns_list = []
255
256 # read each line, and check that the DNS name exists
257 for line in file:
258     line = line.strip()
259     if line == '' or line[0] == "#":
260         continue
261     d = parse_dns_line(line, sub_vars)
262     dns_list.append(d)
263
264 # now expand the entries, if any are A record with ip set to $IP
265 # then replace with multiple entries, one for each interface IP
266 for d in dns_list:
267     if d.type == 'A' and d.ip == "$IP":
268         d.ip = IPs[0]
269         for i in range(len(IPs)-1):
270             d2 = d
271             d2.ip = IPs[i+1]
272             dns_list.append(d2)
273
274 # now check if the entries already exist on the DNS server
275 for d in dns_list:
276     if not check_dns_name(d):
277         update_list.append(d)
278
279 if len(update_list) == 0:
280     if opts.verbose:
281         print "No DNS updates needed"
282     sys.exit(0)
283
284 # get our krb5 creds
285 get_credentials(lp)
286
287 # ask nsupdate to add entries as needed
288 for d in update_list:
289     call_nsupdate(d)
290
291 # delete the ccache if we created it
292 if ccachename is not None:
293     os.unlink(ccachename)