session.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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. import copy
  24. # Result codes for UpdateSession.handle()
  25. UPDATE_SUCCESS = 0
  26. UPDATE_ERROR = 1
  27. UPDATE_DROP = 2
  28. # Convenient aliases of update-specific section names
  29. SECTION_ZONE = Message.SECTION_QUESTION
  30. SECTION_PREREQUISITE = Message.SECTION_ANSWER
  31. SECTION_UPDATE = Message.SECTION_AUTHORITY
  32. # Shortcut
  33. DBGLVL_TRACE_BASIC = logger.DBGLVL_TRACE_BASIC
  34. class UpdateError(Exception):
  35. '''Exception for general error in update request handling.
  36. This exception is intended to be used internally within this module.
  37. When UpdateSession.handle() encounters an error in handling an update
  38. request it can raise this exception to terminate the handling.
  39. This class is constructed with some information that may be useful for
  40. subsequent possible logging:
  41. - msg (string) A string explaining the error.
  42. - zname (isc.dns.Name) The zone name. Can be None when not identified.
  43. - zclass (isc.dns.RRClass) The zone class. Like zname, can be None.
  44. - rcode (isc.dns.RCode) The RCODE to be set in the response message.
  45. - nolog (bool) If True, it indicates there's no more need for logging.
  46. '''
  47. def __init__(self, msg, zname, zclass, rcode, nolog=False):
  48. Exception.__init__(self, msg)
  49. self.zname = zname
  50. self.zclass = zclass
  51. self.rcode = rcode
  52. self.nolog = nolog
  53. def foreach_rr_in_rrset(rrset, method, *kwargs):
  54. '''Helper function. For DDNS, in a number of cases, we need to
  55. treat the various RRs in a single RRset separately.
  56. Our libdns++ has no concept of RRs, so in that case,
  57. what we do is create a temporary 1-RR RRset for each Rdata
  58. in the RRset object.
  59. This method then calls the given method with the given args
  60. for each of the temporary rrsets (the rrset in *wargs is
  61. replaced by the temporary one)
  62. Note: if this method is useful in more places, we may want
  63. to move it out of ddns.
  64. Example:
  65. Say you have a method that prints a prexif string and an
  66. rrset, def my_print(prefix, rrset)
  67. Given an rrset my_rrset, you'd print the entire rrset
  68. with my_print("foo", rrset)
  69. And with this helper function, to print each rr invidually,
  70. you'd call
  71. foreach_rr_in_rrsetet(rrset, my_print, "foo", rrset)
  72. Note the rrset is needed twice, the first to identify it,
  73. the second as the 'real' argument to my_print (which is replaced
  74. by this function.
  75. '''
  76. result = None
  77. for rdata in rrset.get_rdata():
  78. tmp_rrset = isc.dns.RRset(rrset.get_name(),
  79. rrset.get_class(),
  80. rrset.get_type(),
  81. rrset.get_ttl())
  82. tmp_rrset.add_rdata(rdata)
  83. # Replace the rrset in the original arguments by our rrset
  84. args = [arg if arg != rrset else tmp_rrset for arg in kwargs]
  85. result = method(*args)
  86. return result
  87. def convert_rrset_class(rrset, rrclass):
  88. '''Returns a (new) rrset with the data from the given rrset,
  89. but of the given class. Useful to convert from NONE and ANY to
  90. a real class.
  91. Note that the caller should be careful what to convert;
  92. and DNS error that could happen during wire-format reading
  93. could technically occur here, and is not caught by this helper.
  94. '''
  95. new_rrset = isc.dns.RRset(rrset.get_name(), rrclass,
  96. rrset.get_type(), rrset.get_ttl())
  97. for rdata in rrset.get_rdata():
  98. # Rdata class is nof modifiable, and must match rrset's
  99. # class, so we need to to some ugly conversion here.
  100. # And we cannot use to_text() (since the class may be unknown)
  101. wire = rdata.to_wire(bytes())
  102. new_rrset.add_rdata(isc.dns.Rdata(rrset.get_type(), rrclass, wire))
  103. return new_rrset
  104. class DDNS_SOA:
  105. '''Class to handle the SOA in the DNS update '''
  106. def __get_serial_internal(self, origin_soa):
  107. '''Get serial number from soa'''
  108. return Serial(int(origin_soa.get_rdata()[0].to_text().split()[2]))
  109. def __write_soa_internal(self, origin_soa, soa_num):
  110. '''Write back serial number to soa'''
  111. new_soa = RRset(origin_soa.get_name(), origin_soa.get_class(),
  112. RRType.SOA(), origin_soa.get_ttl())
  113. soa_rdata_parts = origin_soa.get_rdata()[0].to_text().split()
  114. soa_rdata_parts[2] = str(soa_num.get_value())
  115. new_soa.add_rdata(Rdata(origin_soa.get_type(), origin_soa.get_class(),
  116. " ".join(soa_rdata_parts)))
  117. return new_soa
  118. def soa_update_check(self, origin_soa, new_soa):
  119. '''Check whether the new soa is valid. If the serial number is bigger
  120. than the old one, it is valid, then return True, otherwise, return
  121. False. Make sure the origin_soa and new_soa parameters are not none
  122. before invoke soa_update_check.
  123. Parameters:
  124. origin_soa, old SOA resource record.
  125. new_soa, new SOA resource record.
  126. Output:
  127. if the serial number of new soa is bigger than the old one, return
  128. True, otherwise return False.
  129. '''
  130. old_serial = self.__get_serial_internal(origin_soa)
  131. new_serial = self.__get_serial_internal(new_soa)
  132. if(new_serial > old_serial):
  133. return True
  134. else:
  135. return False
  136. def update_soa(self, origin_soa, inc_number = 1):
  137. ''' Update the soa number incrementally as RFC 2136. Please make sure
  138. that the origin_soa exists and not none before invoke this function.
  139. Parameters:
  140. origin_soa, the soa resource record which will be updated.
  141. inc_number, the number which will be added into the serial number of
  142. origin_soa, the default value is one.
  143. Output:
  144. The new origin soa whoes serial number has been updated.
  145. '''
  146. soa_num = self.__get_serial_internal(origin_soa)
  147. soa_num = soa_num + inc_number
  148. if soa_num.get_value() == 0:
  149. soa_num = soa_num + 1
  150. return self.__write_soa_internal(origin_soa, soa_num)
  151. class UpdateSession:
  152. '''Protocol handling for a single dynamic update request.
  153. This class is instantiated with a request message and some other
  154. information that will be used for handling the request. Its main
  155. method, handle(), will process the request, and normally build
  156. a response message according to the result. The application of this
  157. class can use the message to send a response to the client.
  158. '''
  159. def __init__(self, req_message, req_data, client_addr, zone_config):
  160. '''Constructor.
  161. Note: req_data is not really used as of #1512 but is listed since
  162. it's quite likely we need it in a subsequent task soon. We'll
  163. also need to get other parameters such as ACLs, for which, it's less
  164. clear in which form we want to get the information, so it's left
  165. open for now.
  166. Parameters:
  167. - req_message (isc.dns.Message) The request message. This must be
  168. in the PARSE mode.
  169. - req_data (binary) Wire format data of the request message.
  170. It will be used for TSIG verification if necessary.
  171. - client_addr (socket address) The address/port of the update client
  172. in the form of Python socket address object. This is mainly for
  173. logging and access control.
  174. - zone_config (ZoneConfig) A tentative container that encapsulates
  175. the server's zone configuration. See zone_config.py.
  176. (It'll soon need to be passed ACL in some way, too)
  177. '''
  178. self.__message = req_message
  179. self.__client_addr = client_addr
  180. self.__zone_config = zone_config
  181. self.__added_soa = None
  182. def get_message(self):
  183. '''Return the update message.
  184. After handle() is called, it's generally transformed to the response
  185. to be returned to the client; otherwise it would be identical to
  186. the request message passed on construction.
  187. '''
  188. return self.__message
  189. def handle(self):
  190. '''Handle the update request according to RFC2136.
  191. This method returns a tuple of the following three elements that
  192. indicate the result of the request.
  193. - Result code of the request processing, which are:
  194. UPDATE_SUCCESS Update request granted and succeeded.
  195. UPDATE_ERROR Some error happened to be reported in the response.
  196. UPDATE_DROP Error happened and no response should be sent.
  197. Except the case of UPDATE_DROP, the UpdateSession object will have
  198. created a response that is to be returned to the request client,
  199. which can be retrieved by get_message().
  200. - The name of the updated zone (isc.dns.Name object) in case of
  201. UPDATE_SUCCESS; otherwise None.
  202. - The RR class of the updated zone (isc.dns.RRClass object) in case
  203. of UPDATE_SUCCESS; otherwise None.
  204. '''
  205. try:
  206. self.__get_update_zone()
  207. # conceptual code that would follow
  208. prereq_result = self.__check_prerequisites()
  209. if prereq_result != Rcode.NOERROR():
  210. self.__make_response(prereq_result)
  211. return UPDATE_ERROR, self.__zname, self.__zclass
  212. # self.__check_update_acl()
  213. update_result = self.__do_update()
  214. if update_result != Rcode.NOERROR():
  215. self.__make_response(update_result)
  216. return UPDATE_ERROR, self.__zname, self.__zclass
  217. self.__make_response(Rcode.NOERROR())
  218. return UPDATE_SUCCESS, self.__zname, self.__zclass
  219. except UpdateError as e:
  220. if not e.nolog:
  221. logger.debug(logger.DBGLVL_TRACE_BASIC, LIBDDNS_UPDATE_ERROR,
  222. ClientFormatter(self.__client_addr),
  223. ZoneFormatter(e.zname, e.zclass), e)
  224. self.__make_response(e.rcode)
  225. return UPDATE_ERROR, None, None
  226. def __get_update_zone(self):
  227. '''Parse the zone section and find the zone to be updated.
  228. If the zone section is valid and the specified zone is found in
  229. the configuration, sets private member variables for this session:
  230. __datasrc_client: A matching data source that contains the specified
  231. zone
  232. __zname: The zone name as a Name object
  233. __zclass: The zone class as an RRClass object
  234. __finder: A ZoneFinder for this zone
  235. If this method raises an exception, these members are not set
  236. '''
  237. # Validation: the zone section must contain exactly one question,
  238. # and it must be of type SOA.
  239. n_zones = self.__message.get_rr_count(SECTION_ZONE)
  240. if n_zones != 1:
  241. raise UpdateError('Invalid number of records in zone section: ' +
  242. str(n_zones), None, None, Rcode.FORMERR())
  243. zrecord = self.__message.get_question()[0]
  244. if zrecord.get_type() != RRType.SOA():
  245. raise UpdateError('update zone section contains non-SOA',
  246. None, None, Rcode.FORMERR())
  247. # See if we're serving a primary zone specified in the zone section.
  248. zname = zrecord.get_name()
  249. zclass = zrecord.get_class()
  250. zone_type, datasrc_client = self.__zone_config.find_zone(zname, zclass)
  251. if zone_type == isc.ddns.zone_config.ZONE_PRIMARY:
  252. self.__zname = zname
  253. self.__zclass = zclass
  254. self.__datasrc_client = datasrc_client
  255. _, self.__finder = datasrc_client.find_zone(zname)
  256. return
  257. elif zone_type == isc.ddns.zone_config.ZONE_SECONDARY:
  258. # We are a secondary server; since we don't yet support update
  259. # forwarding, we return 'not implemented'.
  260. logger.debug(DBGLVL_TRACE_BASIC, LIBDDNS_UPDATE_FORWARD_FAIL,
  261. ClientFormatter(self.__client_addr),
  262. ZoneFormatter(zname, zclass))
  263. raise UpdateError('forward', zname, zclass, Rcode.NOTIMP(), True)
  264. # zone wasn't found
  265. logger.debug(DBGLVL_TRACE_BASIC, LIBDDNS_UPDATE_NOTAUTH,
  266. ClientFormatter(self.__client_addr),
  267. ZoneFormatter(zname, zclass))
  268. raise UpdateError('notauth', zname, zclass, Rcode.NOTAUTH(), True)
  269. def __make_response(self, rcode):
  270. '''Transform the internal message to the update response.
  271. According RFC2136 Section 3.8, the zone section will be cleared
  272. as well as other sections. The response Rcode will be set to the
  273. given value.
  274. '''
  275. self.__message.make_response()
  276. self.__message.clear_section(SECTION_ZONE)
  277. self.__message.set_rcode(rcode)
  278. def __prereq_rrset_exists(self, rrset):
  279. '''Check whether an rrset with the given name and type exists. Class,
  280. TTL, and Rdata (if any) of the given RRset are ignored.
  281. RFC2136 Section 2.4.1.
  282. Returns True if the prerequisite is satisfied, False otherwise.
  283. Note: the only thing used in the call to find() here is the
  284. result status. The actual data is immediately dropped. As
  285. a future optimization, we may want to add a find() option to
  286. only return what the result code would be (and not read/copy
  287. any actual data).
  288. '''
  289. result, _, _ = self.__finder.find(rrset.get_name(), rrset.get_type(),
  290. ZoneFinder.NO_WILDCARD |
  291. ZoneFinder.FIND_GLUE_OK)
  292. return result == ZoneFinder.SUCCESS
  293. def __prereq_rrset_exists_value(self, rrset):
  294. '''Check whether an rrset that matches name, type, and rdata(s) of the
  295. given rrset exists.
  296. RFC2136 Section 2.4.2
  297. Returns True if the prerequisite is satisfied, False otherwise.
  298. '''
  299. result, found_rrset, _ = self.__finder.find(rrset.get_name(),
  300. rrset.get_type(),
  301. ZoneFinder.NO_WILDCARD |
  302. ZoneFinder.FIND_GLUE_OK)
  303. if result == ZoneFinder.SUCCESS and\
  304. rrset.get_name() == found_rrset.get_name() and\
  305. rrset.get_type() == found_rrset.get_type():
  306. # We need to match all actual RRs, unfortunately there is no
  307. # direct order-independent comparison for rrsets, so this
  308. # a slightly inefficient way to handle that.
  309. # shallow copy of the rdata list, so we are sure that this
  310. # loop does not mess with actual data.
  311. found_rdata = copy.copy(found_rrset.get_rdata())
  312. for rdata in rrset.get_rdata():
  313. if rdata in found_rdata:
  314. found_rdata.remove(rdata)
  315. else:
  316. return False
  317. return len(found_rdata) == 0
  318. return False
  319. def __prereq_rrset_does_not_exist(self, rrset):
  320. '''Check whether no rrsets with the same name and type as the given
  321. rrset exist.
  322. RFC2136 Section 2.4.3.
  323. Returns True if the prerequisite is satisfied, False otherwise.
  324. '''
  325. return not self.__prereq_rrset_exists(rrset)
  326. def __prereq_name_in_use(self, rrset):
  327. '''Check whether the name of the given RRset is in use (i.e. has
  328. 1 or more RRs).
  329. RFC2136 Section 2.4.4
  330. Returns True if the prerequisite is satisfied, False otherwise.
  331. Note: the only thing used in the call to find_all() here is
  332. the result status. The actual data is immediately dropped. As
  333. a future optimization, we may want to add a find_all() option
  334. to only return what the result code would be (and not read/copy
  335. any actual data).
  336. '''
  337. result, rrsets, flags = self.__finder.find_all(rrset.get_name(),
  338. ZoneFinder.NO_WILDCARD |
  339. ZoneFinder.FIND_GLUE_OK)
  340. if result == ZoneFinder.SUCCESS and\
  341. (flags & ZoneFinder.RESULT_WILDCARD == 0):
  342. return True
  343. return False
  344. def __prereq_name_not_in_use(self, rrset):
  345. '''Check whether the name of the given RRset is not in use (i.e. does
  346. not exist at all, or is an empty nonterminal.
  347. RFC2136 Section 2.4.5.
  348. Returns True if the prerequisite is satisfied, False otherwise.
  349. '''
  350. return not self.__prereq_name_in_use(rrset)
  351. def __check_in_zone(self, rrset):
  352. '''Returns true if the name of the given rrset is equal to
  353. or a subdomain of the zname from the Zone Section.'''
  354. relation = rrset.get_name().compare(self.__zname).get_relation()
  355. return relation == NameComparisonResult.SUBDOMAIN or\
  356. relation == NameComparisonResult.EQUAL
  357. def __check_prerequisites(self):
  358. '''Check the prerequisites section of the UPDATE Message.
  359. RFC2136 Section 2.4.
  360. Returns a dns Rcode signaling either no error (Rcode.NOERROR())
  361. or that one of the prerequisites failed (any other Rcode).
  362. '''
  363. for rrset in self.__message.get_section(SECTION_PREREQUISITE):
  364. # First check if the name is in the zone
  365. if not self.__check_in_zone(rrset):
  366. logger.info(LIBDDNS_PREREQ_NOTZONE,
  367. ClientFormatter(self.__client_addr),
  368. ZoneFormatter(self.__zname, self.__zclass),
  369. RRsetFormatter(rrset))
  370. return Rcode.NOTZONE()
  371. # Algorithm taken from RFC2136 Section 3.2
  372. if rrset.get_class() == RRClass.ANY():
  373. if rrset.get_ttl().get_value() != 0 or\
  374. rrset.get_rdata_count() != 0:
  375. logger.info(LIBDDNS_PREREQ_FORMERR_ANY,
  376. ClientFormatter(self.__client_addr),
  377. ZoneFormatter(self.__zname, self.__zclass),
  378. RRsetFormatter(rrset))
  379. return Rcode.FORMERR()
  380. elif rrset.get_type() == RRType.ANY():
  381. if not self.__prereq_name_in_use(rrset):
  382. rcode = Rcode.NXDOMAIN()
  383. logger.info(LIBDDNS_PREREQ_NAME_IN_USE_FAILED,
  384. ClientFormatter(self.__client_addr),
  385. ZoneFormatter(self.__zname, self.__zclass),
  386. RRsetFormatter(rrset), rcode)
  387. return rcode
  388. else:
  389. if not self.__prereq_rrset_exists(rrset):
  390. rcode = Rcode.NXRRSET()
  391. logger.info(LIBDDNS_PREREQ_RRSET_EXISTS_FAILED,
  392. ClientFormatter(self.__client_addr),
  393. ZoneFormatter(self.__zname, self.__zclass),
  394. RRsetFormatter(rrset), rcode)
  395. return rcode
  396. elif rrset.get_class() == RRClass.NONE():
  397. if rrset.get_ttl().get_value() != 0 or\
  398. rrset.get_rdata_count() != 0:
  399. logger.info(LIBDDNS_PREREQ_FORMERR_NONE,
  400. ClientFormatter(self.__client_addr),
  401. ZoneFormatter(self.__zname, self.__zclass),
  402. RRsetFormatter(rrset))
  403. return Rcode.FORMERR()
  404. elif rrset.get_type() == RRType.ANY():
  405. if not self.__prereq_name_not_in_use(rrset):
  406. rcode = Rcode.YXDOMAIN()
  407. logger.info(LIBDDNS_PREREQ_NAME_NOT_IN_USE_FAILED,
  408. ClientFormatter(self.__client_addr),
  409. ZoneFormatter(self.__zname, self.__zclass),
  410. RRsetFormatter(rrset), rcode)
  411. return rcode
  412. else:
  413. if not self.__prereq_rrset_does_not_exist(rrset):
  414. rcode = Rcode.YXRRSET()
  415. logger.info(LIBDDNS_PREREQ_RRSET_DOES_NOT_EXIST_FAILED,
  416. ClientFormatter(self.__client_addr),
  417. ZoneFormatter(self.__zname, self.__zclass),
  418. RRsetFormatter(rrset), rcode)
  419. return rcode
  420. elif rrset.get_class() == self.__zclass:
  421. if rrset.get_ttl().get_value() != 0:
  422. logger.info(LIBDDNS_PREREQ_FORMERR,
  423. ClientFormatter(self.__client_addr),
  424. ZoneFormatter(self.__zname, self.__zclass),
  425. RRsetFormatter(rrset))
  426. return Rcode.FORMERR()
  427. else:
  428. if not self.__prereq_rrset_exists_value(rrset):
  429. rcode = Rcode.NXRRSET()
  430. logger.info(LIBDDNS_PREREQ_RRSET_EXISTS_VAL_FAILED,
  431. ClientFormatter(self.__client_addr),
  432. ZoneFormatter(self.__zname, self.__zclass),
  433. RRsetFormatter(rrset), rcode)
  434. return rcode
  435. else:
  436. logger.info(LIBDDNS_PREREQ_FORMERR_CLASS,
  437. ClientFormatter(self.__client_addr),
  438. ZoneFormatter(self.__zname, self.__zclass),
  439. RRsetFormatter(rrset))
  440. return Rcode.FORMERR()
  441. # All prerequisites are satisfied
  442. return Rcode.NOERROR()
  443. def __set_soa_rrset(self, rrset):
  444. '''Sets the given rrset to the member __added_soa (which
  445. is used by __do_update for updating the SOA record'''
  446. self.__added_soa = rrset
  447. def __do_prescan(self):
  448. '''Perform the prescan as defined in RFC2136 section 3.4.1.
  449. This method has a side-effect; it sets self._new_soa if
  450. it encounters the addition of a SOA record in the update
  451. list (so serial can be checked by update later, etc.).
  452. It puts the added SOA in self.__added_soa.
  453. '''
  454. for rrset in self.__message.get_section(SECTION_UPDATE):
  455. if not self.__check_in_zone(rrset):
  456. logger.info(LIBDDNS_UPDATE_NOTZONE,
  457. ClientFormatter(self.__client_addr),
  458. ZoneFormatter(self.__zname, self.__zclass),
  459. RRsetFormatter(rrset))
  460. return Rcode.NOTZONE()
  461. if rrset.get_class() == self.__zclass:
  462. # In fact, all metatypes are in a specific range,
  463. # so one check can test TKEY to ANY
  464. # (some value check is needed anyway, since we do
  465. # not have defined RRtypes for MAILA and MAILB)
  466. if rrset.get_type().get_code() >= 249:
  467. logger.info(LIBDDNS_UPDATE_ADD_BAD_TYPE,
  468. ClientFormatter(self.__client_addr),
  469. ZoneFormatter(self.__zname, self.__zclass),
  470. RRsetFormatter(rrset))
  471. return Rcode.FORMERR()
  472. if rrset.get_type() == RRType.SOA():
  473. # In case there's multiple soa records in the update
  474. # somehow, just take the last
  475. foreach_rr_in_rrset(rrset, self.__set_soa_rrset, rrset)
  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, diff, 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. diff.add_data(rr)
  523. else:
  524. rr_rdata = rr.get_rdata()[0]
  525. if not rr_rdata in existing_rrset.get_rdata():
  526. diff.add_data(rr)
  527. def __do_update_add_rrs_to_rrset(self, diff, rrset):
  528. '''Add the rrs from the given rrset to the 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 not 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 == self.__finder.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. 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. foreach_rr_in_rrset(rrset, self.__do_update_add_single_rr, diff, rrset, orig_rrset)
  570. def __do_update_delete_rrset(self, diff, rrset):
  571. '''Deletes the rrset with the name and type of the given
  572. rrset from the zone data (by putting all existing data
  573. in the given diff as delete statements).
  574. Special cases: if the delete statement is for the
  575. zone's apex, and the type is either SOA or NS, it
  576. is ignored.'''
  577. result, to_delete, _ = self.__finder.find(rrset.get_name(),
  578. rrset.get_type(),
  579. ZoneFinder.NO_WILDCARD |
  580. ZoneFinder.FIND_GLUE_OK)
  581. if to_delete.get_name() == self.__zname and\
  582. (to_delete.get_type() == RRType.SOA() or\
  583. to_delete.get_type() == RRType.NS()):
  584. # ignore
  585. return
  586. foreach_rr_in_rrset(to_delete, diff.delete_data, to_delete)
  587. def __ns_deleter_helper(self, diff, rrset):
  588. '''Special case helper for deleting NS resource records
  589. at the zone apex. In that scenario, the last NS record
  590. may never be removed (and any action that would do so
  591. should be ignored).
  592. '''
  593. result, orig_rrset, _ = self.__finder.find(rrset.get_name(),
  594. rrset.get_type(),
  595. ZoneFinder.NO_WILDCARD |
  596. ZoneFinder.FIND_GLUE_OK)
  597. # Even a real rrset comparison wouldn't help here...
  598. # The goal is to make sure that after deletion of the
  599. # given rrset, at least 1 NS record is left (at the apex).
  600. # So we make a (shallow) copy of the existing rrset,
  601. # and for each rdata in the to_delete set, we check if it wouldn't
  602. # delete the last one. If it would, that specific one is ignored.
  603. # If it would not, the rdata is removed from the temporary list
  604. orig_rrset_rdata = copy.copy(orig_rrset.get_rdata())
  605. for rdata in rrset.get_rdata():
  606. if len(orig_rrset_rdata) == 1 and rdata == orig_rrset_rdata[0]:
  607. # ignore
  608. continue
  609. else:
  610. # create an individual RRset for deletion
  611. to_delete = isc.dns.RRset(rrset.get_name(),
  612. rrset.get_class(),
  613. rrset.get_type(),
  614. rrset.get_ttl())
  615. to_delete.add_rdata(rdata)
  616. orig_rrset_rdata.remove(rdata)
  617. diff.delete_data(to_delete)
  618. def __do_update_delete_name(self, diff, rrset):
  619. '''Delete all data at the name of the given rrset,
  620. by adding all data found by find_all as delete statements
  621. to the given diff.
  622. Special case: if the name is the zone's apex, SOA and
  623. NS records are kept.
  624. '''
  625. result, rrsets, flags = self.__finder.find_all(rrset.get_name(),
  626. ZoneFinder.NO_WILDCARD |
  627. ZoneFinder.FIND_GLUE_OK)
  628. if result == ZoneFinder.SUCCESS and\
  629. (flags & ZoneFinder.RESULT_WILDCARD == 0):
  630. for to_delete in rrsets:
  631. # if name == self.__zname and type is soa or ns, don't delete!
  632. if to_delete.get_name() == self.__zname and\
  633. (to_delete.get_type() == RRType.SOA() or
  634. to_delete.get_type() == RRType.NS()):
  635. continue
  636. else:
  637. foreach_rr_in_rrset(to_delete, diff.delete_data, to_delete)
  638. def __do_update_delete_rrs_from_rrset(self, diff, rrset):
  639. '''Deletes all resource records in the given rrset from the
  640. zone. Resource records that do not exist are ignored.
  641. If the rrset if of type SOA, it is ignored.
  642. Uses the __ns_deleter_helper if the rrset's name is the
  643. zone's apex, and the type is NS.
  644. '''
  645. # Delete all rrs in the rrset, except if name=self.__zname and type=soa, or
  646. # type = ns and there is only one left (...)
  647. # The delete does not want class NONE, we would not have gotten here
  648. # if it wasn't, but now is a good time to change it to the zclass.
  649. to_delete = convert_rrset_class(rrset, self.__zclass)
  650. if rrset.get_name() == self.__zname:
  651. if rrset.get_type() == RRType.SOA():
  652. # ignore
  653. return
  654. elif rrset.get_type() == RRType.NS():
  655. # hmm. okay. annoying. There must be at least one left,
  656. # delegate to helper method
  657. self.__ns_deleter_helper(diff, to_delete)
  658. return
  659. foreach_rr_in_rrset(to_delete, diff.delete_data, to_delete)
  660. def __update_soa(self, diff):
  661. '''Checks the member value __added_soa, and depending on
  662. whether it has been set and what its value is, creates
  663. a new SOA if necessary.
  664. Then removes the original SOA and adds the new one,
  665. by adding the needed operations to the given diff.'''
  666. # Get the existing SOA
  667. # if a new soa was specified, add that one, otherwise, do the
  668. # serial magic and add the newly created one
  669. # get it from DS and to increment and stuff
  670. result, old_soa, _ = self.__finder.find(self.__zname, RRType.SOA(),
  671. ZoneFinder.NO_WILDCARD |
  672. ZoneFinder.FIND_GLUE_OK)
  673. # We may implement recovering from missing SOA data at some point, but
  674. # for now servfail on such a broken state
  675. if result != ZoneFinder.SUCCESS:
  676. raise UpdateError("Error finding SOA record in datasource.",
  677. self.__zname, self.__zclass, Rcode.SERVFAIL())
  678. serial_operation = DDNS_SOA()
  679. if self.__added_soa is not None and\
  680. serial_operation.soa_update_check(old_soa, self.__added_soa):
  681. new_soa = self.__added_soa
  682. else:
  683. # increment goes here
  684. new_soa = serial_operation.update_soa(old_soa)
  685. diff.delete_data(old_soa)
  686. diff.add_data(new_soa)
  687. def __do_update(self):
  688. '''Scan, check, and execute the Update section in the
  689. DDNS Update message.
  690. Returns an Rcode to signal the result (NOERROR upon success,
  691. any error result otherwise).
  692. '''
  693. # prescan
  694. prescan_result = self.__do_prescan()
  695. if prescan_result != Rcode.NOERROR():
  696. return prescan_result
  697. # update
  698. try:
  699. # create an ixfr-out-friendly diff structure to work on
  700. diff = isc.xfrin.diff.Diff(self.__datasrc_client, self.__zname,
  701. journaling=True, single_update_mode=True)
  702. # Do special handling for SOA first
  703. self.__update_soa(diff)
  704. # Algorithm from RFC2136 Section 3.4
  705. # Note that this works on full rrsets, not individual RRs.
  706. # Some checks might be easier with individual RRs, but only if we
  707. # would use the ZoneUpdater directly (so we can query the
  708. # 'zone-as-it-would-be-so-far'. However, due to the current use
  709. # of the Diff class, this is not the case, and therefore it
  710. # is easier to work with full rrsets for the most parts
  711. # (less lookups needed; conversion to individual rrs is
  712. # the same offort whether it is done here or in the several
  713. # do_update statements)
  714. for rrset in self.__message.get_section(SECTION_UPDATE):
  715. if rrset.get_class() == self.__zclass:
  716. self.__do_update_add_rrs_to_rrset(diff, rrset)
  717. elif rrset.get_class() == RRClass.ANY():
  718. if rrset.get_type() == RRType.ANY():
  719. self.__do_update_delete_name(diff, rrset)
  720. else:
  721. self.__do_update_delete_rrset(diff, rrset)
  722. elif rrset.get_class() == RRClass.NONE():
  723. self.__do_update_delete_rrs_from_rrset(diff, rrset)
  724. diff.commit()
  725. return Rcode.NOERROR()
  726. except isc.datasrc.Error as dse:
  727. logger.info(LIBDDNS_UPDATE_DATASRC_ERROR, dse)
  728. return Rcode.SERVFAIL()
  729. except Exception as uce:
  730. logger.error(LIBDDNS_UPDATE_UNCAUGHT_EXCEPTION,
  731. ClientFormatter(self.__client_addr),
  732. ZoneFormatter(self.__zname, self.__zclass),
  733. uce)
  734. return Rcode.SERVFAIL()