gen_wiredata.py.in 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  1. #!@PYTHON@
  2. # Copyright (C) 2010 Internet Systems Consortium.
  3. #
  4. # Permission to use, copy, modify, and distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  9. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  10. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  11. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  12. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  13. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  14. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  15. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """
  17. Generator of various types of DNS data in the hex format.
  18. This script reads a human readable specification file (called "spec
  19. file" hereafter) that defines some type of DNS data (an RDATA, an RR,
  20. or a complete message) and dumps the defined data to a separate file
  21. as a "wire format" sequence parsable by the
  22. UnitTestUtil::readWireData() function (currently defined as part of
  23. libdns++ tests). Many DNS related tests involve wire format test
  24. data, so it will be convenient if we can define the data in a more
  25. intuitive way than writing the entire hex sequence by hand.
  26. Here is a simple example. Consider the following spec file:
  27. [custom]
  28. sections: a
  29. [a]
  30. as_rr: True
  31. When the script reads this file, it detects the file specifies a single
  32. component (called "section" here) that consists of a single A RDATA,
  33. which must be dumped as an RR (not only the part of RDATA). It then
  34. dumps the following content:
  35. # A RR (QNAME=example.com Class=IN(1) TTL=86400 RDLEN=4)
  36. 076578616d706c6503636f6d00 0001 0001 00015180 0004
  37. # Address=192.0.2.1
  38. c0000201
  39. As can be seen, the script automatically completes all variable
  40. parameters of RRs: owner name, class, TTL, RDATA length and data. For
  41. testing purposes many of these will be the same common one (like
  42. "example.com" or 192.0.2.1), so it would be convenient if we only have
  43. to specify non default parameters. To change the RDATA (i.e., the
  44. IPv4 address), we should add the following line at the end of the spec
  45. file:
  46. address: 192.0.2.2
  47. Then the last two lines of the output file will be as follows:
  48. # Address=192.0.2.2
  49. c0000202
  50. In some cases we would rather specify malformed data for tests. This
  51. script has the ability to specify broken parameters for many types of
  52. data. For example, we can generate data that would look like an A RR
  53. but the RDLEN is 3 by adding the following line to the spec file:
  54. rdlen: 3
  55. Then the first two lines of the output file will be as follows:
  56. # A RR (QNAME=example.com Class=IN(1) TTL=86400 RDLEN=3)
  57. 076578616d706c6503636f6d00 0001 0001 00015180 0003
  58. ** USAGE **
  59. gen_wiredata.py [-o output_file] spec_file
  60. If the -o option is missing, and if the spec_file has a suffix (such as
  61. in the form of "data.spec"), the output file name will be the prefix
  62. part of it (as in "data"); if -o is missing and the spec_file does not
  63. have a suffix, the script will fail.
  64. ** SPEC FILE SYNTAX **
  65. A spec file accepted in this script should be in the form of a
  66. configuration file that is parsable by the Python's standard
  67. configparser module. In short, it consists of sections; each section
  68. is identified in the form of [section_name] followed by "name: value"
  69. entries. Lines beginning with # or ; will be treated as comments.
  70. Refer to the configparser module documentation for further details of
  71. the general syntax.
  72. This script has two major modes: the custom mode and the DNS query
  73. mode. The former generates an arbitrary combination of DNS message
  74. header, question section, RDATAs or RRs. It is mainly intended to
  75. generate a test data for a single type of RDATA or RR, or for
  76. complicated complete DNS messages. The DNS query mode is actually a
  77. special case of the custom mode, which is a shortcut to generate a
  78. simple DNS query message (with or without EDNS).
  79. * Custom mode syntax *
  80. By default this script assumes the DNS query mode. To specify the
  81. custom mode, there must be a special "custom" section in the spec
  82. file, which should contain 'sections' entry. This value of this
  83. entryis colon-separated string fields, each of which is either
  84. "header", "question", "edns", "name", or a string specifying an RR
  85. type. For RR types the string is lower-cased string mnemonic that
  86. identifies the type: 'a' for type A, 'ns' for type NS, and so on
  87. (note: in the current implementation it's case sensitive, and must be
  88. lower cased).
  89. Each of these fields is interpreted as a section name of the spec
  90. (configuration), and in that section parameters specific to the
  91. semantics of the field can be configured.
  92. A "header" section specifies the content of a DNS message header.
  93. See the documentation of the DNSHeader class of this module for
  94. configurable parameters.
  95. A "question" section specifies the content of a single question that
  96. is normally to be placed in the Question section of a DNS message.
  97. See the documentation of the DNSQuestion class of this module for
  98. configurable parameters.
  99. An "edns" section specifies the content of an EDNS OPT RR. See the
  100. documentation of the EDNS class of this module for configurable
  101. parameters.
  102. A "name" section specifies a domain name with or without compression.
  103. This is specifically intended to be used for testing name related
  104. functionalities and would rarely be used with other sections. See the
  105. documentation of the Name class of this module for configurable
  106. parameters.
  107. In a specific section for an RR or RDATA, possible entries depend on
  108. the type. But there are some common configurable entries. See the
  109. description of the RR class. The most important one would be "as_rr".
  110. It controls whether the entry should be treated as an RR (with name,
  111. type, class and TTL) or only as an RDATA. By default as_rr is
  112. "False", so if an entry is to be interpreted as an RR, an as_rr entry
  113. must be explicitly specified with a value of "True".
  114. Another common entry is "rdlen". It specifies the RDLEN field value
  115. of the RR (note: this is included when the entry is interpreted as
  116. RDATA, too). By default this value is automatically determined by the
  117. RR type and (it has a variable length) from other fields of RDATA, but
  118. as shown in the above example, it can be explicitly set, possibly to a
  119. bogus value for testing against invalid data.
  120. For type specific entries (and their defaults when provided), see the
  121. documentation of the corresponding Python class defined in this
  122. module. In general, there should be a class named the same mnemonic
  123. of the corresponding RR type for each supported type, and they are a
  124. subclass of the RR class. For example, the "NS" class is defined for
  125. RR type NS.
  126. Look again at the A RR example shown at the beginning of this
  127. description. There's a "custom" section, which consists of a
  128. "sections" entry whose value is a single "a", which means the data to
  129. be generated is an A RR or RDATA. There's a corresponding "a"
  130. section, which only specifies that it should be interpreted as an RR
  131. (all field values of the RR are derived from the default).
  132. If you want to generate a data sequence for two ore more RRs or
  133. RDATAs, you can specify them in the form of colon-separated fields for
  134. the "sections" entry. For example, to generate a sequence of A and NS
  135. RRs in that order, the "custom" section would be something like this:
  136. [custom]
  137. sections: a:ns
  138. and there must be an "ns" section in addtion to "a".
  139. If a sequence of two or more RRs/RDATAs of the same RR type should be
  140. generated, these should be uniquely indexed with the "/" separator.
  141. For example, to generate two A RRs, the "custom" section would be as
  142. follows:
  143. [custom]
  144. sections: a/1:a/2
  145. and there must be "a/1" and "a/2" sections.
  146. Another practical example that would be used for many tests is to
  147. generate data for a complete DNS ressponse message. The spec file of
  148. such an example configuration would look like as follows:
  149. [custom]
  150. sections: header:question:a
  151. [header]
  152. qr: 1
  153. ancount: 1
  154. [question]
  155. [a]
  156. as_rr: True
  157. With this configuration, this script will generate test data for a DNS
  158. response to a query for example.com/IN/A containing one corresponding
  159. A RR in the answer section.
  160. * DNS query mode syntax *
  161. If the spec file does not contain a "custom" section (that has a
  162. "sections" entry), this script assumes the DNS query mode. This mode
  163. is actually a special case of custom mode; it implicitly assumes the
  164. "sections" entry whose value is "header:question:edns".
  165. In this mode it is expected that the spec file also contains at least
  166. a "header" and "question" sections, and optionally an "edns" section.
  167. But the script does not warn or fail even if the expected sections are
  168. missing.
  169. * Entry value types *
  170. As described above, a section of the spec file accepts entries
  171. specific to the semantics of the section. They generally correspond
  172. to DNS message or RR fields.
  173. Many of them are expected to be integral values, for which either decimal or
  174. hexadecimal representation is accepted, for example:
  175. rr_ttl: 3600
  176. tag: 0x1234
  177. Some others are expected to be string. A string value does not have
  178. to be quated:
  179. address: 192.0.2.2
  180. but can also be quoated with single quotes:
  181. address: '192.0.2.2'
  182. Note 1: a string that can be interpreted as an integer must be quated.
  183. For example, if you want to set a "string" entry to "3600", it should
  184. be:
  185. string: '3600'
  186. instead of
  187. string: 3600
  188. Note 2: a string enclosed with double quotes is not accepted:
  189. # This doesn't work:
  190. address: "192.0.2.2"
  191. In general, string values are converted to hexadecimal sequences
  192. according to the semantics of the entry. For instance, a textual IPv4
  193. address in the above example will be converted to a hexadecimal
  194. sequence corresponding to a 4-byte integer. So, in many cases, the
  195. acceptable syntax for a particular string entry value should be
  196. obvious from the context. There are still some exceptional cases
  197. especially for complicated RR field values, for which the
  198. corresponding class documentation should be referenced.
  199. One special string syntax that would be worth noting is domain names,
  200. which would natually be used in many kinds of entries. The simplest
  201. form of acceptable syntax is a textual representation of domain names
  202. such as "example.com" (note: names are always assumed to be
  203. "absolute", so the trailing dot can be omitted). But a domain name in
  204. the wire format can also contain a compression pointer. This script
  205. provides a simple support for name compression with a special notation
  206. of "ptr=nn" where nn is the numeric pointer value (decimal). For example,
  207. if the NSDNAME field of an NS RDATA is specified as follows:
  208. nsname: ns.ptr=12
  209. this script will generate the following output:
  210. # NS name=ns.ptr=12
  211. 026e73c00c
  212. ** EXTEND THE SCRIPT **
  213. This script is expected to be extended as we add more support for
  214. various types of RR. It is encouraged to add support for a new type
  215. of RR to this script as we see the need for testing that type. Here
  216. is a simple instruction of how to do that.
  217. Assume you are adding support for "FOO" RR. Also assume that the FOO
  218. RDATA contains a single field named "value".
  219. What you are expected to do is as follows:
  220. - Define a new class named "FOO" inherited from the RR class. Also
  221. define a class variable named "value" for the FOO RDATA field (the
  222. variable name can be different from the field name, but it's
  223. convenient if it can be easily identifiable.) with an appropriate
  224. default value (if possible):
  225. class FOO(RR):
  226. value = 10
  227. The name of the variable will be (automatically) used as the
  228. corresponding entry name in the spec file. So, a spec file that
  229. sets this field to 20 would look like this:
  230. [foo]
  231. value: 20
  232. - Define the "dump()" method for class FOO. It must call
  233. self.dump_header() (which is derived from class RR) at the
  234. beginning. It then prints the RDATA field values in an appropriate
  235. way. Assuming the value is a 16-bit integer field, a complete
  236. dump() method would look like this:
  237. def dump(self, f):
  238. if self.rdlen is None:
  239. self.rdlen = 2
  240. self.dump_header(f, self.rdlen)
  241. f.write('# Value=%d\\n' % (self.value))
  242. f.write('%04x\\n' % (self.value))
  243. The first f.write() call is not mandatory, but is encouraged to
  244. be provided so that the generated files will be more human readable.
  245. Depending on the complexity of the RDATA fields, the dump()
  246. implementation would be more complicated. In particular, if the
  247. RDATA length is variable and the RDLEN field value is not specified
  248. in the spec file, the dump() method is normally expected to
  249. calculate the correct length and pass it to dump_header(). See the
  250. implementation of various derived classes of class RR for actual
  251. examples.
  252. """
  253. import configparser, re, time, socket, sys
  254. from datetime import datetime
  255. from optparse import OptionParser
  256. re_hex = re.compile(r'^0x[0-9a-fA-F]+')
  257. re_decimal = re.compile(r'^\d+$')
  258. re_string = re.compile(r"\'(.*)\'$")
  259. dnssec_timefmt = '%Y%m%d%H%M%S'
  260. dict_qr = { 'query' : 0, 'response' : 1 }
  261. dict_opcode = { 'query' : 0, 'iquery' : 1, 'status' : 2, 'notify' : 4,
  262. 'update' : 5 }
  263. rdict_opcode = dict([(dict_opcode[k], k.upper()) for k in dict_opcode.keys()])
  264. dict_rcode = { 'noerror' : 0, 'formerr' : 1, 'servfail' : 2, 'nxdomain' : 3,
  265. 'notimp' : 4, 'refused' : 5, 'yxdomain' : 6, 'yxrrset' : 7,
  266. 'nxrrset' : 8, 'notauth' : 9, 'notzone' : 10 }
  267. rdict_rcode = dict([(dict_rcode[k], k.upper()) for k in dict_rcode.keys()])
  268. dict_rrtype = { 'none' : 0, 'a' : 1, 'ns' : 2, 'md' : 3, 'mf' : 4, 'cname' : 5,
  269. 'soa' : 6, 'mb' : 7, 'mg' : 8, 'mr' : 9, 'null' : 10,
  270. 'wks' : 11, 'ptr' : 12, 'hinfo' : 13, 'minfo' : 14, 'mx' : 15,
  271. 'txt' : 16, 'rp' : 17, 'afsdb' : 18, 'x25' : 19, 'isdn' : 20,
  272. 'rt' : 21, 'nsap' : 22, 'nsap_tr' : 23, 'sig' : 24, 'key' : 25,
  273. 'px' : 26, 'gpos' : 27, 'aaaa' : 28, 'loc' : 29, 'nxt' : 30,
  274. 'srv' : 33, 'naptr' : 35, 'kx' : 36, 'cert' : 37, 'a6' : 38,
  275. 'dname' : 39, 'opt' : 41, 'apl' : 42, 'ds' : 43, 'sshfp' : 44,
  276. 'ipseckey' : 45, 'rrsig' : 46, 'nsec' : 47, 'dnskey' : 48,
  277. 'dhcid' : 49, 'nsec3' : 50, 'nsec3param' : 51, 'hip' : 55,
  278. 'spf' : 99, 'unspec' : 103, 'tkey' : 249, 'tsig' : 250,
  279. 'dlv' : 32769, 'ixfr' : 251, 'axfr' : 252, 'mailb' : 253,
  280. 'maila' : 254, 'any' : 255 }
  281. rdict_rrtype = dict([(dict_rrtype[k], k.upper()) for k in dict_rrtype.keys()])
  282. dict_rrclass = { 'in' : 1, 'ch' : 3, 'hs' : 4, 'any' : 255 }
  283. rdict_rrclass = dict([(dict_rrclass[k], k.upper()) for k in \
  284. dict_rrclass.keys()])
  285. dict_algorithm = { 'rsamd5' : 1, 'dh' : 2, 'dsa' : 3, 'ecc' : 4,
  286. 'rsasha1' : 5 }
  287. dict_nsec3_algorithm = { 'reserved' : 0, 'sha1' : 1 }
  288. rdict_algorithm = dict([(dict_algorithm[k], k.upper()) for k in \
  289. dict_algorithm.keys()])
  290. rdict_nsec3_algorithm = dict([(dict_nsec3_algorithm[k], k.upper()) for k in \
  291. dict_nsec3_algorithm.keys()])
  292. header_xtables = { 'qr' : dict_qr, 'opcode' : dict_opcode,
  293. 'rcode' : dict_rcode }
  294. question_xtables = { 'rrtype' : dict_rrtype, 'rrclass' : dict_rrclass }
  295. def parse_value(value, xtable = {}):
  296. if re.search(re_hex, value):
  297. return int(value, 16)
  298. if re.search(re_decimal, value):
  299. return int(value)
  300. m = re.match(re_string, value)
  301. if m:
  302. return m.group(1)
  303. lovalue = value.lower()
  304. if lovalue in xtable:
  305. return xtable[lovalue]
  306. return value
  307. def code_totext(code, dict):
  308. if code in dict.keys():
  309. return dict[code] + '(' + str(code) + ')'
  310. return str(code)
  311. def encode_name(name, absolute=True):
  312. # make sure the name is dot-terminated. duplicate dots will be ignored
  313. # below.
  314. name += '.'
  315. labels = name.split('.')
  316. wire = ''
  317. for l in labels:
  318. if len(l) > 4 and l[0:4] == 'ptr=':
  319. # special meta-syntax for compression pointer
  320. wire += '%04x' % (0xc000 | int(l[4:]))
  321. break
  322. if absolute or len(l) > 0:
  323. wire += '%02x' % len(l)
  324. wire += ''.join(['%02x' % ord(ch) for ch in l])
  325. if len(l) == 0:
  326. break
  327. return wire
  328. def encode_string(name, len=None):
  329. if type(name) is int and len is not None:
  330. return '%0.*x' % (len * 2, name)
  331. return ''.join(['%02x' % ord(ch) for ch in name])
  332. def count_namelabels(name):
  333. if name == '.': # special case
  334. return 0
  335. m = re.match('^(.*)\.$', name)
  336. if m:
  337. name = m.group(1)
  338. return len(name.split('.'))
  339. def get_config(config, section, configobj, xtables = {}):
  340. try:
  341. for field in config.options(section):
  342. value = config.get(section, field)
  343. if field in xtables.keys():
  344. xtable = xtables[field]
  345. else:
  346. xtable = {}
  347. configobj.__dict__[field] = parse_value(value, xtable)
  348. except configparser.NoSectionError:
  349. return False
  350. return True
  351. def print_header(f, input_file):
  352. f.write('''###
  353. ### This data file was auto-generated from ''' + input_file + '''
  354. ###
  355. ''')
  356. class Name:
  357. '''Implements rendering a single domain name in the test data format.
  358. Configurable parameter is as follows (see the description of the
  359. same name of attribute for the default value):
  360. - name (string): A textual representation of the name, such as
  361. 'example.com'.
  362. - pointer (int): If specified, compression pointer will be
  363. prepended to the generated data with the offset being the value
  364. of this parameter.
  365. '''
  366. name = 'example.com'
  367. pointer = None # no compression by default
  368. def dump(self, f):
  369. name = self.name
  370. if self.pointer is not None:
  371. if len(name) > 0 and name[-1] != '.':
  372. name += '.'
  373. name += 'ptr=%d' % self.pointer
  374. name_wire = encode_name(name)
  375. f.write('\n# DNS Name: %s' % self.name)
  376. if self.pointer is not None:
  377. f.write(' + compression pointer: %d' % self.pointer)
  378. f.write('\n')
  379. f.write('%s' % name_wire)
  380. f.write('\n')
  381. class DNSHeader:
  382. '''Implements rendering a DNS Header section in the test data format.
  383. Configurable parameter is as follows (see the description of the
  384. same name of attribute for the default value):
  385. - id (16-bit int):
  386. - qr, aa, tc, rd, ra, ad, cd (0 or 1): Standard header bits as
  387. defined in RFC1035 and RFC4035. If set to 1, the corresponding
  388. bit will be set; if set to 0, it will be cleared.
  389. - mbz (0-3): The reserved field of the 3rd and 4th octets of the
  390. header.
  391. - rcode (4-bit int or string): The RCODE field. If specified as a
  392. string, it must be the commonly used textual mnemonic of the RCODEs
  393. (NOERROR, FORMERR, etc, case insensitive).
  394. - opcode (4-bit int or string): The OPCODE field. If specified as
  395. a string, it must be the commonly used textual mnemonic of the
  396. OPCODEs (QUERY, NOTIFY, etc, case insensitive).
  397. - qdcount, ancount, nscount, arcount (16-bit int): The QD/AN/NS/AR
  398. COUNT fields, respectively.
  399. '''
  400. id = 0x1035
  401. (qr, aa, tc, rd, ra, ad, cd) = 0, 0, 0, 0, 0, 0, 0
  402. mbz = 0
  403. rcode = 0 # noerror
  404. opcode = 0 # query
  405. (qdcount, ancount, nscount, arcount) = 1, 0, 0, 0
  406. def dump(self, f):
  407. f.write('\n# Header Section\n')
  408. f.write('# ID=' + str(self.id))
  409. f.write(' QR=' + ('Response' if self.qr else 'Query'))
  410. f.write(' Opcode=' + code_totext(self.opcode, rdict_opcode))
  411. f.write(' Rcode=' + code_totext(self.rcode, rdict_rcode))
  412. f.write('%s' % (' AA' if self.aa else ''))
  413. f.write('%s' % (' TC' if self.tc else ''))
  414. f.write('%s' % (' RD' if self.rd else ''))
  415. f.write('%s' % (' AD' if self.ad else ''))
  416. f.write('%s' % (' CD' if self.cd else ''))
  417. f.write('\n')
  418. f.write('%04x ' % self.id)
  419. flag_and_code = 0
  420. flag_and_code |= (self.qr << 15 | self.opcode << 14 | self.aa << 10 |
  421. self.tc << 9 | self.rd << 8 | self.ra << 7 |
  422. self.mbz << 6 | self.ad << 5 | self.cd << 4 |
  423. self.rcode)
  424. f.write('%04x\n' % flag_and_code)
  425. f.write('# QDCNT=%d, ANCNT=%d, NSCNT=%d, ARCNT=%d\n' %
  426. (self.qdcount, self.ancount, self.nscount, self.arcount))
  427. f.write('%04x %04x %04x %04x\n' % (self.qdcount, self.ancount,
  428. self.nscount, self.arcount))
  429. class DNSQuestion:
  430. '''Implements rendering a DNS question in the test data format.
  431. Configurable parameter is as follows (see the description of the
  432. same name of attribute for the default value):
  433. - name (string): The QNAME. The string must be interpreted as a
  434. valid domain name.
  435. - rrtype (int or string): The question type. If specified
  436. as an integer, it must be the 16-bit RR type value of the
  437. covered type. If specifed as a string, it must be the textual
  438. mnemonic of the type.
  439. - rrclass (int or string): The question class. If specified as an
  440. integer, it must be the 16-bit RR class value of the covered
  441. type. If specifed as a string, it must be the textual mnemonic
  442. of the class.
  443. '''
  444. name = 'example.com.'
  445. rrtype = parse_value('A', dict_rrtype)
  446. rrclass = parse_value('IN', dict_rrclass)
  447. def dump(self, f):
  448. f.write('\n# Question Section\n')
  449. f.write('# QNAME=%s QTYPE=%s QCLASS=%s\n' %
  450. (self.name,
  451. code_totext(self.rrtype, rdict_rrtype),
  452. code_totext(self.rrclass, rdict_rrclass)))
  453. f.write(encode_name(self.name))
  454. f.write(' %04x %04x\n' % (self.rrtype, self.rrclass))
  455. class EDNS:
  456. '''Implements rendering EDNS OPT RR in the test data format.
  457. Configurable parameter is as follows (see the description of the
  458. same name of attribute for the default value):
  459. - name (string): The owner name of the OPT RR. The string must be
  460. interpreted as a valid domain name.
  461. - udpsize (16-bit int): The UDP payload size (set as the RR class)
  462. - extrcode (8-bit int): The upper 8 bits of the extended RCODE.
  463. - version (8-bit int): The EDNS version.
  464. - do (int): The DNSSEC DO bit. The bit will be set if this value
  465. is 1; otherwise the bit will be unset.
  466. - mbz (15-bit int): The rest of the flags field.
  467. - rdlen (16-bit int): The RDLEN field. Note: right now specifying
  468. a non 0 value (except for making bogus data) doesn't make sense
  469. because there is no way to configure RDATA.
  470. '''
  471. name = '.'
  472. udpsize = 4096
  473. extrcode = 0
  474. version = 0
  475. do = 0
  476. mbz = 0
  477. rdlen = 0
  478. def dump(self, f):
  479. f.write('\n# EDNS OPT RR\n')
  480. f.write('# NAME=%s TYPE=%s UDPSize=%d ExtRcode=%s Version=%s DO=%d\n' %
  481. (self.name, code_totext(dict_rrtype['opt'], rdict_rrtype),
  482. self.udpsize, self.extrcode, self.version,
  483. 1 if self.do else 0))
  484. code_vers = (self.extrcode << 8) | (self.version & 0x00ff)
  485. extflags = (self.do << 15) | (self.mbz & ~0x8000)
  486. f.write('%s %04x %04x %04x %04x\n' %
  487. (encode_name(self.name), dict_rrtype['opt'], self.udpsize,
  488. code_vers, extflags))
  489. f.write('# RDLEN=%d\n' % self.rdlen)
  490. f.write('%04x\n' % self.rdlen)
  491. class RR:
  492. '''This is a base class for various types of RR test data.
  493. For each RR type (A, AAAA, NS, etc), we define a derived class of RR
  494. to dump type specific RDATA parameters. This class defines parameters
  495. common to all types of RDATA, namely the owner name, RR class and TTL.
  496. The dump() method of derived classes are expected to call dump_header(),
  497. whose default implementation is provided in this class. This method
  498. decides whether to dump the test data as an RR (with name, type, class)
  499. or only as RDATA (with its length), and dumps the corresponding data
  500. via the specified file object.
  501. By convention we assume derived classes are named after the common
  502. standard mnemonic of the corresponding RR types. For example, the
  503. derived class for the RR type SOA should be named "SOA".
  504. Configurable parameters are as follows:
  505. - as_rr (bool): Whether or not the data is to be dumped as an RR.
  506. False by default.
  507. - rr_name (string): The owner name of the RR. The string must be
  508. interpreted as a valid domain name (compression pointer can be
  509. contained). Default is 'example.com.'
  510. - rr_class (string): The RR class of the data. Only meaningful
  511. when the data is dumped as an RR. Default is 'IN'.
  512. - rr_ttl (int): The TTL value of the RR. Only meaningful when
  513. the data is dumped as an RR. Default is 86400 (1 day).
  514. - rdlen (int): 16-bit RDATA length. It can be None (i.e. omitted
  515. in the spec file), in which case the actual length of the
  516. generated RDATA is automatically determined and used; if
  517. negative, the RDLEN field will be omitted from the output data.
  518. (Note that omitting RDLEN with as_rr being True is mostly
  519. meaningless, although the script doesn't complain about it).
  520. Default is None.
  521. '''
  522. def __init__(self):
  523. self.as_rr = False
  524. # only when as_rr is True, same for class/TTL:
  525. self.rr_name = 'example.com'
  526. self.rr_class = 'IN'
  527. self.rr_ttl = 86400
  528. self.rdlen = None
  529. def dump_header(self, f, rdlen):
  530. type_txt = self.__class__.__name__
  531. type_code = parse_value(type_txt, dict_rrtype)
  532. rdlen_spec = ''
  533. rdlen_data = ''
  534. if rdlen >= 0:
  535. rdlen_spec = ', RDLEN=%d' % rdlen
  536. rdlen_data = '%04x' % rdlen
  537. if self.as_rr:
  538. rrclass = parse_value(self.rr_class, dict_rrclass)
  539. f.write('\n# %s RR (QNAME=%s Class=%s TTL=%d%s)\n' %
  540. (type_txt, self.rr_name,
  541. code_totext(rrclass, rdict_rrclass), self.rr_ttl,
  542. rdlen_spec))
  543. f.write('%s %04x %04x %08x %s\n' %
  544. (encode_name(self.rr_name), type_code, rrclass,
  545. self.rr_ttl, rdlen_data))
  546. else:
  547. f.write('\n# %s RDATA%s\n' % (type_txt, rdlen_spec))
  548. f.write('%s\n' % rdlen_data)
  549. class A(RR):
  550. '''Implements rendering A RDATA (of class IN) in the test data format.
  551. Configurable parameter is as follows (see the description of the
  552. same name of attribute for the default value):
  553. - address (string): The address field. This must be a valid textual
  554. IPv4 address.
  555. '''
  556. RDLEN_DEFAULT = 4 # fixed by default
  557. address = '192.0.2.1'
  558. def dump(self, f):
  559. if self.rdlen is None:
  560. self.rdlen = self.RDLEN_DEFAULT
  561. self.dump_header(f, self.rdlen)
  562. f.write('# Address=%s\n' % (self.address))
  563. bin_address = socket.inet_aton(self.address)
  564. f.write('%02x%02x%02x%02x\n' % (bin_address[0], bin_address[1],
  565. bin_address[2], bin_address[3]))
  566. class AAAA(RR):
  567. '''Implements rendering AAAA RDATA (of class IN) in the test data
  568. format.
  569. Configurable parameter is as follows (see the description of the
  570. same name of attribute for the default value):
  571. - address (string): The address field. This must be a valid textual
  572. IPv6 address.
  573. '''
  574. RDLEN_DEFAULT = 16 # fixed by default
  575. address = '2001:db8::1'
  576. def dump(self, f):
  577. if self.rdlen is None:
  578. self.rdlen = self.RDLEN_DEFAULT
  579. self.dump_header(f, self.rdlen)
  580. f.write('# Address=%s\n' % (self.address))
  581. bin_address = socket.inet_pton(socket.AF_INET6, self.address)
  582. [f.write('%02x' % x) for x in bin_address]
  583. f.write('\n')
  584. class NS(RR):
  585. '''Implements rendering NS RDATA in the test data format.
  586. Configurable parameter is as follows (see the description of the
  587. same name of attribute for the default value):
  588. - nsname (string): The NSDNAME field. The string must be
  589. interpreted as a valid domain name.
  590. '''
  591. nsname = 'ns.example.com'
  592. def dump(self, f):
  593. nsname_wire = encode_name(self.nsname)
  594. if self.rdlen is None:
  595. self.rdlen = len(nsname_wire) / 2
  596. self.dump_header(f, self.rdlen)
  597. f.write('# NS name=%s\n' % (self.nsname))
  598. f.write('%s\n' % nsname_wire)
  599. class SOA(RR):
  600. '''Implements rendering SOA RDATA in the test data format.
  601. Configurable parameters are as follows (see the description of the
  602. same name of attribute for the default value):
  603. - mname/rname (string): The MNAME/RNAME fields, respectively. The
  604. string must be interpreted as a valid domain name.
  605. - serial (32-bit int): The SERIAL field
  606. - refresh (32-bit int): The REFRESH field
  607. - retry (32-bit int): The RETRY field
  608. - expire (32-bit int): The EXPIRE field
  609. - minimum (32-bit int): The MINIMUM field
  610. '''
  611. mname = 'ns.example.com'
  612. rname = 'root.example.com'
  613. serial = 2010012601
  614. refresh = 3600
  615. retry = 300
  616. expire = 3600000
  617. minimum = 1200
  618. def dump(self, f):
  619. mname_wire = encode_name(self.mname)
  620. rname_wire = encode_name(self.rname)
  621. if self.rdlen is None:
  622. self.rdlen = int(20 + len(mname_wire) / 2 + len(str(rname_wire)) / 2)
  623. self.dump_header(f, self.rdlen)
  624. f.write('# NNAME=%s RNAME=%s\n' % (self.mname, self.rname))
  625. f.write('%s %s\n' % (mname_wire, rname_wire))
  626. f.write('# SERIAL(%d) REFRESH(%d) RETRY(%d) EXPIRE(%d) MINIMUM(%d)\n' %
  627. (self.serial, self.refresh, self.retry, self.expire,
  628. self.minimum))
  629. f.write('%08x %08x %08x %08x %08x\n' % (self.serial, self.refresh,
  630. self.retry, self.expire,
  631. self.minimum))
  632. class TXT(RR):
  633. '''Implements rendering TXT RDATA in the test data format.
  634. Configurable parameters are as follows (see the description of the
  635. same name of attribute for the default value):
  636. - nstring (int): number of character-strings
  637. - stringlenN (int) (int, N = 0, ..., nstring-1): the length of the
  638. N-th character-string.
  639. - stringN (string, N = 0, ..., nstring-1): the N-th
  640. character-string.
  641. - stringlen (int): the default string. If nstring >= 1 and the
  642. corresponding stringlenN isn't specified in the spec file, this
  643. value will be used. If this parameter isn't specified either,
  644. the length of the string will be used. Note that it means
  645. this parameter (or any stringlenN) doesn't have to be specified
  646. unless you want to intentionally build a broken character string.
  647. - string (string): the default string. If nstring >= 1 and the
  648. corresponding stringN isn't specified in the spec file, this
  649. string will be used.
  650. '''
  651. nstring = 1
  652. stringlen = None
  653. string = 'Test-String'
  654. def dump(self, f):
  655. stringlen_list = []
  656. string_list = []
  657. wirestring_list = []
  658. for i in range(0, self.nstring):
  659. key_string = 'string' + str(i)
  660. if key_string in self.__dict__:
  661. string_list.append(self.__dict__[key_string])
  662. else:
  663. string_list.append(self.string)
  664. wirestring_list.append(encode_string(string_list[-1]))
  665. key_stringlen = 'stringlen' + str(i)
  666. if key_stringlen in self.__dict__:
  667. stringlen_list.append(self.__dict__[key_stringlen])
  668. else:
  669. stringlen_list.append(self.stringlen)
  670. if stringlen_list[-1] is None:
  671. stringlen_list[-1] = int(len(wirestring_list[-1]) / 2)
  672. if self.rdlen is None:
  673. self.rdlen = int(len(''.join(wirestring_list)) / 2) + self.nstring
  674. self.dump_header(f, self.rdlen)
  675. for i in range(0, self.nstring):
  676. f.write('# String Len=%d, String=\"%s\"\n' %
  677. (stringlen_list[i], string_list[i]))
  678. f.write('%02x%s%s\n' % (stringlen_list[i],
  679. ' ' if len(wirestring_list[i]) > 0 else '',
  680. wirestring_list[i]))
  681. class RP(RR):
  682. '''Implements rendering RP RDATA in the test data format.
  683. Configurable parameters are as follows (see the description of the
  684. same name of attribute for the default value):
  685. - mailbox (string): The mailbox field.
  686. - text (string): The text field.
  687. These strings must be interpreted as a valid domain name.
  688. '''
  689. mailbox = 'root.example.com'
  690. text = 'rp-text.example.com'
  691. def dump(self, f):
  692. mailbox_wire = encode_name(self.mailbox)
  693. text_wire = encode_name(self.text)
  694. if self.rdlen is None:
  695. self.rdlen = (len(mailbox_wire) + len(text_wire)) / 2
  696. else:
  697. self.rdlen = int(self.rdlen)
  698. self.dump_header(f, self.rdlen)
  699. f.write('# MAILBOX=%s TEXT=%s\n' % (self.mailbox, self.text))
  700. f.write('%s %s\n' % (mailbox_wire, text_wire))
  701. class SSHFP(RR):
  702. '''Implements rendering SSHFP RDATA in the test data format.
  703. Configurable parameters are as follows (see the description of the
  704. same name of attribute for the default value):
  705. - algorithm (int): The algorithm number.
  706. - fingerprint_type (int): The fingerprint type.
  707. - fingerprint (string): The fingerprint.
  708. '''
  709. algorithm = 2
  710. fingerprint_type = 1
  711. fingerprint = '123456789abcdef67890123456789abcdef67890'
  712. def dump(self, f):
  713. if self.rdlen is None:
  714. self.rdlen = 2 + (len(self.fingerprint) / 2)
  715. else:
  716. self.rdlen = int(self.rdlen)
  717. self.dump_header(f, self.rdlen)
  718. f.write('# ALGORITHM=%d FINGERPRINT_TYPE=%d FINGERPRINT=%s\n' % (self.algorithm,
  719. self.fingerprint_type,
  720. self.fingerprint))
  721. f.write('%02x %02x %s\n' % (self.algorithm, self.fingerprint_type, self.fingerprint))
  722. class MINFO(RR):
  723. '''Implements rendering MINFO RDATA in the test data format.
  724. Configurable parameters are as follows (see the description of the
  725. same name of attribute for the default value):
  726. - rmailbox (string): The rmailbox field.
  727. - emailbox (string): The emailbox field.
  728. These strings must be interpreted as a valid domain name.
  729. '''
  730. rmailbox = 'rmailbox.example.com'
  731. emailbox = 'emailbox.example.com'
  732. def dump(self, f):
  733. rmailbox_wire = encode_name(self.rmailbox)
  734. emailbox_wire = encode_name(self.emailbox)
  735. if self.rdlen is None:
  736. self.rdlen = (len(rmailbox_wire) + len(emailbox_wire)) / 2
  737. else:
  738. self.rdlen = int(self.rdlen)
  739. self.dump_header(f, self.rdlen)
  740. f.write('# RMAILBOX=%s EMAILBOX=%s\n' % (self.rmailbox, self.emailbox))
  741. f.write('%s %s\n' % (rmailbox_wire, emailbox_wire))
  742. class AFSDB(RR):
  743. '''Implements rendering AFSDB RDATA in the test data format.
  744. Configurable parameters are as follows (see the description of the
  745. same name of attribute for the default value):
  746. - subtype (16 bit int): The subtype field.
  747. - server (string): The server field.
  748. The string must be interpreted as a valid domain name.
  749. '''
  750. subtype = 1
  751. server = 'afsdb.example.com'
  752. def dump(self, f):
  753. server_wire = encode_name(self.server)
  754. if self.rdlen is None:
  755. self.rdlen = 2 + len(server_wire) / 2
  756. else:
  757. self.rdlen = int(self.rdlen)
  758. self.dump_header(f, self.rdlen)
  759. f.write('# SUBTYPE=%d SERVER=%s\n' % (self.subtype, self.server))
  760. f.write('%04x %s\n' % (self.subtype, server_wire))
  761. class NSECBASE(RR):
  762. '''Implements rendering NSEC/NSEC3 type bitmaps commonly used for
  763. these RRs. The NSEC and NSEC3 classes will be inherited from this
  764. class.
  765. Configurable parameters are as follows (see the description of the
  766. same name of attribute for the default value):
  767. - nbitmap (int): The number of type bitmaps.
  768. The following three define the bitmaps. If suffixed with "N"
  769. (0 <= N < nbitmaps), it means the definition for the N-th bitmap.
  770. If there is no suffix (e.g., just "block", it means the default
  771. for any unspecified values)
  772. - block[N] (8-bit int): The Window Block.
  773. - maplen[N] (8-bit int): The Bitmap Length. The default "maplen"
  774. can also be unspecified (with being set to None), in which case
  775. the corresponding length will be calculated from the bitmap.
  776. - bitmap[N] (string): The Bitmap. This must be the hexadecimal
  777. representation of the bitmap field. For example, for a bitmap
  778. where the 7th and 15th bits (and only these bits) are set, it
  779. must be '0101'. Note also that the value must be quated with
  780. single quatations because it could also be interpreted as an
  781. integer.
  782. '''
  783. nbitmap = 1 # number of bitmaps
  784. block = 0
  785. maplen = None # default bitmap length, auto-calculate
  786. bitmap = '040000000003' # an arbitrarily chosen bitmap sample
  787. def dump(self, f):
  788. # first, construct the bitmap data
  789. block_list = []
  790. maplen_list = []
  791. bitmap_list = []
  792. for i in range(0, self.nbitmap):
  793. key_bitmap = 'bitmap' + str(i)
  794. if key_bitmap in self.__dict__:
  795. bitmap_list.append(self.__dict__[key_bitmap])
  796. else:
  797. bitmap_list.append(self.bitmap)
  798. key_maplen = 'maplen' + str(i)
  799. if key_maplen in self.__dict__:
  800. maplen_list.append(self.__dict__[key_maplen])
  801. else:
  802. maplen_list.append(self.maplen)
  803. if maplen_list[-1] is None: # calculate it if not specified
  804. maplen_list[-1] = int(len(bitmap_list[-1]) / 2)
  805. key_block = 'block' + str(i)
  806. if key_block in self.__dict__:
  807. block_list.append(self.__dict__[key_block])
  808. else:
  809. block_list.append(self.block)
  810. # dump RR-type specific part (NSEC or NSEC3)
  811. self.dump_fixedpart(f, 2 * self.nbitmap + \
  812. int(len(''.join(bitmap_list)) / 2))
  813. # dump the bitmap
  814. for i in range(0, self.nbitmap):
  815. f.write('# Bitmap: Block=%d, Length=%d\n' %
  816. (block_list[i], maplen_list[i]))
  817. f.write('%02x %02x %s\n' %
  818. (block_list[i], maplen_list[i], bitmap_list[i]))
  819. class NSEC(NSECBASE):
  820. '''Implements rendering NSEC RDATA in the test data format.
  821. Configurable parameters are as follows (see the description of the
  822. same name of attribute for the default value):
  823. - Type bitmap related parameters: see class NSECBASE
  824. - nextname (string): The Next Domain Name field. The string must be
  825. interpreted as a valid domain name.
  826. '''
  827. nextname = 'next.example.com'
  828. def dump_fixedpart(self, f, bitmap_totallen):
  829. name_wire = encode_name(self.nextname)
  830. if self.rdlen is None:
  831. # if rdlen needs to be calculated, it must be based on the bitmap
  832. # length, because the configured maplen can be fake.
  833. self.rdlen = int(len(name_wire) / 2) + bitmap_totallen
  834. self.dump_header(f, self.rdlen)
  835. f.write('# Next Name=%s (%d bytes)\n' % (self.nextname,
  836. int(len(name_wire) / 2)))
  837. f.write('%s\n' % name_wire)
  838. class NSEC3PARAM(RR):
  839. '''Implements rendering NSEC3PARAM RDATA in the test data format.
  840. Configurable parameters are as follows (see the description of the
  841. same name of attribute for the default value):
  842. - hashalg (8-bit int): The Hash Algorithm field. Note that
  843. currently the only defined algorithm is SHA-1, for which a value
  844. of 1 will be used, and it's the default. So this implementation
  845. does not support any string representation right now.
  846. - optout (bool): The Opt-Out flag of the Flags field.
  847. - mbz (7-bit int): The rest of the Flags field. This value will
  848. be left shifted for 1 bit and then OR-ed with optout to
  849. construct the complete Flags field.
  850. - iterations (16-bit int): The Iterations field.
  851. - saltlen (int): The Salt Length field.
  852. - salt (string): The Salt field. It is converted to a sequence of
  853. ascii codes and its hexadecimal representation will be used.
  854. '''
  855. hashalg = 1 # SHA-1
  856. optout = False # opt-out flag
  857. mbz = 0 # other flag fields (none defined yet)
  858. iterations = 1
  859. saltlen = 5
  860. salt = 's' * saltlen
  861. def dump(self, f):
  862. if self.rdlen is None:
  863. self.rdlen = 4 + 1 + len(self.salt)
  864. self.dump_header(f, self.rdlen)
  865. self._dump_params(f)
  866. def _dump_params(self, f):
  867. '''This method is intended to be shared with NSEC3 class.
  868. '''
  869. optout_val = 1 if self.optout else 0
  870. f.write('# Hash Alg=%s, Opt-Out=%d, Other Flags=%0x, Iterations=%d\n' %
  871. (code_totext(self.hashalg, rdict_nsec3_algorithm),
  872. optout_val, self.mbz, self.iterations))
  873. f.write('%02x %02x %04x\n' %
  874. (self.hashalg, (self.mbz << 1) | optout_val, self.iterations))
  875. f.write("# Salt Len=%d, Salt='%s'\n" % (self.saltlen, self.salt))
  876. f.write('%02x%s%s\n' % (self.saltlen,
  877. ' ' if len(self.salt) > 0 else '',
  878. encode_string(self.salt)))
  879. class NSEC3(NSECBASE, NSEC3PARAM):
  880. '''Implements rendering NSEC3 RDATA in the test data format.
  881. Configurable parameters are as follows (see the description of the
  882. same name of attribute for the default value):
  883. - Type bitmap related parameters: see class NSECBASE
  884. - Hash parameter related parameters: see class NSEC3PARAM
  885. - hashlen (int): The Hash Length field.
  886. - hash (string): The Next Hashed Owner Name field. This parameter
  887. is interpreted as "salt".
  888. '''
  889. hashlen = 20
  890. hash = 'h' * hashlen
  891. def dump_fixedpart(self, f, bitmap_totallen):
  892. if self.rdlen is None:
  893. # if rdlen needs to be calculated, it must be based on the bitmap
  894. # length, because the configured maplen can be fake.
  895. self.rdlen = 4 + 1 + len(self.salt) + 1 + len(self.hash) \
  896. + bitmap_totallen
  897. self.dump_header(f, self.rdlen)
  898. self._dump_params(f)
  899. f.write("# Hash Len=%d, Hash='%s'\n" % (self.hashlen, self.hash))
  900. f.write('%02x%s%s\n' % (self.hashlen,
  901. ' ' if len(self.hash) > 0 else '',
  902. encode_string(self.hash)))
  903. class RRSIG(RR):
  904. '''Implements rendering RRSIG RDATA in the test data format.
  905. Configurable parameters are as follows (see the description of the
  906. same name of attribute for the default value):
  907. - covered (int or string): The Type Covered field. If specified
  908. as an integer, it must be the 16-bit RR type value of the
  909. covered type. If specifed as a string, it must be the textual
  910. mnemonic of the type.
  911. - algorithm (int or string): The Algorithm field. If specified
  912. as an integer, it must be the 8-bit algorithm number as defined
  913. in RFC4034. If specifed as a string, it must be one of the keys
  914. of dict_algorithm (case insensitive).
  915. - labels (int): The Labels field. If omitted (the corresponding
  916. variable being set to None), the number of labels of "signer"
  917. (excluding the trailing null label as specified in RFC4034) will
  918. be used.
  919. - originalttl (32-bit int): The Original TTL field.
  920. - expiration (32-bit int): The Expiration TTL field.
  921. - inception (32-bit int): The Inception TTL field.
  922. - tag (16-bit int): The Key Tag field.
  923. - signer (string): The Signer's Name field. The string must be
  924. interpreted as a valid domain name.
  925. - signature (int): The Signature field. Right now only a simple
  926. integer form is supported. A prefix of "0" will be prepended if
  927. the resulting hexadecimal representation consists of an odd
  928. number of characters.
  929. '''
  930. covered = 'A'
  931. algorithm = 'RSASHA1'
  932. labels = None # auto-calculate (#labels of signer)
  933. originalttl = 3600
  934. expiration = int(time.mktime(datetime.strptime('20100131120000',
  935. dnssec_timefmt).timetuple()))
  936. inception = int(time.mktime(datetime.strptime('20100101120000',
  937. dnssec_timefmt).timetuple()))
  938. tag = 0x1035
  939. signer = 'example.com'
  940. signature = 0x123456789abcdef123456789abcdef
  941. def dump(self, f):
  942. name_wire = encode_name(self.signer)
  943. sig_wire = '%x' % self.signature
  944. if len(sig_wire) % 2 != 0:
  945. sig_wire = '0' + sig_wire
  946. if self.rdlen is None:
  947. self.rdlen = int(18 + len(name_wire) / 2 + len(str(sig_wire)) / 2)
  948. self.dump_header(f, self.rdlen)
  949. if type(self.covered) is str:
  950. self.covered = dict_rrtype[self.covered.lower()]
  951. if type(self.algorithm) is str:
  952. self.algorithm = dict_algorithm[self.algorithm.lower()]
  953. if self.labels is None:
  954. self.labels = count_namelabels(self.signer)
  955. f.write('# Covered=%s Algorithm=%s Labels=%d OrigTTL=%d\n' %
  956. (code_totext(self.covered, rdict_rrtype),
  957. code_totext(self.algorithm, rdict_algorithm), self.labels,
  958. self.originalttl))
  959. f.write('%04x %02x %02x %08x\n' % (self.covered, self.algorithm,
  960. self.labels, self.originalttl))
  961. f.write('# Expiration=%s, Inception=%s\n' %
  962. (str(self.expiration), str(self.inception)))
  963. f.write('%08x %08x\n' % (self.expiration, self.inception))
  964. f.write('# Tag=%d Signer=%s and Signature\n' % (self.tag, self.signer))
  965. f.write('%04x %s %s\n' % (self.tag, name_wire, sig_wire))
  966. class TSIG(RR):
  967. '''Implements rendering TSIG RDATA in the test data format.
  968. As a meta RR type TSIG uses some non common parameters. This
  969. class overrides some of the default attributes of the RR class
  970. accordingly:
  971. - rr_class is set to 'ANY'
  972. - rr_ttl is set to 0
  973. Like other derived classes these can be overridden via the spec
  974. file.
  975. Other configurable parameters are as follows (see the description
  976. of the same name of attribute for the default value):
  977. - algorithm (string): The Algorithm Name field. The value is
  978. generally interpreted as a domain name string, and will
  979. typically be one of the standard algorithm names defined in
  980. RFC4635. For convenience, however, a shortcut value "hmac-md5"
  981. is allowed instead of the standard "hmac-md5.sig-alg.reg.int".
  982. - time_signed (48-bit int): The Time Signed field.
  983. - fudge (16-bit int): The Fudge field.
  984. - mac_size (int): The MAC Size field. If omitted, the common value
  985. determined by the algorithm will be used.
  986. - mac (int or string): The MAC field. If specified as an integer,
  987. the integer value is used as the MAC, possibly with prepended
  988. 0's so that the total length will be mac_size. If specifed as a
  989. string, it is converted to a sequence of ascii codes and its
  990. hexadecimal representation will be used. So, for example, if
  991. "mac" is set to 'abc', it will be converted to '616263'. Note
  992. that in this case the length of "mac" may not be equal to
  993. mac_size. If unspecified, the mac_size number of '78' (ascii
  994. code of 'x') will be used.
  995. - original_id (16-bit int): The Original ID field.
  996. - error (16-bit int): The Error field.
  997. - other_len (int): The Other Len field.
  998. - other_data (int or string): The Other Data field. This is
  999. interpreted just like "mac" except that other_len is used
  1000. instead of mac_size. If unspecified this will be empty unless
  1001. the "error" is set to 18 (which means the "BADTIME" error), in
  1002. which case a hexadecimal representation of "time_signed + fudge
  1003. + 1" will be used.
  1004. '''
  1005. algorithm = 'hmac-sha256'
  1006. time_signed = 1286978795 # arbitrarily chosen default
  1007. fudge = 300
  1008. mac_size = None # use a common value for the algorithm
  1009. mac = None # use 'x' * mac_size
  1010. original_id = 2845 # arbitrarily chosen default
  1011. error = 0
  1012. other_len = None # 6 if error is BADTIME; otherwise 0
  1013. other_data = None # use time_signed + fudge + 1 for BADTIME
  1014. dict_macsize = { 'hmac-md5' : 16, 'hmac-sha1' : 20, 'hmac-sha256' : 32 }
  1015. # TSIG has some special defaults
  1016. def __init__(self):
  1017. super().__init__()
  1018. self.rr_class = 'ANY'
  1019. self.rr_ttl = 0
  1020. def dump(self, f):
  1021. if str(self.algorithm) == 'hmac-md5':
  1022. name_wire = encode_name('hmac-md5.sig-alg.reg.int')
  1023. else:
  1024. name_wire = encode_name(self.algorithm)
  1025. mac_size = self.mac_size
  1026. if mac_size is None:
  1027. if self.algorithm in self.dict_macsize.keys():
  1028. mac_size = self.dict_macsize[self.algorithm]
  1029. else:
  1030. raise RuntimeError('TSIG Mac Size cannot be determined')
  1031. mac = encode_string('x' * mac_size) if self.mac is None else \
  1032. encode_string(self.mac, mac_size)
  1033. other_len = self.other_len
  1034. if other_len is None:
  1035. # 18 = BADTIME
  1036. other_len = 6 if self.error == 18 else 0
  1037. other_data = self.other_data
  1038. if other_data is None:
  1039. other_data = '%012x' % (self.time_signed + self.fudge + 1) \
  1040. if self.error == 18 else ''
  1041. else:
  1042. other_data = encode_string(self.other_data, other_len)
  1043. if self.rdlen is None:
  1044. self.rdlen = int(len(name_wire) / 2 + 16 + len(mac) / 2 + \
  1045. len(other_data) / 2)
  1046. self.dump_header(f, self.rdlen)
  1047. f.write('# Algorithm=%s Time-Signed=%d Fudge=%d\n' %
  1048. (self.algorithm, self.time_signed, self.fudge))
  1049. f.write('%s %012x %04x\n' % (name_wire, self.time_signed, self.fudge))
  1050. f.write('# MAC Size=%d MAC=(see hex)\n' % mac_size)
  1051. f.write('%04x%s\n' % (mac_size, ' ' + mac if len(mac) > 0 else ''))
  1052. f.write('# Original-ID=%d Error=%d\n' % (self.original_id, self.error))
  1053. f.write('%04x %04x\n' % (self.original_id, self.error))
  1054. f.write('# Other-Len=%d Other-Data=(see hex)\n' % other_len)
  1055. f.write('%04x%s\n' % (other_len,
  1056. ' ' + other_data if len(other_data) > 0 else ''))
  1057. # Build section-class mapping
  1058. config_param = { 'name' : (Name, {}),
  1059. 'header' : (DNSHeader, header_xtables),
  1060. 'question' : (DNSQuestion, question_xtables),
  1061. 'edns' : (EDNS, {}) }
  1062. for rrtype in dict_rrtype.keys():
  1063. # For any supported RR types add the tuple of (RR_CLASS, {}).
  1064. # We expect KeyError as not all the types are supported, and simply
  1065. # ignore them.
  1066. try:
  1067. cur_mod = sys.modules[__name__]
  1068. config_param[rrtype] = (cur_mod.__dict__[rrtype.upper()], {})
  1069. except KeyError:
  1070. pass
  1071. def get_config_param(section):
  1072. s = section
  1073. m = re.match('^([^:]+)/\d+$', section)
  1074. if m:
  1075. s = m.group(1)
  1076. return config_param[s]
  1077. usage = '''usage: %prog [options] input_file'''
  1078. if __name__ == "__main__":
  1079. parser = OptionParser(usage=usage)
  1080. parser.add_option('-o', '--output', action='store', dest='output',
  1081. default=None, metavar='FILE',
  1082. help='output file name [default: prefix of input_file]')
  1083. (options, args) = parser.parse_args()
  1084. if len(args) == 0:
  1085. parser.error('input file is missing')
  1086. configfile = args[0]
  1087. outputfile = options.output
  1088. if not outputfile:
  1089. m = re.match('(.*)\.[^.]+$', configfile)
  1090. if m:
  1091. outputfile = m.group(1)
  1092. else:
  1093. raise ValueError('output file is not specified and input file is not in the form of "output_file.suffix"')
  1094. config = configparser.SafeConfigParser()
  1095. config.read(configfile)
  1096. output = open(outputfile, 'w')
  1097. print_header(output, configfile)
  1098. # First try the 'custom' mode; if it fails assume the query mode.
  1099. try:
  1100. sections = config.get('custom', 'sections').split(':')
  1101. except configparser.NoSectionError:
  1102. sections = ['header', 'question', 'edns']
  1103. for s in sections:
  1104. section_param = get_config_param(s)
  1105. (obj, xtables) = (section_param[0](), section_param[1])
  1106. if get_config(config, s, obj, xtables):
  1107. obj.dump(output)
  1108. output.close()