authority.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. # -*- test-case-name: twisted.names.test.test_names -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Authoritative resolvers.
  6. """
  7. from __future__ import absolute_import, division
  8. import os
  9. import time
  10. from twisted.names import dns, error, common
  11. from twisted.internet import defer
  12. from twisted.python import failure
  13. from twisted.python.compat import execfile, nativeString, _PY3
  14. from twisted.python.filepath import FilePath
  15. def getSerial(filename='/tmp/twisted-names.serial'):
  16. """
  17. Return a monotonically increasing (across program runs) integer.
  18. State is stored in the given file. If it does not exist, it is
  19. created with rw-/---/--- permissions.
  20. This manipulates process-global state by calling C{os.umask()}, so it isn't
  21. thread-safe.
  22. @param filename: Path to a file that is used to store the state across
  23. program runs.
  24. @type filename: L{str}
  25. @return: a monotonically increasing number
  26. @rtype: L{str}
  27. """
  28. serial = time.strftime('%Y%m%d')
  29. o = os.umask(0o177)
  30. try:
  31. if not os.path.exists(filename):
  32. with open(filename, 'w') as f:
  33. f.write(serial + ' 0')
  34. finally:
  35. os.umask(o)
  36. with open(filename, 'r') as serialFile:
  37. lastSerial, zoneID = serialFile.readline().split()
  38. zoneID = (lastSerial == serial) and (int(zoneID) + 1) or 0
  39. with open(filename, 'w') as serialFile:
  40. serialFile.write('%s %d' % (serial, zoneID))
  41. serial = serial + ('%02d' % (zoneID,))
  42. return serial
  43. class FileAuthority(common.ResolverBase):
  44. """
  45. An Authority that is loaded from a file.
  46. This is an abstract class that implements record search logic. To create
  47. a functional resolver, subclass it and override the L{loadFile} method.
  48. @ivar _ADDITIONAL_PROCESSING_TYPES: Record types for which additional
  49. processing will be done.
  50. @ivar _ADDRESS_TYPES: Record types which are useful for inclusion in the
  51. additional section generated during additional processing.
  52. @ivar soa: A 2-tuple containing the SOA domain name as a L{bytes} and a
  53. L{dns.Record_SOA}.
  54. @ivar records: A mapping of domains (as lowercased L{bytes}) to records.
  55. @type records: L{dict} with L{byte} keys
  56. """
  57. # See https://twistedmatrix.com/trac/ticket/6650
  58. _ADDITIONAL_PROCESSING_TYPES = (dns.CNAME, dns.MX, dns.NS)
  59. _ADDRESS_TYPES = (dns.A, dns.AAAA)
  60. soa = None
  61. records = None
  62. def __init__(self, filename):
  63. common.ResolverBase.__init__(self)
  64. self.loadFile(filename)
  65. self._cache = {}
  66. def __setstate__(self, state):
  67. self.__dict__ = state
  68. def loadFile(self, filename):
  69. """
  70. Load DNS records from a file.
  71. This method populates the I{soa} and I{records} attributes. It must be
  72. overridden in a subclass. It is called once from the initializer.
  73. @param filename: The I{filename} parameter that was passed to the
  74. initilizer.
  75. @returns: L{None} -- the return value is ignored
  76. """
  77. def _additionalRecords(self, answer, authority, ttl):
  78. """
  79. Find locally known information that could be useful to the consumer of
  80. the response and construct appropriate records to include in the
  81. I{additional} section of that response.
  82. Essentially, implement RFC 1034 section 4.3.2 step 6.
  83. @param answer: A L{list} of the records which will be included in the
  84. I{answer} section of the response.
  85. @param authority: A L{list} of the records which will be included in
  86. the I{authority} section of the response.
  87. @param ttl: The default TTL for records for which this is not otherwise
  88. specified.
  89. @return: A generator of L{dns.RRHeader} instances for inclusion in the
  90. I{additional} section. These instances represent extra information
  91. about the records in C{answer} and C{authority}.
  92. """
  93. for record in answer + authority:
  94. if record.type in self._ADDITIONAL_PROCESSING_TYPES:
  95. name = record.payload.name.name
  96. for rec in self.records.get(name.lower(), ()):
  97. if rec.TYPE in self._ADDRESS_TYPES:
  98. yield dns.RRHeader(
  99. name, rec.TYPE, dns.IN,
  100. rec.ttl or ttl, rec, auth=True)
  101. def _lookup(self, name, cls, type, timeout=None):
  102. """
  103. Determine a response to a particular DNS query.
  104. @param name: The name which is being queried and for which to lookup a
  105. response.
  106. @type name: L{bytes}
  107. @param cls: The class which is being queried. Only I{IN} is
  108. implemented here and this value is presently disregarded.
  109. @type cls: L{int}
  110. @param type: The type of records being queried. See the types defined
  111. in L{twisted.names.dns}.
  112. @type type: L{int}
  113. @param timeout: All processing is done locally and a result is
  114. available immediately, so the timeout value is ignored.
  115. @return: A L{Deferred} that fires with a L{tuple} of three sets of
  116. response records (to comprise the I{answer}, I{authority}, and
  117. I{additional} sections of a DNS response) or with a L{Failure} if
  118. there is a problem processing the query.
  119. """
  120. cnames = []
  121. results = []
  122. authority = []
  123. additional = []
  124. default_ttl = max(self.soa[1].minimum, self.soa[1].expire)
  125. domain_records = self.records.get(name.lower())
  126. if domain_records:
  127. for record in domain_records:
  128. if record.ttl is not None:
  129. ttl = record.ttl
  130. else:
  131. ttl = default_ttl
  132. if (record.TYPE == dns.NS and
  133. name.lower() != self.soa[0].lower()):
  134. # NS record belong to a child zone: this is a referral. As
  135. # NS records are authoritative in the child zone, ours here
  136. # are not. RFC 2181, section 6.1.
  137. authority.append(
  138. dns.RRHeader(
  139. name, record.TYPE, dns.IN, ttl, record, auth=False
  140. )
  141. )
  142. elif record.TYPE == type or type == dns.ALL_RECORDS:
  143. results.append(
  144. dns.RRHeader(
  145. name, record.TYPE, dns.IN, ttl, record, auth=True
  146. )
  147. )
  148. if record.TYPE == dns.CNAME:
  149. cnames.append(
  150. dns.RRHeader(
  151. name, record.TYPE, dns.IN, ttl, record, auth=True
  152. )
  153. )
  154. if not results:
  155. results = cnames
  156. # Sort of https://tools.ietf.org/html/rfc1034#section-4.3.2 .
  157. # See https://twistedmatrix.com/trac/ticket/6732
  158. additionalInformation = self._additionalRecords(
  159. results, authority, default_ttl)
  160. if cnames:
  161. results.extend(additionalInformation)
  162. else:
  163. additional.extend(additionalInformation)
  164. if not results and not authority:
  165. # Empty response. Include SOA record to allow clients to cache
  166. # this response. RFC 1034, sections 3.7 and 4.3.4, and RFC 2181
  167. # section 7.1.
  168. authority.append(
  169. dns.RRHeader(
  170. self.soa[0], dns.SOA, dns.IN, ttl, self.soa[1],
  171. auth=True
  172. )
  173. )
  174. return defer.succeed((results, authority, additional))
  175. else:
  176. if dns._isSubdomainOf(name, self.soa[0]):
  177. # We may be the authority and we didn't find it.
  178. # XXX: The QNAME may also be in a delegated child zone. See
  179. # #6581 and #6580
  180. return defer.fail(
  181. failure.Failure(dns.AuthoritativeDomainError(name))
  182. )
  183. else:
  184. # The QNAME is not a descendant of this zone. Fail with
  185. # DomainError so that the next chained authority or
  186. # resolver will be queried.
  187. return defer.fail(failure.Failure(error.DomainError(name)))
  188. def lookupZone(self, name, timeout=10):
  189. name = dns.domainString(name)
  190. if self.soa[0].lower() == name.lower():
  191. # Wee hee hee hooo yea
  192. default_ttl = max(self.soa[1].minimum, self.soa[1].expire)
  193. if self.soa[1].ttl is not None:
  194. soa_ttl = self.soa[1].ttl
  195. else:
  196. soa_ttl = default_ttl
  197. results = [
  198. dns.RRHeader(
  199. self.soa[0], dns.SOA, dns.IN, soa_ttl, self.soa[1],
  200. auth=True
  201. )
  202. ]
  203. for (k, r) in self.records.items():
  204. for rec in r:
  205. if rec.ttl is not None:
  206. ttl = rec.ttl
  207. else:
  208. ttl = default_ttl
  209. if rec.TYPE != dns.SOA:
  210. results.append(
  211. dns.RRHeader(
  212. k, rec.TYPE, dns.IN, ttl, rec, auth=True
  213. )
  214. )
  215. results.append(results[0])
  216. return defer.succeed((results, (), ()))
  217. return defer.fail(failure.Failure(dns.DomainError(name)))
  218. def _cbAllRecords(self, results):
  219. ans, auth, add = [], [], []
  220. for res in results:
  221. if res[0]:
  222. ans.extend(res[1][0])
  223. auth.extend(res[1][1])
  224. add.extend(res[1][2])
  225. return ans, auth, add
  226. class PySourceAuthority(FileAuthority):
  227. """
  228. A FileAuthority that is built up from Python source code.
  229. """
  230. def loadFile(self, filename):
  231. g, l = self.setupConfigNamespace(), {}
  232. execfile(filename, g, l)
  233. if 'zone' not in l:
  234. raise ValueError("No zone defined in " + filename)
  235. self.records = {}
  236. for rr in l['zone']:
  237. if isinstance(rr[1], dns.Record_SOA):
  238. self.soa = rr
  239. self.records.setdefault(rr[0].lower(), []).append(rr[1])
  240. def wrapRecord(self, type):
  241. return lambda name, *arg, **kw: (name, type(*arg, **kw))
  242. def setupConfigNamespace(self):
  243. r = {}
  244. items = dns.__dict__.iterkeys()
  245. for record in [x for x in items if x.startswith('Record_')]:
  246. type = getattr(dns, record)
  247. f = self.wrapRecord(type)
  248. r[record[len('Record_'):]] = f
  249. return r
  250. class BindAuthority(FileAuthority):
  251. """
  252. An Authority that loads U{BIND zone files
  253. <https://en.wikipedia.org/wiki/Zone_file>}.
  254. Supports only C{$ORIGIN} and C{$TTL} directives.
  255. """
  256. def loadFile(self, filename):
  257. """
  258. Load records from C{filename}.
  259. @param filename: file to read from
  260. @type filename: L{bytes}
  261. """
  262. fp = FilePath(filename)
  263. # Not the best way to set an origin. It can be set using $ORIGIN
  264. # though.
  265. self.origin = nativeString(fp.basename() + b'.')
  266. lines = fp.getContent().splitlines(True)
  267. lines = self.stripComments(lines)
  268. lines = self.collapseContinuations(lines)
  269. self.parseLines(lines)
  270. def stripComments(self, lines):
  271. """
  272. Strip comments from C{lines}.
  273. @param lines: lines to work on
  274. @type lines: iterable of L{bytes}
  275. @return: C{lines} sans comments.
  276. """
  277. return (
  278. a.find(b';') == -1 and a or a[:a.find(b';')] for a in [
  279. b.strip() for b in lines
  280. ]
  281. )
  282. def collapseContinuations(self, lines):
  283. """
  284. Transform multiline statements into single lines.
  285. @param lines: lines to work on
  286. @type lines: iterable of L{bytes}
  287. @return: iterable of continuous lines
  288. """
  289. l = []
  290. state = 0
  291. for line in lines:
  292. if state == 0:
  293. if line.find(b'(') == -1:
  294. l.append(line)
  295. else:
  296. l.append(line[:line.find(b'(')])
  297. state = 1
  298. else:
  299. if line.find(b')') != -1:
  300. l[-1] += b' ' + line[:line.find(b')')]
  301. state = 0
  302. else:
  303. l[-1] += b' ' + line
  304. return filter(None, (line.split() for line in l))
  305. def parseLines(self, lines):
  306. """
  307. Parse C{lines}.
  308. @param lines: lines to work on
  309. @type lines: iterable of L{bytes}
  310. """
  311. ttl = 60 * 60 * 3
  312. origin = self.origin
  313. self.records = {}
  314. for line in lines:
  315. if line[0] == b'$TTL':
  316. ttl = dns.str2time(line[1])
  317. elif line[0] == b'$ORIGIN':
  318. origin = line[1]
  319. elif line[0] == b'$INCLUDE':
  320. raise NotImplementedError('$INCLUDE directive not implemented')
  321. elif line[0] == b'$GENERATE':
  322. raise NotImplementedError(
  323. '$GENERATE directive not implemented'
  324. )
  325. else:
  326. self.parseRecordLine(origin, ttl, line)
  327. # If the origin changed, reflect that within the instance.
  328. self.origin = origin
  329. def addRecord(self, owner, ttl, type, domain, cls, rdata):
  330. """
  331. Add a record to our authority. Expand domain with origin if necessary.
  332. @param owner: origin?
  333. @type owner: L{bytes}
  334. @param ttl: time to live for the record
  335. @type ttl: L{int}
  336. @param domain: the domain for which the record is to be added
  337. @type domain: L{bytes}
  338. @param type: record type
  339. @type type: L{str}
  340. @param cls: record class
  341. @type cls: L{str}
  342. @param rdata: record data
  343. @type rdata: L{list} of L{bytes}
  344. """
  345. if not domain.endswith(b'.'):
  346. domain = domain + b'.' + owner[:-1]
  347. else:
  348. domain = domain[:-1]
  349. f = getattr(self, 'class_%s' % (cls,), None)
  350. if f:
  351. f(ttl, type, domain, rdata)
  352. else:
  353. raise NotImplementedError(
  354. "Record class %r not supported" % (cls,)
  355. )
  356. def class_IN(self, ttl, type, domain, rdata):
  357. """
  358. Simulate a class IN and recurse into the actual class.
  359. @param ttl: time to live for the record
  360. @type ttl: L{int}
  361. @param type: record type
  362. @type type: str
  363. @param domain: the domain
  364. @type domain: bytes
  365. @param rdata:
  366. @type rdate: bytes
  367. """
  368. record = getattr(dns, 'Record_%s' % (nativeString(type),), None)
  369. if record:
  370. r = record(*rdata)
  371. r.ttl = ttl
  372. self.records.setdefault(domain.lower(), []).append(r)
  373. if type == 'SOA':
  374. self.soa = (domain, r)
  375. else:
  376. raise NotImplementedError(
  377. "Record type %r not supported" % (nativeString(type),)
  378. )
  379. def parseRecordLine(self, origin, ttl, line):
  380. """
  381. Parse a C{line} from a zone file respecting C{origin} and C{ttl}.
  382. Add resulting records to authority.
  383. @param origin: starting point for the zone
  384. @type origin: L{bytes}
  385. @param ttl: time to live for the record
  386. @type ttl: L{int}
  387. @param line: zone file line to parse; split by word
  388. @type line: L{list} of L{bytes}
  389. """
  390. if _PY3:
  391. queryClasses = set(
  392. qc.encode("ascii") for qc in dns.QUERY_CLASSES.values()
  393. )
  394. queryTypes = set(
  395. qt.encode("ascii") for qt in dns.QUERY_TYPES.values()
  396. )
  397. else:
  398. queryClasses = set(dns.QUERY_CLASSES.values())
  399. queryTypes = set(dns.QUERY_TYPES.values())
  400. markers = queryClasses | queryTypes
  401. cls = b'IN'
  402. owner = origin
  403. if line[0] == b'@':
  404. line = line[1:]
  405. owner = origin
  406. elif not line[0].isdigit() and line[0] not in markers:
  407. owner = line[0]
  408. line = line[1:]
  409. if line[0].isdigit() or line[0] in markers:
  410. domain = owner
  411. owner = origin
  412. else:
  413. domain = line[0]
  414. line = line[1:]
  415. if line[0] in queryClasses:
  416. cls = line[0]
  417. line = line[1:]
  418. if line[0].isdigit():
  419. ttl = int(line[0])
  420. line = line[1:]
  421. elif line[0].isdigit():
  422. ttl = int(line[0])
  423. line = line[1:]
  424. if line[0] in queryClasses:
  425. cls = line[0]
  426. line = line[1:]
  427. type = line[0]
  428. rdata = line[1:]
  429. self.addRecord(
  430. owner, ttl, nativeString(type), domain, nativeString(cls), rdata
  431. )