session.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. # Copyright (C) 2012 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. from isc.dns import *
  16. import isc.ddns.zone_config
  17. from isc.log import *
  18. from isc.ddns.logger import logger, ClientFormatter, ZoneFormatter,\
  19. RRsetFormatter
  20. from isc.log_messages.libddns_messages import *
  21. from isc.datasrc import ZoneFinder
  22. import isc.xfrin.diff
  23. from isc.acl.acl import ACCEPT, REJECT, DROP
  24. import copy
  25. # Result codes for UpdateSession.handle()
  26. UPDATE_SUCCESS = 0
  27. UPDATE_ERROR = 1
  28. UPDATE_DROP = 2
  29. # Convenient aliases of update-specific section names
  30. SECTION_ZONE = Message.SECTION_QUESTION
  31. SECTION_PREREQUISITE = Message.SECTION_ANSWER
  32. SECTION_UPDATE = Message.SECTION_AUTHORITY
  33. # Shortcut
  34. DBGLVL_TRACE_BASIC = logger.DBGLVL_TRACE_BASIC
  35. class UpdateError(Exception):
  36. '''Exception for general error in update request handling.
  37. This exception is intended to be used internally within this module.
  38. When UpdateSession.handle() encounters an error in handling an update
  39. request it can raise this exception to terminate the handling.
  40. This class is constructed with some information that may be useful for
  41. subsequent possible logging:
  42. - msg (string) A string explaining the error.
  43. - zname (isc.dns.Name) The zone name. Can be None when not identified.
  44. - zclass (isc.dns.RRClass) The zone class. Like zname, can be None.
  45. - rcode (isc.dns.RCode or None) The RCODE to be set in the response
  46. message; this can be None if the response is not expected to be sent.
  47. - nolog (bool) If True, it indicates there's no more need for logging.
  48. '''
  49. def __init__(self, msg, zname, zclass, rcode, nolog=False):
  50. Exception.__init__(self, msg)
  51. self.zname = zname
  52. self.zclass = zclass
  53. self.rcode = rcode
  54. self.nolog = nolog
  55. def foreach_rr(rrset):
  56. '''
  57. Generator that creates a new RRset with one RR from
  58. the given RRset upon each iteration, usable in calls that
  59. need to loop over an RRset and perform an action with each
  60. of the individual RRs in it.
  61. Example:
  62. for rr in foreach_rr(rrset):
  63. print(str(rr))
  64. '''
  65. for rdata in rrset.get_rdata():
  66. rr = isc.dns.RRset(rrset.get_name(),
  67. rrset.get_class(),
  68. rrset.get_type(),
  69. rrset.get_ttl())
  70. rr.add_rdata(rdata)
  71. yield rr
  72. def convert_rrset_class(rrset, rrclass):
  73. '''Returns a (new) rrset with the data from the given rrset,
  74. but of the given class. Useful to convert from NONE and ANY to
  75. a real class.
  76. Note that the caller should be careful what to convert;
  77. and DNS error that could happen during wire-format reading
  78. could technically occur here, and is not caught by this helper.
  79. '''
  80. new_rrset = isc.dns.RRset(rrset.get_name(), rrclass,
  81. rrset.get_type(), rrset.get_ttl())
  82. for rdata in rrset.get_rdata():
  83. # Rdata class is nof modifiable, and must match rrset's
  84. # class, so we need to to some ugly conversion here.
  85. # And we cannot use to_text() (since the class may be unknown)
  86. wire = rdata.to_wire(bytes())
  87. new_rrset.add_rdata(isc.dns.Rdata(rrset.get_type(), rrclass, wire))
  88. return new_rrset
  89. def collect_rrsets(collection, rrset):
  90. '''
  91. Helper function to collect similar rrsets.
  92. Collect all rrsets with the same name, class, and type
  93. collection is the currently collected list of RRsets,
  94. rrset is the RRset to add;
  95. if an RRset with the same name, class and type as the
  96. given rrset exists in the collection, its rdata fields
  97. are added to that RRset. Otherwise, the rrset is added
  98. to the given collection.
  99. TTL is ignored.
  100. This method does not check rdata contents for duplicate
  101. values.
  102. The collection and its rrsets are modified in-place,
  103. this method does not return anything.
  104. '''
  105. found = False
  106. for existing_rrset in collection:
  107. if existing_rrset.get_name() == rrset.get_name() and\
  108. existing_rrset.get_class() == rrset.get_class() and\
  109. existing_rrset.get_type() == rrset.get_type():
  110. for rdata in rrset.get_rdata():
  111. existing_rrset.add_rdata(rdata)
  112. found = True
  113. if not found:
  114. collection.append(rrset)
  115. class UpdateSession:
  116. '''Protocol handling for a single dynamic update request.
  117. This class is instantiated with a request message and some other
  118. information that will be used for handling the request. Its main
  119. method, handle(), will process the request, and normally build
  120. a response message according to the result. The application of this
  121. class can use the message to send a response to the client.
  122. '''
  123. def __init__(self, req_message, client_addr, zone_config):
  124. '''Constructor.
  125. Parameters:
  126. - req_message (isc.dns.Message) The request message. This must be
  127. in the PARSE mode, its Opcode must be UPDATE, and must have been
  128. TSIG validatd if it's TSIG signed.
  129. - client_addr (socket address) The address/port of the update client
  130. in the form of Python socket address object. This is mainly for
  131. logging and access control.
  132. - zone_config (ZoneConfig) A tentative container that encapsulates
  133. the server's zone configuration. See zone_config.py.
  134. - req_data (binary) Wire format data of the request message.
  135. It will be used for TSIG verification if necessary.
  136. '''
  137. self.__message = req_message
  138. self.__tsig = req_message.get_tsig_record()
  139. self.__client_addr = client_addr
  140. self.__zone_config = zone_config
  141. self.__added_soa = None
  142. def get_message(self):
  143. '''Return the update message.
  144. After handle() is called, it's generally transformed to the response
  145. to be returned to the client. If the request has been dropped,
  146. this method returns None. If this method is called before handle()
  147. the return value would be identical to the request message passed on
  148. construction, although it's of no practical use.
  149. '''
  150. return self.__message
  151. def handle(self):
  152. '''Handle the update request according to RFC2136.
  153. This method returns a tuple of the following three elements that
  154. indicate the result of the request.
  155. - Result code of the request processing, which are:
  156. UPDATE_SUCCESS Update request granted and succeeded.
  157. UPDATE_ERROR Some error happened to be reported in the response.
  158. UPDATE_DROP Error happened and no response should be sent.
  159. Except the case of UPDATE_DROP, the UpdateSession object will have
  160. created a response that is to be returned to the request client,
  161. which can be retrieved by get_message(). If it's UPDATE_DROP,
  162. subsequent call to get_message() returns None.
  163. - The name of the updated zone (isc.dns.Name object) in case of
  164. UPDATE_SUCCESS; otherwise None.
  165. - The RR class of the updated zone (isc.dns.RRClass object) in case
  166. of UPDATE_SUCCESS; otherwise None.
  167. '''
  168. try:
  169. self._get_update_zone()
  170. self._create_diff()
  171. prereq_result = self.__check_prerequisites()
  172. if prereq_result != Rcode.NOERROR():
  173. self.__make_response(prereq_result)
  174. return UPDATE_ERROR, self.__zname, self.__zclass
  175. self.__check_update_acl(self.__zname, self.__zclass)
  176. update_result = self.__do_update()
  177. if update_result != Rcode.NOERROR():
  178. self.__make_response(update_result)
  179. return UPDATE_ERROR, self.__zname, self.__zclass
  180. self.__make_response(Rcode.NOERROR())
  181. return UPDATE_SUCCESS, self.__zname, self.__zclass
  182. except UpdateError as e:
  183. if not e.nolog:
  184. logger.debug(logger.DBGLVL_TRACE_BASIC, LIBDDNS_UPDATE_ERROR,
  185. ClientFormatter(self.__client_addr, self.__tsig),
  186. ZoneFormatter(e.zname, e.zclass), e)
  187. # If RCODE is specified, create a corresponding resonse and return
  188. # ERROR; otherwise clear the message and return DROP.
  189. if e.rcode is not None:
  190. self.__make_response(e.rcode)
  191. return UPDATE_ERROR, None, None
  192. self.__message = None
  193. return UPDATE_DROP, None, None
  194. def _get_update_zone(self):
  195. '''Parse the zone section and find the zone to be updated.
  196. If the zone section is valid and the specified zone is found in
  197. the configuration, sets private member variables for this session:
  198. __datasrc_client: A matching data source that contains the specified
  199. zone
  200. __zname: The zone name as a Name object
  201. __zclass: The zone class as an RRClass object
  202. If this method raises an exception, these members are not set.
  203. Note: This method is protected for ease of use in tests, where
  204. methods are tested that need the setup done here without calling
  205. the full handle() method.
  206. '''
  207. # Validation: the zone section must contain exactly one question,
  208. # and it must be of type SOA.
  209. n_zones = self.__message.get_rr_count(SECTION_ZONE)
  210. if n_zones != 1:
  211. raise UpdateError('Invalid number of records in zone section: ' +
  212. str(n_zones), None, None, Rcode.FORMERR())
  213. zrecord = self.__message.get_question()[0]
  214. if zrecord.get_type() != RRType.SOA():
  215. raise UpdateError('update zone section contains non-SOA',
  216. None, None, Rcode.FORMERR())
  217. # See if we're serving a primary zone specified in the zone section.
  218. zname = zrecord.get_name()
  219. zclass = zrecord.get_class()
  220. zone_type, datasrc_client = self.__zone_config.find_zone(zname, zclass)
  221. if zone_type == isc.ddns.zone_config.ZONE_PRIMARY:
  222. self.__datasrc_client = datasrc_client
  223. self.__zname = zname
  224. self.__zclass = zclass
  225. return
  226. elif zone_type == isc.ddns.zone_config.ZONE_SECONDARY:
  227. # We are a secondary server; since we don't yet support update
  228. # forwarding, we return 'not implemented'.
  229. logger.debug(DBGLVL_TRACE_BASIC, LIBDDNS_UPDATE_FORWARD_FAIL,
  230. ClientFormatter(self.__client_addr, self.__tsig),
  231. ZoneFormatter(zname, zclass))
  232. raise UpdateError('forward', zname, zclass, Rcode.NOTIMP(), True)
  233. # zone wasn't found
  234. logger.debug(DBGLVL_TRACE_BASIC, LIBDDNS_UPDATE_NOTAUTH,
  235. ClientFormatter(self.__client_addr, self.__tsig),
  236. ZoneFormatter(zname, zclass))
  237. raise UpdateError('notauth', zname, zclass, Rcode.NOTAUTH(), True)
  238. def _create_diff(self):
  239. '''
  240. Initializes the internal data structure used for searching current
  241. data and for adding and deleting data. This is supposed to be called
  242. after ACL checks but before prerequisite checks (since the latter
  243. needs the find calls provided by the Diff class).
  244. Adds the private member:
  245. __diff: A buffer of changes made against the zone by this update
  246. This object also contains find() calls, see documentation
  247. of the Diff class.
  248. Note: This method is protected for ease of use in tests, where
  249. methods are tested that need the setup done here without calling
  250. the full handle() method.
  251. '''
  252. self.__diff = isc.xfrin.diff.Diff(self.__datasrc_client,
  253. self.__zname,
  254. journaling=True,
  255. single_update_mode=True)
  256. def __check_update_acl(self, zname, zclass):
  257. '''Apply update ACL for the zone to be updated.'''
  258. acl = self.__zone_config.get_update_acl(zname, zclass)
  259. action = acl.execute(isc.acl.dns.RequestContext(
  260. (self.__client_addr[0], self.__client_addr[1]), self.__tsig))
  261. if action == REJECT:
  262. logger.info(LIBDDNS_UPDATE_DENIED,
  263. ClientFormatter(self.__client_addr, self.__tsig),
  264. ZoneFormatter(zname, zclass))
  265. raise UpdateError('rejected', zname, zclass, Rcode.REFUSED(), True)
  266. if action == DROP:
  267. logger.info(LIBDDNS_UPDATE_DROPPED,
  268. ClientFormatter(self.__client_addr, self.__tsig),
  269. ZoneFormatter(zname, zclass))
  270. raise UpdateError('dropped', zname, zclass, None, True)
  271. logger.debug(logger.DBGLVL_TRACE_BASIC, LIBDDNS_UPDATE_APPROVED,
  272. ClientFormatter(self.__client_addr, self.__tsig),
  273. ZoneFormatter(zname, zclass))
  274. def __make_response(self, rcode):
  275. '''Transform the internal message to the update response.
  276. According RFC2136 Section 3.8, the zone section will be cleared
  277. as well as other sections. The response Rcode will be set to the
  278. given value.
  279. '''
  280. self.__message.make_response()
  281. self.__message.clear_section(SECTION_ZONE)
  282. self.__message.set_rcode(rcode)
  283. def __prereq_rrset_exists(self, rrset):
  284. '''Check whether an rrset with the given name and type exists. Class,
  285. TTL, and Rdata (if any) of the given RRset are ignored.
  286. RFC2136 Section 2.4.1.
  287. Returns True if the prerequisite is satisfied, False otherwise.
  288. Note: the only thing used in the call to find() here is the
  289. result status. The actual data is immediately dropped. As
  290. a future optimization, we may want to add a find() option to
  291. only return what the result code would be (and not read/copy
  292. any actual data).
  293. '''
  294. result, _, _ = self.__diff.find(rrset.get_name(), rrset.get_type())
  295. return result == ZoneFinder.SUCCESS
  296. def __prereq_rrset_exists_value(self, rrset):
  297. '''Check whether an rrset that matches name, type, and rdata(s) of the
  298. given rrset exists.
  299. RFC2136 Section 2.4.2
  300. Returns True if the prerequisite is satisfied, False otherwise.
  301. '''
  302. result, found_rrset, _ = self.__diff.find(rrset.get_name(),
  303. rrset.get_type())
  304. if result == ZoneFinder.SUCCESS and\
  305. rrset.get_name() == found_rrset.get_name() and\
  306. rrset.get_type() == found_rrset.get_type():
  307. # We need to match all actual RRs, unfortunately there is no
  308. # direct order-independent comparison for rrsets, so this
  309. # a slightly inefficient way to handle that.
  310. # shallow copy of the rdata list, so we are sure that this
  311. # loop does not mess with actual data.
  312. found_rdata = copy.copy(found_rrset.get_rdata())
  313. for rdata in rrset.get_rdata():
  314. if rdata in found_rdata:
  315. found_rdata.remove(rdata)
  316. else:
  317. return False
  318. return len(found_rdata) == 0
  319. return False
  320. def __prereq_rrset_does_not_exist(self, rrset):
  321. '''Check whether no rrsets with the same name and type as the given
  322. rrset exist.
  323. RFC2136 Section 2.4.3.
  324. Returns True if the prerequisite is satisfied, False otherwise.
  325. '''
  326. return not self.__prereq_rrset_exists(rrset)
  327. def __prereq_name_in_use(self, rrset):
  328. '''Check whether the name of the given RRset is in use (i.e. has
  329. 1 or more RRs).
  330. RFC2136 Section 2.4.4
  331. Returns True if the prerequisite is satisfied, False otherwise.
  332. Note: the only thing used in the call to find_all() here is
  333. the result status. The actual data is immediately dropped. As
  334. a future optimization, we may want to add a find_all() option
  335. to only return what the result code would be (and not read/copy
  336. any actual data).
  337. '''
  338. result, rrsets, flags = self.__diff.find_all(rrset.get_name())
  339. if result == ZoneFinder.SUCCESS and\
  340. (flags & ZoneFinder.RESULT_WILDCARD == 0):
  341. return True
  342. return False
  343. def __prereq_name_not_in_use(self, rrset):
  344. '''Check whether the name of the given RRset is not in use (i.e. does
  345. not exist at all, or is an empty nonterminal.
  346. RFC2136 Section 2.4.5.
  347. Returns True if the prerequisite is satisfied, False otherwise.
  348. '''
  349. return not self.__prereq_name_in_use(rrset)
  350. def __check_in_zone(self, rrset):
  351. '''Returns true if the name of the given rrset is equal to
  352. or a subdomain of the zname from the Zone Section.'''
  353. relation = rrset.get_name().compare(self.__zname).get_relation()
  354. return relation == NameComparisonResult.SUBDOMAIN or\
  355. relation == NameComparisonResult.EQUAL
  356. def __check_prerequisites(self):
  357. '''Check the prerequisites section of the UPDATE Message.
  358. RFC2136 Section 2.4.
  359. Returns a dns Rcode signaling either no error (Rcode.NOERROR())
  360. or that one of the prerequisites failed (any other Rcode).
  361. '''
  362. # Temporary array to store exact-match RRsets
  363. exact_match_rrsets = []
  364. for rrset in self.__message.get_section(SECTION_PREREQUISITE):
  365. # First check if the name is in the zone
  366. if not self.__check_in_zone(rrset):
  367. logger.info(LIBDDNS_PREREQ_NOTZONE,
  368. ClientFormatter(self.__client_addr),
  369. ZoneFormatter(self.__zname, self.__zclass),
  370. RRsetFormatter(rrset))
  371. return Rcode.NOTZONE()
  372. # Algorithm taken from RFC2136 Section 3.2
  373. if rrset.get_class() == RRClass.ANY():
  374. if rrset.get_ttl().get_value() != 0 or\
  375. rrset.get_rdata_count() != 0:
  376. logger.info(LIBDDNS_PREREQ_FORMERR_ANY,
  377. ClientFormatter(self.__client_addr),
  378. ZoneFormatter(self.__zname, self.__zclass),
  379. RRsetFormatter(rrset))
  380. return Rcode.FORMERR()
  381. elif rrset.get_type() == RRType.ANY():
  382. if not self.__prereq_name_in_use(rrset):
  383. rcode = Rcode.NXDOMAIN()
  384. logger.info(LIBDDNS_PREREQ_NAME_IN_USE_FAILED,
  385. ClientFormatter(self.__client_addr),
  386. ZoneFormatter(self.__zname, self.__zclass),
  387. RRsetFormatter(rrset), rcode)
  388. return rcode
  389. else:
  390. if not self.__prereq_rrset_exists(rrset):
  391. rcode = Rcode.NXRRSET()
  392. logger.info(LIBDDNS_PREREQ_RRSET_EXISTS_FAILED,
  393. ClientFormatter(self.__client_addr),
  394. ZoneFormatter(self.__zname, self.__zclass),
  395. RRsetFormatter(rrset), rcode)
  396. return rcode
  397. elif rrset.get_class() == RRClass.NONE():
  398. if rrset.get_ttl().get_value() != 0 or\
  399. rrset.get_rdata_count() != 0:
  400. logger.info(LIBDDNS_PREREQ_FORMERR_NONE,
  401. ClientFormatter(self.__client_addr),
  402. ZoneFormatter(self.__zname, self.__zclass),
  403. RRsetFormatter(rrset))
  404. return Rcode.FORMERR()
  405. elif rrset.get_type() == RRType.ANY():
  406. if not self.__prereq_name_not_in_use(rrset):
  407. rcode = Rcode.YXDOMAIN()
  408. logger.info(LIBDDNS_PREREQ_NAME_NOT_IN_USE_FAILED,
  409. ClientFormatter(self.__client_addr),
  410. ZoneFormatter(self.__zname, self.__zclass),
  411. RRsetFormatter(rrset), rcode)
  412. return rcode
  413. else:
  414. if not self.__prereq_rrset_does_not_exist(rrset):
  415. rcode = Rcode.YXRRSET()
  416. logger.info(LIBDDNS_PREREQ_RRSET_DOES_NOT_EXIST_FAILED,
  417. ClientFormatter(self.__client_addr),
  418. ZoneFormatter(self.__zname, self.__zclass),
  419. RRsetFormatter(rrset), rcode)
  420. return rcode
  421. elif rrset.get_class() == self.__zclass:
  422. if rrset.get_ttl().get_value() != 0:
  423. logger.info(LIBDDNS_PREREQ_FORMERR,
  424. ClientFormatter(self.__client_addr),
  425. ZoneFormatter(self.__zname, self.__zclass),
  426. RRsetFormatter(rrset))
  427. return Rcode.FORMERR()
  428. else:
  429. collect_rrsets(exact_match_rrsets, rrset)
  430. else:
  431. logger.info(LIBDDNS_PREREQ_FORMERR_CLASS,
  432. ClientFormatter(self.__client_addr),
  433. ZoneFormatter(self.__zname, self.__zclass),
  434. RRsetFormatter(rrset))
  435. return Rcode.FORMERR()
  436. for collected_rrset in exact_match_rrsets:
  437. if not self.__prereq_rrset_exists_value(collected_rrset):
  438. rcode = Rcode.NXRRSET()
  439. logger.info(LIBDDNS_PREREQ_RRSET_EXISTS_VAL_FAILED,
  440. ClientFormatter(self.__client_addr),
  441. ZoneFormatter(self.__zname, self.__zclass),
  442. RRsetFormatter(collected_rrset), rcode)
  443. return rcode
  444. # All prerequisites are satisfied
  445. return Rcode.NOERROR()
  446. def __set_soa_rrset(self, rrset):
  447. '''Sets the given rrset to the member __added_soa (which
  448. is used by __do_update for updating the SOA record'''
  449. self.__added_soa = rrset
  450. def __do_prescan(self):
  451. '''Perform the prescan as defined in RFC2136 section 3.4.1.
  452. This method has a side-effect; it sets self._new_soa if
  453. it encounters the addition of a SOA record in the update
  454. list (so serial can be checked by update later, etc.).
  455. It puts the added SOA in self.__added_soa.
  456. '''
  457. for rrset in self.__message.get_section(SECTION_UPDATE):
  458. if not self.__check_in_zone(rrset):
  459. logger.info(LIBDDNS_UPDATE_NOTZONE,
  460. ClientFormatter(self.__client_addr),
  461. ZoneFormatter(self.__zname, self.__zclass),
  462. RRsetFormatter(rrset))
  463. return Rcode.NOTZONE()
  464. if rrset.get_class() == self.__zclass:
  465. # In fact, all metatypes are in a specific range,
  466. # so one check can test TKEY to ANY
  467. # (some value check is needed anyway, since we do
  468. # not have defined RRtypes for MAILA and MAILB)
  469. if rrset.get_type().get_code() >= 249:
  470. logger.info(LIBDDNS_UPDATE_ADD_BAD_TYPE,
  471. ClientFormatter(self.__client_addr),
  472. ZoneFormatter(self.__zname, self.__zclass),
  473. RRsetFormatter(rrset))
  474. return Rcode.FORMERR()
  475. if rrset.get_type() == RRType.SOA():
  476. # In case there's multiple soa records in the update
  477. # somehow, just take the last
  478. for rr in foreach_rr(rrset):
  479. self.__set_soa_rrset(rr)
  480. elif rrset.get_class() == RRClass.ANY():
  481. if rrset.get_ttl().get_value() != 0:
  482. logger.info(LIBDDNS_UPDATE_DELETE_NONZERO_TTL,
  483. ClientFormatter(self.__client_addr),
  484. ZoneFormatter(self.__zname, self.__zclass),
  485. RRsetFormatter(rrset))
  486. return Rcode.FORMERR()
  487. if rrset.get_rdata_count() > 0:
  488. logger.info(LIBDDNS_UPDATE_DELETE_RRSET_NOT_EMPTY,
  489. ClientFormatter(self.__client_addr),
  490. ZoneFormatter(self.__zname, self.__zclass),
  491. RRsetFormatter(rrset))
  492. return Rcode.FORMERR()
  493. if rrset.get_type().get_code() >= 249 and\
  494. rrset.get_type().get_code() <= 254:
  495. logger.info(LIBDDNS_UPDATE_DELETE_BAD_TYPE,
  496. ClientFormatter(self.__client_addr),
  497. ZoneFormatter(self.__zname, self.__zclass),
  498. RRsetFormatter(rrset))
  499. return Rcode.FORMERR()
  500. elif rrset.get_class() == RRClass.NONE():
  501. if rrset.get_ttl().get_value() != 0:
  502. logger.info(LIBDDNS_UPDATE_DELETE_RR_NONZERO_TTL,
  503. ClientFormatter(self.__client_addr),
  504. ZoneFormatter(self.__zname, self.__zclass),
  505. RRsetFormatter(rrset))
  506. return Rcode.FORMERR()
  507. if rrset.get_type().get_code() >= 249:
  508. logger.info(LIBDDNS_UPDATE_DELETE_RR_BAD_TYPE,
  509. ClientFormatter(self.__client_addr),
  510. ZoneFormatter(self.__zname, self.__zclass),
  511. RRsetFormatter(rrset))
  512. return Rcode.FORMERR()
  513. else:
  514. logger.info(LIBDDNS_UPDATE_BAD_CLASS,
  515. ClientFormatter(self.__client_addr),
  516. ZoneFormatter(self.__zname, self.__zclass),
  517. RRsetFormatter(rrset))
  518. return Rcode.FORMERR()
  519. return Rcode.NOERROR()
  520. def __do_update_add_single_rr(self, rr, existing_rrset):
  521. '''Helper for __do_update_add_rrs_to_rrset: only add the
  522. rr if it is not present yet
  523. (note that rr here should already be a single-rr rrset)
  524. '''
  525. if existing_rrset is None:
  526. self.__diff.add_data(rr)
  527. else:
  528. rr_rdata = rr.get_rdata()[0]
  529. if not rr_rdata in existing_rrset.get_rdata():
  530. self.__diff.add_data(rr)
  531. def __do_update_add_rrs_to_rrset(self, rrset):
  532. '''Add the rrs from the given rrset to the internal diff.
  533. There is handling for a number of special cases mentioned
  534. in RFC2136;
  535. - If the addition is a CNAME, but existing data at its
  536. name is not, the addition is ignored, and vice versa.
  537. - If it is a CNAME, and existing data is too, it is
  538. replaced (existing data is deleted)
  539. An additional restriction is that SOA data is ignored as
  540. well (it is handled separately by the __do_update method).
  541. Note that in the (near) future, this method may have
  542. addition special-cases processing.
  543. '''
  544. # For a number of cases, we may need to remove data in the zone
  545. # (note; SOA is handled separately by __do_update, so that one
  546. # is explicitely ignored here)
  547. if rrset.get_type() == RRType.SOA():
  548. return
  549. result, orig_rrset, _ = self.__diff.find(rrset.get_name(),
  550. rrset.get_type())
  551. if result == ZoneFinder.CNAME:
  552. # Ignore non-cname rrs that try to update CNAME records
  553. # (if rrset itself is a CNAME, the finder result would be
  554. # SUCCESS, see next case)
  555. return
  556. elif result == ZoneFinder.SUCCESS:
  557. # if update is cname, and zone rr is not, ignore
  558. if rrset.get_type() == RRType.CNAME():
  559. # Remove original CNAME record (the new one
  560. # is added below)
  561. self.__diff.delete_data(orig_rrset)
  562. # We do not have WKS support at this time, but if there
  563. # are special Update equality rules such as for WKS, and
  564. # we do have support for the type, this is where the check
  565. # (and potential delete) would go.
  566. elif result == ZoneFinder.NXRRSET:
  567. # There is data present, but not for this type.
  568. # If this type is CNAME, ignore the update
  569. if rrset.get_type() == RRType.CNAME():
  570. return
  571. for rr in foreach_rr(rrset):
  572. self.__do_update_add_single_rr(rr, orig_rrset)
  573. def __do_update_delete_rrset(self, rrset):
  574. '''Deletes the rrset with the name and type of the given
  575. rrset from the zone data (by putting all existing data
  576. in the internal diff as delete statements).
  577. Special cases: if the delete statement is for the
  578. zone's apex, and the type is either SOA or NS, it
  579. is ignored.'''
  580. result, to_delete, _ = self.__diff.find(rrset.get_name(),
  581. rrset.get_type())
  582. if result == ZoneFinder.SUCCESS:
  583. if to_delete.get_name() == self.__zname and\
  584. (to_delete.get_type() == RRType.SOA() or\
  585. to_delete.get_type() == RRType.NS()):
  586. # ignore
  587. return
  588. for rr in foreach_rr(to_delete):
  589. self.__diff.delete_data(rr)
  590. def __ns_deleter_helper(self, rrset):
  591. '''Special case helper for deleting NS resource records
  592. at the zone apex. In that scenario, the last NS record
  593. may never be removed (and any action that would do so
  594. should be ignored).
  595. '''
  596. # NOTE: This method is currently bad: it WILL delete all
  597. # NS rrsets in a number of cases.
  598. # We need an extension to our diff.py to handle this correctly
  599. # (see ticket #2016)
  600. # The related test is currently disabled. When this is fixed,
  601. # enable that test again.
  602. result, orig_rrset, _ = self.__diff.find(rrset.get_name(),
  603. rrset.get_type())
  604. # Even a real rrset comparison wouldn't help here...
  605. # The goal is to make sure that after deletion of the
  606. # given rrset, at least 1 NS record is left (at the apex).
  607. # So we make a (shallow) copy of the existing rrset,
  608. # and for each rdata in the to_delete set, we check if it wouldn't
  609. # delete the last one. If it would, that specific one is ignored.
  610. # If it would not, the rdata is removed from the temporary list
  611. orig_rrset_rdata = copy.copy(orig_rrset.get_rdata())
  612. for rdata in rrset.get_rdata():
  613. if len(orig_rrset_rdata) == 1 and rdata == orig_rrset_rdata[0]:
  614. # ignore
  615. continue
  616. else:
  617. # create an individual RRset for deletion
  618. to_delete = isc.dns.RRset(rrset.get_name(),
  619. rrset.get_class(),
  620. rrset.get_type(),
  621. rrset.get_ttl())
  622. to_delete.add_rdata(rdata)
  623. orig_rrset_rdata.remove(rdata)
  624. self.__diff.delete_data(to_delete)
  625. def __do_update_delete_name(self, rrset):
  626. '''Delete all data at the name of the given rrset,
  627. by adding all data found by find_all as delete statements
  628. to the internal diff.
  629. Special case: if the name is the zone's apex, SOA and
  630. NS records are kept.
  631. '''
  632. result, rrsets, flags = self.__diff.find_all(rrset.get_name())
  633. if result == ZoneFinder.SUCCESS and\
  634. (flags & ZoneFinder.RESULT_WILDCARD == 0):
  635. for to_delete in rrsets:
  636. # if name == self.__zname and type is soa or ns, don't delete!
  637. if to_delete.get_name() == self.__zname and\
  638. (to_delete.get_type() == RRType.SOA() or
  639. to_delete.get_type() == RRType.NS()):
  640. continue
  641. else:
  642. for rr in foreach_rr(to_delete):
  643. self.__diff.delete_data(rr)
  644. def __do_update_delete_rrs_from_rrset(self, rrset):
  645. '''Deletes all resource records in the given rrset from the
  646. zone. Resource records that do not exist are ignored.
  647. If the rrset if of type SOA, it is ignored.
  648. Uses the __ns_deleter_helper if the rrset's name is the
  649. zone's apex, and the type is NS.
  650. '''
  651. # Delete all rrs in the rrset, except if name=self.__zname and type=soa, or
  652. # type = ns and there is only one left (...)
  653. # The delete does not want class NONE, we would not have gotten here
  654. # if it wasn't, but now is a good time to change it to the zclass.
  655. to_delete = convert_rrset_class(rrset, self.__zclass)
  656. if rrset.get_name() == self.__zname:
  657. if rrset.get_type() == RRType.SOA():
  658. # ignore
  659. return
  660. elif rrset.get_type() == RRType.NS():
  661. # hmm. okay. annoying. There must be at least one left,
  662. # delegate to helper method
  663. self.__ns_deleter_helper(to_delete)
  664. return
  665. for rr in foreach_rr(to_delete):
  666. self.__diff.delete_data(rr)
  667. def __update_soa(self):
  668. '''Checks the member value __added_soa, and depending on
  669. whether it has been set and what its value is, creates
  670. a new SOA if necessary.
  671. Then removes the original SOA and adds the new one,
  672. by adding the needed operations to the internal diff.'''
  673. # Get the existing SOA
  674. # if a new soa was specified, add that one, otherwise, do the
  675. # serial magic and add the newly created one
  676. # get it from DS and to increment and stuff
  677. result, old_soa, _ = self.__diff.find(self.__zname, RRType.SOA())
  678. if self.__added_soa is not None:
  679. new_soa = self.__added_soa
  680. # serial check goes here
  681. else:
  682. new_soa = old_soa
  683. # increment goes here
  684. self.__diff.delete_data(old_soa)
  685. self.__diff.add_data(new_soa)
  686. def __do_update(self):
  687. '''Scan, check, and execute the Update section in the
  688. DDNS Update message.
  689. Returns an Rcode to signal the result (NOERROR upon success,
  690. any error result otherwise).
  691. '''
  692. # prescan
  693. prescan_result = self.__do_prescan()
  694. if prescan_result != Rcode.NOERROR():
  695. return prescan_result
  696. # update
  697. try:
  698. # Do special handling for SOA first
  699. self.__update_soa()
  700. # Algorithm from RFC2136 Section 3.4
  701. # Note that this works on full rrsets, not individual RRs.
  702. # Some checks might be easier with individual RRs, but only if we
  703. # would use the ZoneUpdater directly (so we can query the
  704. # 'zone-as-it-would-be-so-far'. However, due to the current use
  705. # of the Diff class, this is not the case, and therefore it
  706. # is easier to work with full rrsets for the most parts
  707. # (less lookups needed; conversion to individual rrs is
  708. # the same effort whether it is done here or in the several
  709. # do_update statements)
  710. for rrset in self.__message.get_section(SECTION_UPDATE):
  711. if rrset.get_class() == self.__zclass:
  712. self.__do_update_add_rrs_to_rrset(rrset)
  713. elif rrset.get_class() == RRClass.ANY():
  714. if rrset.get_type() == RRType.ANY():
  715. self.__do_update_delete_name(rrset)
  716. else:
  717. self.__do_update_delete_rrset(rrset)
  718. elif rrset.get_class() == RRClass.NONE():
  719. self.__do_update_delete_rrs_from_rrset(rrset)
  720. self.__diff.commit()
  721. return Rcode.NOERROR()
  722. except isc.datasrc.Error as dse:
  723. logger.info(LIBDDNS_UPDATE_DATASRC_ERROR, dse)
  724. return Rcode.SERVFAIL()
  725. except Exception as uce:
  726. logger.error(LIBDDNS_UPDATE_UNCAUGHT_EXCEPTION,
  727. ClientFormatter(self.__client_addr),
  728. ZoneFormatter(self.__zname, self.__zclass),
  729. uce)
  730. return Rcode.SERVFAIL()