session.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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. # conceptual code that would follow
  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. __finder: A ZoneFinder for this zone
  203. If this method raises an exception, these members are not set
  204. '''
  205. # Validation: the zone section must contain exactly one question,
  206. # and it must be of type SOA.
  207. n_zones = self.__message.get_rr_count(SECTION_ZONE)
  208. if n_zones != 1:
  209. raise UpdateError('Invalid number of records in zone section: ' +
  210. str(n_zones), None, None, Rcode.FORMERR())
  211. zrecord = self.__message.get_question()[0]
  212. if zrecord.get_type() != RRType.SOA():
  213. raise UpdateError('update zone section contains non-SOA',
  214. None, None, Rcode.FORMERR())
  215. # See if we're serving a primary zone specified in the zone section.
  216. zname = zrecord.get_name()
  217. zclass = zrecord.get_class()
  218. zone_type, datasrc_client = self.__zone_config.find_zone(zname, zclass)
  219. if zone_type == isc.ddns.zone_config.ZONE_PRIMARY:
  220. # create an ixfr-out-friendly diff structure to work on
  221. self.__diff = isc.xfrin.diff.Diff(datasrc_client, zname,
  222. journaling=True,
  223. single_update_mode=True)
  224. # Note that while it is really the ZoneUpdater that is set
  225. # here, it is still called finder, as the only methods that
  226. # are and should be used on this object are find() and find_all()
  227. # (ZoneUpdater provides the ZoneFinder interface itself, no
  228. # separate get_zone_finder())
  229. self.__finder = self.__diff.get_updater()
  230. self.__zname = zname
  231. self.__zclass = zclass
  232. self.__datasrc_client = datasrc_client
  233. return
  234. elif zone_type == isc.ddns.zone_config.ZONE_SECONDARY:
  235. # We are a secondary server; since we don't yet support update
  236. # forwarding, we return 'not implemented'.
  237. logger.debug(DBGLVL_TRACE_BASIC, LIBDDNS_UPDATE_FORWARD_FAIL,
  238. ClientFormatter(self.__client_addr, self.__tsig),
  239. ZoneFormatter(zname, zclass))
  240. raise UpdateError('forward', zname, zclass, Rcode.NOTIMP(), True)
  241. # zone wasn't found
  242. logger.debug(DBGLVL_TRACE_BASIC, LIBDDNS_UPDATE_NOTAUTH,
  243. ClientFormatter(self.__client_addr, self.__tsig),
  244. ZoneFormatter(zname, zclass))
  245. raise UpdateError('notauth', zname, zclass, Rcode.NOTAUTH(), True)
  246. def __check_update_acl(self, zname, zclass):
  247. '''Apply update ACL for the zone to be updated.'''
  248. acl = self.__zone_config.get_update_acl(zname, zclass)
  249. action = acl.execute(isc.acl.dns.RequestContext(
  250. (self.__client_addr[0], self.__client_addr[1]), self.__tsig))
  251. if action == REJECT:
  252. logger.info(LIBDDNS_UPDATE_DENIED,
  253. ClientFormatter(self.__client_addr, self.__tsig),
  254. ZoneFormatter(zname, zclass))
  255. raise UpdateError('rejected', zname, zclass, Rcode.REFUSED(), True)
  256. if action == DROP:
  257. logger.info(LIBDDNS_UPDATE_DROPPED,
  258. ClientFormatter(self.__client_addr, self.__tsig),
  259. ZoneFormatter(zname, zclass))
  260. raise UpdateError('dropped', zname, zclass, None, True)
  261. logger.debug(logger.DBGLVL_TRACE_BASIC, LIBDDNS_UPDATE_APPROVED,
  262. ClientFormatter(self.__client_addr, self.__tsig),
  263. ZoneFormatter(zname, zclass))
  264. def __make_response(self, rcode):
  265. '''Transform the internal message to the update response.
  266. According RFC2136 Section 3.8, the zone section will be cleared
  267. as well as other sections. The response Rcode will be set to the
  268. given value.
  269. '''
  270. self.__message.make_response()
  271. self.__message.clear_section(SECTION_ZONE)
  272. self.__message.set_rcode(rcode)
  273. def __prereq_rrset_exists(self, rrset):
  274. '''Check whether an rrset with the given name and type exists. Class,
  275. TTL, and Rdata (if any) of the given RRset are ignored.
  276. RFC2136 Section 2.4.1.
  277. Returns True if the prerequisite is satisfied, False otherwise.
  278. Note: the only thing used in the call to find() here is the
  279. result status. The actual data is immediately dropped. As
  280. a future optimization, we may want to add a find() option to
  281. only return what the result code would be (and not read/copy
  282. any actual data).
  283. '''
  284. result, _, _ = self.__finder.find(rrset.get_name(), rrset.get_type(),
  285. ZoneFinder.NO_WILDCARD |
  286. ZoneFinder.FIND_GLUE_OK)
  287. return result == ZoneFinder.SUCCESS
  288. def __prereq_rrset_exists_value(self, rrset):
  289. '''Check whether an rrset that matches name, type, and rdata(s) of the
  290. given rrset exists.
  291. RFC2136 Section 2.4.2
  292. Returns True if the prerequisite is satisfied, False otherwise.
  293. '''
  294. result, found_rrset, _ = self.__finder.find(rrset.get_name(),
  295. rrset.get_type(),
  296. ZoneFinder.NO_WILDCARD |
  297. ZoneFinder.FIND_GLUE_OK)
  298. if result == ZoneFinder.SUCCESS and\
  299. rrset.get_name() == found_rrset.get_name() and\
  300. rrset.get_type() == found_rrset.get_type():
  301. # We need to match all actual RRs, unfortunately there is no
  302. # direct order-independent comparison for rrsets, so this
  303. # a slightly inefficient way to handle that.
  304. # shallow copy of the rdata list, so we are sure that this
  305. # loop does not mess with actual data.
  306. found_rdata = copy.copy(found_rrset.get_rdata())
  307. for rdata in rrset.get_rdata():
  308. if rdata in found_rdata:
  309. found_rdata.remove(rdata)
  310. else:
  311. return False
  312. return len(found_rdata) == 0
  313. return False
  314. def __prereq_rrset_does_not_exist(self, rrset):
  315. '''Check whether no rrsets with the same name and type as the given
  316. rrset exist.
  317. RFC2136 Section 2.4.3.
  318. Returns True if the prerequisite is satisfied, False otherwise.
  319. '''
  320. return not self.__prereq_rrset_exists(rrset)
  321. def __prereq_name_in_use(self, rrset):
  322. '''Check whether the name of the given RRset is in use (i.e. has
  323. 1 or more RRs).
  324. RFC2136 Section 2.4.4
  325. Returns True if the prerequisite is satisfied, False otherwise.
  326. Note: the only thing used in the call to find_all() here is
  327. the result status. The actual data is immediately dropped. As
  328. a future optimization, we may want to add a find_all() option
  329. to only return what the result code would be (and not read/copy
  330. any actual data).
  331. '''
  332. result, rrsets, flags = self.__finder.find_all(rrset.get_name(),
  333. ZoneFinder.NO_WILDCARD |
  334. ZoneFinder.FIND_GLUE_OK)
  335. if result == ZoneFinder.SUCCESS and\
  336. (flags & ZoneFinder.RESULT_WILDCARD == 0):
  337. return True
  338. return False
  339. def __prereq_name_not_in_use(self, rrset):
  340. '''Check whether the name of the given RRset is not in use (i.e. does
  341. not exist at all, or is an empty nonterminal.
  342. RFC2136 Section 2.4.5.
  343. Returns True if the prerequisite is satisfied, False otherwise.
  344. '''
  345. return not self.__prereq_name_in_use(rrset)
  346. def __check_in_zone(self, rrset):
  347. '''Returns true if the name of the given rrset is equal to
  348. or a subdomain of the zname from the Zone Section.'''
  349. relation = rrset.get_name().compare(self.__zname).get_relation()
  350. return relation == NameComparisonResult.SUBDOMAIN or\
  351. relation == NameComparisonResult.EQUAL
  352. def __check_prerequisites(self):
  353. '''Check the prerequisites section of the UPDATE Message.
  354. RFC2136 Section 2.4.
  355. Returns a dns Rcode signaling either no error (Rcode.NOERROR())
  356. or that one of the prerequisites failed (any other Rcode).
  357. '''
  358. # Temporary array to store exact-match RRsets
  359. exact_match_rrsets = []
  360. for rrset in self.__message.get_section(SECTION_PREREQUISITE):
  361. # First check if the name is in the zone
  362. if not self.__check_in_zone(rrset):
  363. logger.info(LIBDDNS_PREREQ_NOTZONE,
  364. ClientFormatter(self.__client_addr),
  365. ZoneFormatter(self.__zname, self.__zclass),
  366. RRsetFormatter(rrset))
  367. return Rcode.NOTZONE()
  368. # Algorithm taken from RFC2136 Section 3.2
  369. if rrset.get_class() == RRClass.ANY():
  370. if rrset.get_ttl().get_value() != 0 or\
  371. rrset.get_rdata_count() != 0:
  372. logger.info(LIBDDNS_PREREQ_FORMERR_ANY,
  373. ClientFormatter(self.__client_addr),
  374. ZoneFormatter(self.__zname, self.__zclass),
  375. RRsetFormatter(rrset))
  376. return Rcode.FORMERR()
  377. elif rrset.get_type() == RRType.ANY():
  378. if not self.__prereq_name_in_use(rrset):
  379. rcode = Rcode.NXDOMAIN()
  380. logger.info(LIBDDNS_PREREQ_NAME_IN_USE_FAILED,
  381. ClientFormatter(self.__client_addr),
  382. ZoneFormatter(self.__zname, self.__zclass),
  383. RRsetFormatter(rrset), rcode)
  384. return rcode
  385. else:
  386. if not self.__prereq_rrset_exists(rrset):
  387. rcode = Rcode.NXRRSET()
  388. logger.info(LIBDDNS_PREREQ_RRSET_EXISTS_FAILED,
  389. ClientFormatter(self.__client_addr),
  390. ZoneFormatter(self.__zname, self.__zclass),
  391. RRsetFormatter(rrset), rcode)
  392. return rcode
  393. elif rrset.get_class() == RRClass.NONE():
  394. if rrset.get_ttl().get_value() != 0 or\
  395. rrset.get_rdata_count() != 0:
  396. logger.info(LIBDDNS_PREREQ_FORMERR_NONE,
  397. ClientFormatter(self.__client_addr),
  398. ZoneFormatter(self.__zname, self.__zclass),
  399. RRsetFormatter(rrset))
  400. return Rcode.FORMERR()
  401. elif rrset.get_type() == RRType.ANY():
  402. if not self.__prereq_name_not_in_use(rrset):
  403. rcode = Rcode.YXDOMAIN()
  404. logger.info(LIBDDNS_PREREQ_NAME_NOT_IN_USE_FAILED,
  405. ClientFormatter(self.__client_addr),
  406. ZoneFormatter(self.__zname, self.__zclass),
  407. RRsetFormatter(rrset), rcode)
  408. return rcode
  409. else:
  410. if not self.__prereq_rrset_does_not_exist(rrset):
  411. rcode = Rcode.YXRRSET()
  412. logger.info(LIBDDNS_PREREQ_RRSET_DOES_NOT_EXIST_FAILED,
  413. ClientFormatter(self.__client_addr),
  414. ZoneFormatter(self.__zname, self.__zclass),
  415. RRsetFormatter(rrset), rcode)
  416. return rcode
  417. elif rrset.get_class() == self.__zclass:
  418. if rrset.get_ttl().get_value() != 0:
  419. logger.info(LIBDDNS_PREREQ_FORMERR,
  420. ClientFormatter(self.__client_addr),
  421. ZoneFormatter(self.__zname, self.__zclass),
  422. RRsetFormatter(rrset))
  423. return Rcode.FORMERR()
  424. else:
  425. collect_rrsets(exact_match_rrsets, rrset)
  426. else:
  427. logger.info(LIBDDNS_PREREQ_FORMERR_CLASS,
  428. ClientFormatter(self.__client_addr),
  429. ZoneFormatter(self.__zname, self.__zclass),
  430. RRsetFormatter(rrset))
  431. return Rcode.FORMERR()
  432. for collected_rrset in exact_match_rrsets:
  433. if not self.__prereq_rrset_exists_value(collected_rrset):
  434. rcode = Rcode.NXRRSET()
  435. logger.info(LIBDDNS_PREREQ_RRSET_EXISTS_VAL_FAILED,
  436. ClientFormatter(self.__client_addr),
  437. ZoneFormatter(self.__zname, self.__zclass),
  438. RRsetFormatter(collected_rrset), rcode)
  439. return rcode
  440. # All prerequisites are satisfied
  441. return Rcode.NOERROR()
  442. def __set_soa_rrset(self, rrset):
  443. '''Sets the given rrset to the member __added_soa (which
  444. is used by __do_update for updating the SOA record'''
  445. self.__added_soa = rrset
  446. def __do_prescan(self):
  447. '''Perform the prescan as defined in RFC2136 section 3.4.1.
  448. This method has a side-effect; it sets self._new_soa if
  449. it encounters the addition of a SOA record in the update
  450. list (so serial can be checked by update later, etc.).
  451. It puts the added SOA in self.__added_soa.
  452. '''
  453. for rrset in self.__message.get_section(SECTION_UPDATE):
  454. if not self.__check_in_zone(rrset):
  455. logger.info(LIBDDNS_UPDATE_NOTZONE,
  456. ClientFormatter(self.__client_addr),
  457. ZoneFormatter(self.__zname, self.__zclass),
  458. RRsetFormatter(rrset))
  459. return Rcode.NOTZONE()
  460. if rrset.get_class() == self.__zclass:
  461. # In fact, all metatypes are in a specific range,
  462. # so one check can test TKEY to ANY
  463. # (some value check is needed anyway, since we do
  464. # not have defined RRtypes for MAILA and MAILB)
  465. if rrset.get_type().get_code() >= 249:
  466. logger.info(LIBDDNS_UPDATE_ADD_BAD_TYPE,
  467. ClientFormatter(self.__client_addr),
  468. ZoneFormatter(self.__zname, self.__zclass),
  469. RRsetFormatter(rrset))
  470. return Rcode.FORMERR()
  471. if rrset.get_type() == RRType.SOA():
  472. # In case there's multiple soa records in the update
  473. # somehow, just take the last
  474. for rr in foreach_rr(rrset):
  475. self.__set_soa_rrset(rr)
  476. elif rrset.get_class() == RRClass.ANY():
  477. if rrset.get_ttl().get_value() != 0:
  478. logger.info(LIBDDNS_UPDATE_DELETE_NONZERO_TTL,
  479. ClientFormatter(self.__client_addr),
  480. ZoneFormatter(self.__zname, self.__zclass),
  481. RRsetFormatter(rrset))
  482. return Rcode.FORMERR()
  483. if rrset.get_rdata_count() > 0:
  484. logger.info(LIBDDNS_UPDATE_DELETE_RRSET_NOT_EMPTY,
  485. ClientFormatter(self.__client_addr),
  486. ZoneFormatter(self.__zname, self.__zclass),
  487. RRsetFormatter(rrset))
  488. return Rcode.FORMERR()
  489. if rrset.get_type().get_code() >= 249 and\
  490. rrset.get_type().get_code() <= 254:
  491. logger.info(LIBDDNS_UPDATE_DELETE_BAD_TYPE,
  492. ClientFormatter(self.__client_addr),
  493. ZoneFormatter(self.__zname, self.__zclass),
  494. RRsetFormatter(rrset))
  495. return Rcode.FORMERR()
  496. elif rrset.get_class() == RRClass.NONE():
  497. if rrset.get_ttl().get_value() != 0:
  498. logger.info(LIBDDNS_UPDATE_DELETE_RR_NONZERO_TTL,
  499. ClientFormatter(self.__client_addr),
  500. ZoneFormatter(self.__zname, self.__zclass),
  501. RRsetFormatter(rrset))
  502. return Rcode.FORMERR()
  503. if rrset.get_type().get_code() >= 249:
  504. logger.info(LIBDDNS_UPDATE_DELETE_RR_BAD_TYPE,
  505. ClientFormatter(self.__client_addr),
  506. ZoneFormatter(self.__zname, self.__zclass),
  507. RRsetFormatter(rrset))
  508. return Rcode.FORMERR()
  509. else:
  510. logger.info(LIBDDNS_UPDATE_BAD_CLASS,
  511. ClientFormatter(self.__client_addr),
  512. ZoneFormatter(self.__zname, self.__zclass),
  513. RRsetFormatter(rrset))
  514. return Rcode.FORMERR()
  515. return Rcode.NOERROR()
  516. def __do_update_add_single_rr(self, rr, existing_rrset):
  517. '''Helper for __do_update_add_rrs_to_rrset: only add the
  518. rr if it is not present yet
  519. (note that rr here should already be a single-rr rrset)
  520. '''
  521. if existing_rrset is None:
  522. self.__diff.add_data(rr)
  523. else:
  524. rr_rdata = rr.get_rdata()[0]
  525. if not rr_rdata in existing_rrset.get_rdata():
  526. self.__diff.add_data(rr)
  527. def __do_update_add_rrs_to_rrset(self, rrset):
  528. '''Add the rrs from the given rrset to the internal diff.
  529. There is handling for a number of special cases mentioned
  530. in RFC2136;
  531. - If the addition is a CNAME, but existing data at its
  532. name is not, the addition is ignored, and vice versa.
  533. - If it is a CNAME, and existing data is too, it is
  534. replaced (existing data is deleted)
  535. An additional restriction is that SOA data is ignored as
  536. well (it is handled separately by the __do_update method).
  537. Note that in the (near) future, this method may have
  538. addition special-cases processing.
  539. '''
  540. # For a number of cases, we may need to remove data in the zone
  541. # (note; SOA is handled separately by __do_update, so that one
  542. # is explicitely ignored here)
  543. if rrset.get_type() == RRType.SOA():
  544. return
  545. result, orig_rrset, _ = self.__finder.find(rrset.get_name(),
  546. rrset.get_type(),
  547. ZoneFinder.NO_WILDCARD |
  548. ZoneFinder.FIND_GLUE_OK)
  549. if result == ZoneFinder.CNAME:
  550. # Ignore non-cname rrs that try to update CNAME records
  551. # (if rrset itself is a CNAME, the finder result would be
  552. # SUCCESS, see next case)
  553. return
  554. elif result == ZoneFinder.SUCCESS:
  555. # if update is cname, and zone rr is not, ignore
  556. if rrset.get_type() == RRType.CNAME():
  557. # Remove original CNAME record (the new one
  558. # is added below)
  559. self.__diff.delete_data(orig_rrset)
  560. # We do not have WKS support at this time, but if there
  561. # are special Update equality rules such as for WKS, and
  562. # we do have support for the type, this is where the check
  563. # (and potential delete) would go.
  564. elif result == ZoneFinder.NXRRSET:
  565. # There is data present, but not for this type.
  566. # If this type is CNAME, ignore the update
  567. if rrset.get_type() == RRType.CNAME():
  568. return
  569. for rr in foreach_rr(rrset):
  570. self.__do_update_add_single_rr(rr, orig_rrset)
  571. def __do_update_delete_rrset(self, rrset):
  572. '''Deletes the rrset with the name and type of the given
  573. rrset from the zone data (by putting all existing data
  574. in the internal diff as delete statements).
  575. Special cases: if the delete statement is for the
  576. zone's apex, and the type is either SOA or NS, it
  577. is ignored.'''
  578. result, to_delete, _ = self.__finder.find(rrset.get_name(),
  579. rrset.get_type(),
  580. ZoneFinder.NO_WILDCARD |
  581. ZoneFinder.FIND_GLUE_OK)
  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.__finder.find(rrset.get_name(),
  603. rrset.get_type(),
  604. ZoneFinder.NO_WILDCARD |
  605. ZoneFinder.FIND_GLUE_OK)
  606. # Even a real rrset comparison wouldn't help here...
  607. # The goal is to make sure that after deletion of the
  608. # given rrset, at least 1 NS record is left (at the apex).
  609. # So we make a (shallow) copy of the existing rrset,
  610. # and for each rdata in the to_delete set, we check if it wouldn't
  611. # delete the last one. If it would, that specific one is ignored.
  612. # If it would not, the rdata is removed from the temporary list
  613. orig_rrset_rdata = copy.copy(orig_rrset.get_rdata())
  614. for rdata in rrset.get_rdata():
  615. if len(orig_rrset_rdata) == 1 and rdata == orig_rrset_rdata[0]:
  616. # ignore
  617. continue
  618. else:
  619. # create an individual RRset for deletion
  620. to_delete = isc.dns.RRset(rrset.get_name(),
  621. rrset.get_class(),
  622. rrset.get_type(),
  623. rrset.get_ttl())
  624. to_delete.add_rdata(rdata)
  625. orig_rrset_rdata.remove(rdata)
  626. self.__diff.delete_data(to_delete)
  627. def __do_update_delete_name(self, rrset):
  628. '''Delete all data at the name of the given rrset,
  629. by adding all data found by find_all as delete statements
  630. to the internal diff.
  631. Special case: if the name is the zone's apex, SOA and
  632. NS records are kept.
  633. '''
  634. result, rrsets, flags = self.__finder.find_all(rrset.get_name(),
  635. ZoneFinder.NO_WILDCARD |
  636. ZoneFinder.FIND_GLUE_OK)
  637. if result == ZoneFinder.SUCCESS and\
  638. (flags & ZoneFinder.RESULT_WILDCARD == 0):
  639. for to_delete in rrsets:
  640. # if name == self.__zname and type is soa or ns, don't delete!
  641. if to_delete.get_name() == self.__zname and\
  642. (to_delete.get_type() == RRType.SOA() or
  643. to_delete.get_type() == RRType.NS()):
  644. continue
  645. else:
  646. for rr in foreach_rr(to_delete):
  647. self.__diff.delete_data(rr)
  648. def __do_update_delete_rrs_from_rrset(self, rrset):
  649. '''Deletes all resource records in the given rrset from the
  650. zone. Resource records that do not exist are ignored.
  651. If the rrset if of type SOA, it is ignored.
  652. Uses the __ns_deleter_helper if the rrset's name is the
  653. zone's apex, and the type is NS.
  654. '''
  655. # Delete all rrs in the rrset, except if name=self.__zname and type=soa, or
  656. # type = ns and there is only one left (...)
  657. # The delete does not want class NONE, we would not have gotten here
  658. # if it wasn't, but now is a good time to change it to the zclass.
  659. to_delete = convert_rrset_class(rrset, self.__zclass)
  660. if rrset.get_name() == self.__zname:
  661. if rrset.get_type() == RRType.SOA():
  662. # ignore
  663. return
  664. elif rrset.get_type() == RRType.NS():
  665. # hmm. okay. annoying. There must be at least one left,
  666. # delegate to helper method
  667. self.__ns_deleter_helper(to_delete)
  668. return
  669. for rr in foreach_rr(to_delete):
  670. self.__diff.delete_data(rr)
  671. def __update_soa(self):
  672. '''Checks the member value __added_soa, and depending on
  673. whether it has been set and what its value is, creates
  674. a new SOA if necessary.
  675. Then removes the original SOA and adds the new one,
  676. by adding the needed operations to the internal diff.'''
  677. # Get the existing SOA
  678. # if a new soa was specified, add that one, otherwise, do the
  679. # serial magic and add the newly created one
  680. # get it from DS and to increment and stuff
  681. result, old_soa, _ = self.__finder.find(self.__zname, RRType.SOA(),
  682. ZoneFinder.NO_WILDCARD |
  683. ZoneFinder.FIND_GLUE_OK)
  684. if self.__added_soa is not None:
  685. new_soa = self.__added_soa
  686. # serial check goes here
  687. else:
  688. new_soa = old_soa
  689. # increment goes here
  690. self.__diff.delete_data(old_soa)
  691. self.__diff.add_data(new_soa)
  692. def __do_update(self):
  693. '''Scan, check, and execute the Update section in the
  694. DDNS Update message.
  695. Returns an Rcode to signal the result (NOERROR upon success,
  696. any error result otherwise).
  697. '''
  698. # prescan
  699. prescan_result = self.__do_prescan()
  700. if prescan_result != Rcode.NOERROR():
  701. return prescan_result
  702. # update
  703. try:
  704. # Do special handling for SOA first
  705. self.__update_soa()
  706. # Algorithm from RFC2136 Section 3.4
  707. # Note that this works on full rrsets, not individual RRs.
  708. # Some checks might be easier with individual RRs, but only if we
  709. # would use the ZoneUpdater directly (so we can query the
  710. # 'zone-as-it-would-be-so-far'. However, due to the current use
  711. # of the Diff class, this is not the case, and therefore it
  712. # is easier to work with full rrsets for the most parts
  713. # (less lookups needed; conversion to individual rrs is
  714. # the same effort whether it is done here or in the several
  715. # do_update statements)
  716. for rrset in self.__message.get_section(SECTION_UPDATE):
  717. if rrset.get_class() == self.__zclass:
  718. self.__do_update_add_rrs_to_rrset(rrset)
  719. elif rrset.get_class() == RRClass.ANY():
  720. if rrset.get_type() == RRType.ANY():
  721. self.__do_update_delete_name(rrset)
  722. else:
  723. self.__do_update_delete_rrset(rrset)
  724. elif rrset.get_class() == RRClass.NONE():
  725. self.__do_update_delete_rrs_from_rrset(rrset)
  726. self.__diff.commit()
  727. return Rcode.NOERROR()
  728. except isc.datasrc.Error as dse:
  729. logger.info(LIBDDNS_UPDATE_DATASRC_ERROR, dse)
  730. return Rcode.SERVFAIL()
  731. except Exception as uce:
  732. logger.error(LIBDDNS_UPDATE_UNCAUGHT_EXCEPTION,
  733. ClientFormatter(self.__client_addr),
  734. ZoneFormatter(self.__zname, self.__zclass),
  735. uce)
  736. return Rcode.SERVFAIL()