authority.py 16 KB

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