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/>.
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')
30 # Find right directory when running from source tree
31 sys
.path
.insert(0, "bin/python")
35 from samba
import getopt
as options
, Ldb
36 from ldb
import SCOPE_SUBTREE
, SCOPE_BASE
, LdbError
38 from samba
import glue
39 from samba
.auth
import system_session
40 from samba
.samdb
import SamDB
43 resolver
= samba
.external
.samba_external_dns_resolver()
47 parser
= optparse
.OptionParser("samba_dnsupdate")
48 sambaopts
= options
.SambaOptions(parser
)
49 parser
.add_option_group(sambaopts
)
50 parser
.add_option_group(options
.VersionOptions(parser
))
51 parser
.add_option("--verbose", action
="store_true")
56 opts
, args
= parser
.parse_args()
62 lp
= sambaopts
.get_loadparm()
64 domain
= lp
.get("realm")
65 host
= lp
.get("netbios name")
66 IPs
= glue
.interface_ips(lp
)
67 nsupdate_cmd
= lp
.get('nsupdate command')
70 print "No IP interfaces - skipping DNS updates"
75 ########################################################
76 # get credentials if we haven't got them already
77 def get_credentials(lp
):
78 from samba
.credentials
import Credentials
79 global ccachename
, creds
85 creds
.set_machine_account(lp
)
87 print "Failed to set machine account"
90 (tmp_fd
, ccachename
) = tempfile
.mkstemp()
91 creds
.get_named_ccache(lp
, ccachename
)
94 #############################################
95 # an object to hold a parsed DNS line
103 self
.existing_port
= None
104 self
.existing_weight
= None
106 if d
.type == "A": return "%s:%s:%s" % (self
.type, self
.name
, self
.ip
)
107 if d
.type == "SRV": return "%s:%s:%s:%s" % (self
.type, self
.name
, self
.dest
, self
.port
)
108 if d
.type == "CNAME": return "%s:%s:%s" % (self
.type, self
.name
, self
.dest
)
111 ################################################
112 # parse a DNS line from
113 def parse_dns_line(line
, sub_vars
):
115 subline
= samba
.substitute_var(line
, sub_vars
)
116 list = subline
.split()
123 d
.ip
= list[2] # usually $IP, which gets replaced
124 elif d
.type == 'CNAME':
127 print "Received unexpected DNS reply of type %s" % d
.type
131 ############################################
132 # see if two hostnames match
133 def hostname_match(h1
, h2
):
136 return h1
.lower().rstrip('.') == h2
.lower().rstrip('.')
139 ############################################
140 # check that a DNS entry exists
141 def check_dns_name(d
):
142 normalised_name
= d
.name
.rstrip('.') + '.'
144 print "Looking for DNS entry %s as %s" % (d
, normalised_name
)
146 ans
= resolver
.query(normalised_name
, d
.type)
147 except resolver
.NXDOMAIN
:
150 # we need to be sure that our IP is there
152 if str(rdata
) == str(d
.ip
):
154 if d
.type == 'CNAME':
155 for i
in range(len(ans
)):
156 if hostname_match(ans
[i
].target
, d
.dest
):
161 print "Checking %s against %s" % (rdata
, d
)
162 if hostname_match(rdata
.target
, d
.dest
):
163 if str(rdata
.port
) == str(d
.port
):
166 d
.existing_port
= str(rdata
.port
)
167 d
.existing_weight
= str(rdata
.weight
)
169 print "Failed to find DNS entry %s" % d
173 ###########################################
174 # get the list of substitution vars
175 def get_subst_vars():
179 samdb
= SamDB(url
=lp
.get("sam database"), session_info
=system_session(), lp
=lp
)
181 vars['DNSDOMAIN'] = lp
.get('realm').lower()
182 vars['HOSTNAME'] = lp
.get('netbios name').lower() + "." + vars['DNSDOMAIN']
183 vars['NTDSGUID'] = samdb
.get_ntds_GUID()
184 vars['SITE'] = samdb
.server_site_name()
185 res
= samdb
.search(base
=None, scope
=SCOPE_BASE
, attrs
=["objectGUID"])
186 guid
= samdb
.schema_format_value("objectGUID", res
[0]['objectGUID'][0])
187 vars['DOMAINGUID'] = guid
191 ############################################
192 # call nsupdate for an entry
193 def call_nsupdate(d
):
194 global ccachename
, nsupdate_cmd
197 print "Calling nsupdate for %s" % d
198 (tmp_fd
, tmpfile
) = tempfile
.mkstemp()
199 f
= os
.fdopen(tmp_fd
, 'w')
201 f
.write("update add %s %u A %s\n" % (d
.name
, default_ttl
, d
.ip
))
203 if d
.existing_port
is not None:
204 f
.write("update delete %s SRV 0 %s %s %s\n" % (d
.name
, d
.existing_weight
,
205 d
.existing_port
, d
.dest
))
206 f
.write("update add %s %u SRV 0 100 %s %s\n" % (d
.name
, default_ttl
, d
.port
, d
.dest
))
207 if d
.type == "CNAME":
208 f
.write("update add %s %u CNAME %s\n" % (d
.name
, default_ttl
, d
.dest
))
214 os
.putenv("KRB5CCNAME", ccachename
)
215 os
.system("%s %s" % (nsupdate_cmd
, tmpfile
))
219 # get the list of DNS entries we should have
220 dns_update_list
= lp
.private_path('dns_update_list')
222 file = open(dns_update_list
, "r")
224 # get the substitution dictionary
225 sub_vars
= get_subst_vars()
227 # build up a list of update commands to pass to nsupdate
231 # read each line, and check that the DNS name exists
232 line
= file.readline()
234 line
= line
.rstrip().lstrip()
236 line
= file.readline()
238 d
= parse_dns_line(line
, sub_vars
)
240 line
= file.readline()
242 # now expand the entries, if any are A record with ip set to $IP
243 # then replace with multiple entries, one for each interface IP
245 if d
.type == 'A' and d
.ip
== "$IP":
247 for i
in range(len(IPs
)-1):
252 # now check if the entries already exist on the DNS server
254 if not check_dns_name(d
):
255 update_list
.append(d
)
257 if len(update_list
) == 0:
259 print "No DNS updates needed"
265 # ask nsupdate to add entries as needed
266 for d
in update_list
:
269 # delete the ccache if we created it
270 if ccachename
is not None:
271 os
.unlink(ccachename
)