dns.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. // Copyright 2014 Google, Inc. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the LICENSE file in the root of the source
  5. // tree.
  6. package layers
  7. import (
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "net"
  12. "github.com/google/gopacket"
  13. )
  14. // DNSClass defines the class associated with a request/response. Different DNS
  15. // classes can be thought of as an array of parallel namespace trees.
  16. type DNSClass uint16
  17. // DNSClass known values.
  18. const (
  19. DNSClassIN DNSClass = 1 // Internet
  20. DNSClassCS DNSClass = 2 // the CSNET class (Obsolete)
  21. DNSClassCH DNSClass = 3 // the CHAOS class
  22. DNSClassHS DNSClass = 4 // Hesiod [Dyer 87]
  23. DNSClassAny DNSClass = 255 // AnyClass
  24. )
  25. func (dc DNSClass) String() string {
  26. switch dc {
  27. default:
  28. return "Unknown"
  29. case DNSClassIN:
  30. return "IN"
  31. case DNSClassCS:
  32. return "CS"
  33. case DNSClassCH:
  34. return "CH"
  35. case DNSClassHS:
  36. return "HS"
  37. case DNSClassAny:
  38. return "Any"
  39. }
  40. }
  41. // DNSType defines the type of data being requested/returned in a
  42. // question/answer.
  43. type DNSType uint16
  44. // DNSType known values.
  45. const (
  46. DNSTypeA DNSType = 1 // a host address
  47. DNSTypeNS DNSType = 2 // an authoritative name server
  48. DNSTypeMD DNSType = 3 // a mail destination (Obsolete - use MX)
  49. DNSTypeMF DNSType = 4 // a mail forwarder (Obsolete - use MX)
  50. DNSTypeCNAME DNSType = 5 // the canonical name for an alias
  51. DNSTypeSOA DNSType = 6 // marks the start of a zone of authority
  52. DNSTypeMB DNSType = 7 // a mailbox domain name (EXPERIMENTAL)
  53. DNSTypeMG DNSType = 8 // a mail group member (EXPERIMENTAL)
  54. DNSTypeMR DNSType = 9 // a mail rename domain name (EXPERIMENTAL)
  55. DNSTypeNULL DNSType = 10 // a null RR (EXPERIMENTAL)
  56. DNSTypeWKS DNSType = 11 // a well known service description
  57. DNSTypePTR DNSType = 12 // a domain name pointer
  58. DNSTypeHINFO DNSType = 13 // host information
  59. DNSTypeMINFO DNSType = 14 // mailbox or mail list information
  60. DNSTypeMX DNSType = 15 // mail exchange
  61. DNSTypeTXT DNSType = 16 // text strings
  62. DNSTypeAAAA DNSType = 28 // a IPv6 host address [RFC3596]
  63. DNSTypeSRV DNSType = 33 // server discovery [RFC2782] [RFC6195]
  64. )
  65. func (dt DNSType) String() string {
  66. switch dt {
  67. default:
  68. return "Unknown"
  69. case DNSTypeA:
  70. return "A"
  71. case DNSTypeNS:
  72. return "NS"
  73. case DNSTypeMD:
  74. return "MD"
  75. case DNSTypeMF:
  76. return "MF"
  77. case DNSTypeCNAME:
  78. return "CNAME"
  79. case DNSTypeSOA:
  80. return "SOA"
  81. case DNSTypeMB:
  82. return "MB"
  83. case DNSTypeMG:
  84. return "MG"
  85. case DNSTypeMR:
  86. return "MR"
  87. case DNSTypeNULL:
  88. return "NULL"
  89. case DNSTypeWKS:
  90. return "WKS"
  91. case DNSTypePTR:
  92. return "PTR"
  93. case DNSTypeHINFO:
  94. return "HINFO"
  95. case DNSTypeMINFO:
  96. return "MINFO"
  97. case DNSTypeMX:
  98. return "MX"
  99. case DNSTypeTXT:
  100. return "TXT"
  101. case DNSTypeAAAA:
  102. return "AAAA"
  103. case DNSTypeSRV:
  104. return "SRV"
  105. }
  106. }
  107. // DNSResponseCode provides response codes for question answers.
  108. type DNSResponseCode uint8
  109. // DNSResponseCode known values.
  110. const (
  111. DNSResponseCodeNoErr DNSResponseCode = 0 // No error
  112. DNSResponseCodeFormErr DNSResponseCode = 1 // Format Error [RFC1035]
  113. DNSResponseCodeServFail DNSResponseCode = 2 // Server Failure [RFC1035]
  114. DNSResponseCodeNXDomain DNSResponseCode = 3 // Non-Existent Domain [RFC1035]
  115. DNSResponseCodeNotImp DNSResponseCode = 4 // Not Implemented [RFC1035]
  116. DNSResponseCodeRefused DNSResponseCode = 5 // Query Refused [RFC1035]
  117. DNSResponseCodeYXDomain DNSResponseCode = 6 // Name Exists when it should not [RFC2136]
  118. DNSResponseCodeYXRRSet DNSResponseCode = 7 // RR Set Exists when it should not [RFC2136]
  119. DNSResponseCodeNXRRSet DNSResponseCode = 8 // RR Set that should exist does not [RFC2136]
  120. DNSResponseCodeNotAuth DNSResponseCode = 9 // Server Not Authoritative for zone [RFC2136]
  121. DNSResponseCodeNotZone DNSResponseCode = 10 // Name not contained in zone [RFC2136]
  122. DNSResponseCodeBadVers DNSResponseCode = 16 // Bad OPT Version [RFC2671]
  123. DNSResponseCodeBadSig DNSResponseCode = 16 // TSIG Signature Failure [RFC2845]
  124. DNSResponseCodeBadKey DNSResponseCode = 17 // Key not recognized [RFC2845]
  125. DNSResponseCodeBadTime DNSResponseCode = 18 // Signature out of time window [RFC2845]
  126. DNSResponseCodeBadMode DNSResponseCode = 19 // Bad TKEY Mode [RFC2930]
  127. DNSResponseCodeBadName DNSResponseCode = 20 // Duplicate key name [RFC2930]
  128. DNSResponseCodeBadAlg DNSResponseCode = 21 // Algorithm not supported [RFC2930]
  129. DNSResponseCodeBadTruc DNSResponseCode = 22 // Bad Truncation [RFC4635]
  130. )
  131. func (drc DNSResponseCode) String() string {
  132. switch drc {
  133. default:
  134. return "Unknown"
  135. case DNSResponseCodeNoErr:
  136. return "No Error"
  137. case DNSResponseCodeFormErr:
  138. return "Format Error"
  139. case DNSResponseCodeServFail:
  140. return "Server Failure "
  141. case DNSResponseCodeNXDomain:
  142. return "Non-Existent Domain"
  143. case DNSResponseCodeNotImp:
  144. return "Not Implemented"
  145. case DNSResponseCodeRefused:
  146. return "Query Refused"
  147. case DNSResponseCodeYXDomain:
  148. return "Name Exists when it should not"
  149. case DNSResponseCodeYXRRSet:
  150. return "RR Set Exists when it should not"
  151. case DNSResponseCodeNXRRSet:
  152. return "RR Set that should exist does not"
  153. case DNSResponseCodeNotAuth:
  154. return "Server Not Authoritative for zone"
  155. case DNSResponseCodeNotZone:
  156. return "Name not contained in zone"
  157. case DNSResponseCodeBadVers:
  158. return "Bad OPT Version"
  159. case DNSResponseCodeBadKey:
  160. return "Key not recognized"
  161. case DNSResponseCodeBadTime:
  162. return "Signature out of time window"
  163. case DNSResponseCodeBadMode:
  164. return "Bad TKEY Mode"
  165. case DNSResponseCodeBadName:
  166. return "Duplicate key name"
  167. case DNSResponseCodeBadAlg:
  168. return "Algorithm not supported"
  169. case DNSResponseCodeBadTruc:
  170. return "Bad Truncation"
  171. }
  172. }
  173. // DNSOpCode defines a set of different operation types.
  174. type DNSOpCode uint8
  175. // DNSOpCode known values.
  176. const (
  177. DNSOpCodeQuery DNSOpCode = 0 // Query [RFC1035]
  178. DNSOpCodeIQuery DNSOpCode = 1 // Inverse Query Obsolete [RFC3425]
  179. DNSOpCodeStatus DNSOpCode = 2 // Status [RFC1035]
  180. DNSOpCodeNotify DNSOpCode = 4 // Notify [RFC1996]
  181. DNSOpCodeUpdate DNSOpCode = 5 // Update [RFC2136]
  182. )
  183. func (doc DNSOpCode) String() string {
  184. switch doc {
  185. default:
  186. return "Unknown"
  187. case DNSOpCodeQuery:
  188. return "Query"
  189. case DNSOpCodeIQuery:
  190. return "Inverse Query"
  191. case DNSOpCodeStatus:
  192. return "Status"
  193. case DNSOpCodeNotify:
  194. return "Notify"
  195. case DNSOpCodeUpdate:
  196. return "Update"
  197. }
  198. }
  199. // DNS is specified in RFC 1034 / RFC 1035
  200. // +---------------------+
  201. // | Header |
  202. // +---------------------+
  203. // | Question | the question for the name server
  204. // +---------------------+
  205. // | Answer | RRs answering the question
  206. // +---------------------+
  207. // | Authority | RRs pointing toward an authority
  208. // +---------------------+
  209. // | Additional | RRs holding additional information
  210. // +---------------------+
  211. //
  212. // DNS Header
  213. // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
  214. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  215. // | ID |
  216. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  217. // |QR| Opcode |AA|TC|RD|RA| Z | RCODE |
  218. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  219. // | QDCOUNT |
  220. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  221. // | ANCOUNT |
  222. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  223. // | NSCOUNT |
  224. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  225. // | ARCOUNT |
  226. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  227. // DNS contains data from a single Domain Name Service packet.
  228. type DNS struct {
  229. BaseLayer
  230. // Header fields
  231. ID uint16
  232. QR bool
  233. OpCode DNSOpCode
  234. AA bool // Authoritative answer
  235. TC bool // Truncated
  236. RD bool // Recursion desired
  237. RA bool // Recursion available
  238. Z uint8 // Reserved for future use
  239. ResponseCode DNSResponseCode
  240. QDCount uint16 // Number of questions to expect
  241. ANCount uint16 // Number of answers to expect
  242. NSCount uint16 // Number of authorities to expect
  243. ARCount uint16 // Number of additional records to expect
  244. // Entries
  245. Questions []DNSQuestion
  246. Answers []DNSResourceRecord
  247. Authorities []DNSResourceRecord
  248. Additionals []DNSResourceRecord
  249. // buffer for doing name decoding. We use a single reusable buffer to avoid
  250. // name decoding on a single object via multiple DecodeFromBytes calls
  251. // requiring constant allocation of small byte slices.
  252. buffer []byte
  253. }
  254. // LayerType returns gopacket.LayerTypeDNS.
  255. func (d *DNS) LayerType() gopacket.LayerType { return LayerTypeDNS }
  256. // decodeDNS decodes the byte slice into a DNS type. It also
  257. // setups the application Layer in PacketBuilder.
  258. func decodeDNS(data []byte, p gopacket.PacketBuilder) error {
  259. d := &DNS{}
  260. err := d.DecodeFromBytes(data, p)
  261. if err != nil {
  262. return err
  263. }
  264. p.AddLayer(d)
  265. p.SetApplicationLayer(d)
  266. return nil
  267. }
  268. // DecodeFromBytes decodes the slice into the DNS struct.
  269. func (d *DNS) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
  270. d.buffer = d.buffer[:0]
  271. if len(data) < 12 {
  272. df.SetTruncated()
  273. return errDNSPacketTooShort
  274. }
  275. // since there are no further layers, the baselayer's content is
  276. // pointing to this layer
  277. d.BaseLayer = BaseLayer{Contents: data[:len(data)]}
  278. d.ID = binary.BigEndian.Uint16(data[:2])
  279. d.QR = data[2]&0x80 != 0
  280. d.OpCode = DNSOpCode(data[2]>>3) & 0x0F
  281. d.AA = data[2]&0x04 != 0
  282. d.TC = data[2]&0x02 != 0
  283. d.RD = data[2]&0x01 != 0
  284. d.RA = data[3]&0x80 != 0
  285. d.Z = uint8(data[3]>>4) & 0x7
  286. d.ResponseCode = DNSResponseCode(data[3] & 0xF)
  287. d.QDCount = binary.BigEndian.Uint16(data[4:6])
  288. d.ANCount = binary.BigEndian.Uint16(data[6:8])
  289. d.NSCount = binary.BigEndian.Uint16(data[8:10])
  290. d.ARCount = binary.BigEndian.Uint16(data[10:12])
  291. d.Questions = d.Questions[:0]
  292. d.Answers = d.Answers[:0]
  293. d.Authorities = d.Authorities[:0]
  294. d.Additionals = d.Additionals[:0]
  295. offset := 12
  296. var err error
  297. for i := 0; i < int(d.QDCount); i++ {
  298. var q DNSQuestion
  299. if offset, err = q.decode(data, offset, df, &d.buffer); err != nil {
  300. return err
  301. }
  302. d.Questions = append(d.Questions, q)
  303. }
  304. // For some horrible reason, if we do the obvious thing in this loop:
  305. // var r DNSResourceRecord
  306. // if blah := r.decode(blah); err != nil {
  307. // return err
  308. // }
  309. // d.Foo = append(d.Foo, r)
  310. // the Go compiler thinks that 'r' escapes to the heap, causing a malloc for
  311. // every Answer, Authority, and Additional. To get around this, we do
  312. // something really silly: we append an empty resource record to our slice,
  313. // then use the last value in the slice to call decode. Since the value is
  314. // already in the slice, there's no WAY it can escape... on the other hand our
  315. // code is MUCH uglier :(
  316. for i := 0; i < int(d.ANCount); i++ {
  317. d.Answers = append(d.Answers, DNSResourceRecord{})
  318. if offset, err = d.Answers[i].decode(data, offset, df, &d.buffer); err != nil {
  319. d.Answers = d.Answers[:i] // strip off erroneous value
  320. return err
  321. }
  322. }
  323. for i := 0; i < int(d.NSCount); i++ {
  324. d.Authorities = append(d.Authorities, DNSResourceRecord{})
  325. if offset, err = d.Authorities[i].decode(data, offset, df, &d.buffer); err != nil {
  326. d.Authorities = d.Authorities[:i] // strip off erroneous value
  327. return err
  328. }
  329. }
  330. for i := 0; i < int(d.ARCount); i++ {
  331. d.Additionals = append(d.Additionals, DNSResourceRecord{})
  332. if offset, err = d.Additionals[i].decode(data, offset, df, &d.buffer); err != nil {
  333. d.Additionals = d.Additionals[:i] // strip off erroneous value
  334. return err
  335. }
  336. }
  337. if uint16(len(d.Questions)) != d.QDCount {
  338. return errDecodeQueryBadQDCount
  339. } else if uint16(len(d.Answers)) != d.ANCount {
  340. return errDecodeQueryBadANCount
  341. } else if uint16(len(d.Authorities)) != d.NSCount {
  342. return errDecodeQueryBadNSCount
  343. } else if uint16(len(d.Additionals)) != d.ARCount {
  344. return errDecodeQueryBadARCount
  345. }
  346. return nil
  347. }
  348. // CanDecode implements gopacket.DecodingLayer.
  349. func (d *DNS) CanDecode() gopacket.LayerClass {
  350. return LayerTypeDNS
  351. }
  352. // NextLayerType implements gopacket.DecodingLayer.
  353. func (d *DNS) NextLayerType() gopacket.LayerType {
  354. return gopacket.LayerTypePayload
  355. }
  356. // Payload returns nil.
  357. func (d *DNS) Payload() []byte {
  358. return nil
  359. }
  360. func b2i(b bool) int {
  361. if b {
  362. return 1
  363. }
  364. return 0
  365. }
  366. func recSize(rr *DNSResourceRecord) int {
  367. switch rr.Type {
  368. case DNSTypeA:
  369. return 4
  370. case DNSTypeAAAA:
  371. return 16
  372. case DNSTypeNS:
  373. return len(rr.NS) + 2
  374. case DNSTypeCNAME:
  375. return len(rr.CNAME) + 2
  376. case DNSTypePTR:
  377. return len(rr.PTR) + 2
  378. case DNSTypeSOA:
  379. return len(rr.SOA.MName) + 2 + len(rr.SOA.RName) + 2 + 20
  380. case DNSTypeMX:
  381. return 2 + len(rr.MX.Name) + 2
  382. case DNSTypeTXT:
  383. l := len(rr.TXTs)
  384. for _, txt := range rr.TXTs {
  385. l += len(txt)
  386. }
  387. return l
  388. case DNSTypeSRV:
  389. return 6 + len(rr.SRV.Name) + 2
  390. }
  391. return 0
  392. }
  393. func computeSize(recs []DNSResourceRecord) int {
  394. sz := 0
  395. for _, rr := range recs {
  396. sz += len(rr.Name) + 12
  397. sz += recSize(&rr)
  398. }
  399. return sz
  400. }
  401. // SerializeTo writes the serialized form of this layer into the
  402. // SerializationBuffer, implementing gopacket.SerializableLayer.
  403. func (d *DNS) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {
  404. dsz := 0
  405. for _, q := range d.Questions {
  406. dsz += len(q.Name) + 6
  407. }
  408. dsz += computeSize(d.Answers)
  409. dsz += computeSize(d.Authorities)
  410. dsz += computeSize(d.Additionals)
  411. bytes, err := b.PrependBytes(12 + dsz)
  412. if err != nil {
  413. return err
  414. }
  415. binary.BigEndian.PutUint16(bytes, d.ID)
  416. bytes[2] = byte((b2i(d.QR) << 7) | (int(d.OpCode) << 3) | (b2i(d.AA) << 2) | (b2i(d.TC) << 1) | b2i(d.RD))
  417. bytes[3] = byte((b2i(d.RA) << 7) | (int(d.Z) << 4) | int(d.ResponseCode))
  418. if opts.FixLengths {
  419. d.QDCount = uint16(len(d.Questions))
  420. d.ANCount = uint16(len(d.Answers))
  421. d.NSCount = uint16(len(d.Authorities))
  422. d.ARCount = uint16(len(d.Additionals))
  423. }
  424. binary.BigEndian.PutUint16(bytes[4:], d.QDCount)
  425. binary.BigEndian.PutUint16(bytes[6:], d.ANCount)
  426. binary.BigEndian.PutUint16(bytes[8:], d.NSCount)
  427. binary.BigEndian.PutUint16(bytes[10:], d.ARCount)
  428. off := 12
  429. for _, qd := range d.Questions {
  430. n := qd.encode(bytes, off)
  431. off += n
  432. }
  433. for i := range d.Answers {
  434. // done this way so we can modify DNSResourceRecord to fix
  435. // lengths if requested
  436. qa := &d.Answers[i]
  437. n, err := qa.encode(bytes, off, opts)
  438. if err != nil {
  439. return err
  440. }
  441. off += n
  442. }
  443. for i := range d.Authorities {
  444. qa := &d.Authorities[i]
  445. n, err := qa.encode(bytes, off, opts)
  446. if err != nil {
  447. return err
  448. }
  449. off += n
  450. }
  451. for i := range d.Additionals {
  452. qa := &d.Additionals[i]
  453. n, err := qa.encode(bytes, off, opts)
  454. if err != nil {
  455. return err
  456. }
  457. off += n
  458. }
  459. return nil
  460. }
  461. const maxRecursionLevel = 255
  462. func decodeName(data []byte, offset int, buffer *[]byte, level int) ([]byte, int, error) {
  463. if level > maxRecursionLevel {
  464. return nil, 0, errMaxRecursion
  465. } else if offset >= len(data) {
  466. return nil, 0, errDNSNameOffsetTooHigh
  467. } else if offset < 0 {
  468. return nil, 0, errDNSNameOffsetNegative
  469. }
  470. start := len(*buffer)
  471. index := offset
  472. if data[index] == 0x00 {
  473. return nil, index + 1, nil
  474. }
  475. loop:
  476. for data[index] != 0x00 {
  477. switch data[index] & 0xc0 {
  478. default:
  479. /* RFC 1035
  480. A domain name represented as a sequence of labels, where
  481. each label consists of a length octet followed by that
  482. number of octets. The domain name terminates with the
  483. zero length octet for the null label of the root. Note
  484. that this field may be an odd number of octets; no
  485. padding is used.
  486. */
  487. index2 := index + int(data[index]) + 1
  488. if index2-offset > 255 {
  489. return nil, 0, errDNSNameTooLong
  490. } else if index2 < index+1 || index2 > len(data) {
  491. return nil, 0, errDNSNameInvalidIndex
  492. }
  493. *buffer = append(*buffer, '.')
  494. *buffer = append(*buffer, data[index+1:index2]...)
  495. index = index2
  496. case 0xc0:
  497. /* RFC 1035
  498. The pointer takes the form of a two octet sequence.
  499. The first two bits are ones. This allows a pointer to
  500. be distinguished from a label, since the label must
  501. begin with two zero bits because labels are restricted
  502. to 63 octets or less. (The 10 and 01 combinations are
  503. reserved for future use.) The OFFSET field specifies
  504. an offset from the start of the message (i.e., the
  505. first octet of the ID field in the domain header). A
  506. zero offset specifies the first byte of the ID field,
  507. etc.
  508. The compression scheme allows a domain name in a message to be
  509. represented as either:
  510. - a sequence of labels ending in a zero octet
  511. - a pointer
  512. - a sequence of labels ending with a pointer
  513. */
  514. if index+2 > len(data) {
  515. return nil, 0, errDNSPointerOffsetTooHigh
  516. }
  517. offsetp := int(binary.BigEndian.Uint16(data[index:index+2]) & 0x3fff)
  518. if offsetp > len(data) {
  519. return nil, 0, errDNSPointerOffsetTooHigh
  520. }
  521. // This looks a little tricky, but actually isn't. Because of how
  522. // decodeName is written, calling it appends the decoded name to the
  523. // current buffer. We already have the start of the buffer, then, so
  524. // once this call is done buffer[start:] will contain our full name.
  525. _, _, err := decodeName(data, offsetp, buffer, level+1)
  526. if err != nil {
  527. return nil, 0, err
  528. }
  529. index++ // pointer is two bytes, so add an extra byte here.
  530. break loop
  531. /* EDNS, or other DNS option ? */
  532. case 0x40: // RFC 2673
  533. return nil, 0, fmt.Errorf("qname '0x40' - RFC 2673 unsupported yet (data=%x index=%d)",
  534. data[index], index)
  535. case 0x80:
  536. return nil, 0, fmt.Errorf("qname '0x80' unsupported yet (data=%x index=%d)",
  537. data[index], index)
  538. }
  539. if index >= len(data) {
  540. return nil, 0, errDNSIndexOutOfRange
  541. }
  542. }
  543. if len(*buffer) <= start {
  544. return nil, 0, errDNSNameHasNoData
  545. }
  546. return (*buffer)[start+1:], index + 1, nil
  547. }
  548. // DNSQuestion wraps a single request (question) within a DNS query.
  549. type DNSQuestion struct {
  550. Name []byte
  551. Type DNSType
  552. Class DNSClass
  553. }
  554. func (q *DNSQuestion) decode(data []byte, offset int, df gopacket.DecodeFeedback, buffer *[]byte) (int, error) {
  555. name, endq, err := decodeName(data, offset, buffer, 1)
  556. if err != nil {
  557. return 0, err
  558. }
  559. q.Name = name
  560. q.Type = DNSType(binary.BigEndian.Uint16(data[endq : endq+2]))
  561. q.Class = DNSClass(binary.BigEndian.Uint16(data[endq+2 : endq+4]))
  562. return endq + 4, nil
  563. }
  564. func (q *DNSQuestion) encode(data []byte, offset int) int {
  565. noff := encodeName(q.Name, data, offset)
  566. binary.BigEndian.PutUint16(data[noff:], uint16(q.Type))
  567. binary.BigEndian.PutUint16(data[noff+2:], uint16(q.Class))
  568. return len(q.Name) + 6
  569. }
  570. // DNSResourceRecord
  571. // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
  572. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  573. // | |
  574. // / /
  575. // / NAME /
  576. // | |
  577. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  578. // | TYPE |
  579. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  580. // | CLASS |
  581. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  582. // | TTL |
  583. // | |
  584. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  585. // | RDLENGTH |
  586. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
  587. // / RDATA /
  588. // / /
  589. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  590. // DNSResourceRecord wraps the data from a single DNS resource within a
  591. // response.
  592. type DNSResourceRecord struct {
  593. // Header
  594. Name []byte
  595. Type DNSType
  596. Class DNSClass
  597. TTL uint32
  598. // RDATA Raw Values
  599. DataLength uint16
  600. Data []byte
  601. // RDATA Decoded Values
  602. IP net.IP
  603. NS, CNAME, PTR []byte
  604. TXTs [][]byte
  605. SOA DNSSOA
  606. SRV DNSSRV
  607. MX DNSMX
  608. // Undecoded TXT for backward compatibility
  609. TXT []byte
  610. }
  611. // decode decodes the resource record, returning the total length of the record.
  612. func (rr *DNSResourceRecord) decode(data []byte, offset int, df gopacket.DecodeFeedback, buffer *[]byte) (int, error) {
  613. name, endq, err := decodeName(data, offset, buffer, 1)
  614. if err != nil {
  615. return 0, err
  616. }
  617. rr.Name = name
  618. rr.Type = DNSType(binary.BigEndian.Uint16(data[endq : endq+2]))
  619. rr.Class = DNSClass(binary.BigEndian.Uint16(data[endq+2 : endq+4]))
  620. rr.TTL = binary.BigEndian.Uint32(data[endq+4 : endq+8])
  621. rr.DataLength = binary.BigEndian.Uint16(data[endq+8 : endq+10])
  622. end := endq + 10 + int(rr.DataLength)
  623. if end > len(data) {
  624. return 0, errDecodeRecordLength
  625. }
  626. rr.Data = data[endq+10 : end]
  627. if err = rr.decodeRData(data, endq+10, buffer); err != nil {
  628. return 0, err
  629. }
  630. return endq + 10 + int(rr.DataLength), nil
  631. }
  632. func encodeName(name []byte, data []byte, offset int) int {
  633. l := 0
  634. for i := range name {
  635. if name[i] == '.' {
  636. data[offset+i-l] = byte(l)
  637. l = 0
  638. } else {
  639. // skip one to write the length
  640. data[offset+i+1] = name[i]
  641. l++
  642. }
  643. }
  644. // length for final portion
  645. data[offset+len(name)-l] = byte(l)
  646. data[offset+len(name)+1] = 0x00 // terminal
  647. return offset + len(name) + 2
  648. }
  649. func (rr *DNSResourceRecord) encode(data []byte, offset int, opts gopacket.SerializeOptions) (int, error) {
  650. noff := encodeName(rr.Name, data, offset)
  651. binary.BigEndian.PutUint16(data[noff:], uint16(rr.Type))
  652. binary.BigEndian.PutUint16(data[noff+2:], uint16(rr.Class))
  653. binary.BigEndian.PutUint32(data[noff+4:], uint32(rr.TTL))
  654. switch rr.Type {
  655. case DNSTypeA:
  656. copy(data[noff+10:], rr.IP.To4())
  657. case DNSTypeAAAA:
  658. copy(data[noff+10:], rr.IP)
  659. case DNSTypeNS:
  660. encodeName(rr.NS, data, noff+10)
  661. case DNSTypeCNAME:
  662. encodeName(rr.CNAME, data, noff+10)
  663. case DNSTypePTR:
  664. encodeName(rr.PTR, data, noff+10)
  665. case DNSTypeSOA:
  666. noff2 := encodeName(rr.SOA.MName, data, noff+10)
  667. noff2 = encodeName(rr.SOA.RName, data, noff2)
  668. binary.BigEndian.PutUint32(data[noff2:], rr.SOA.Serial)
  669. binary.BigEndian.PutUint32(data[noff2+4:], rr.SOA.Refresh)
  670. binary.BigEndian.PutUint32(data[noff2+8:], rr.SOA.Retry)
  671. binary.BigEndian.PutUint32(data[noff2+12:], rr.SOA.Expire)
  672. binary.BigEndian.PutUint32(data[noff2+16:], rr.SOA.Minimum)
  673. case DNSTypeMX:
  674. binary.BigEndian.PutUint16(data[noff+10:], rr.MX.Preference)
  675. encodeName(rr.MX.Name, data, noff+12)
  676. case DNSTypeTXT:
  677. noff2 := noff + 10
  678. for _, txt := range rr.TXTs {
  679. data[noff2] = byte(len(txt))
  680. copy(data[noff2+1:], txt)
  681. noff2 += 1 + len(txt)
  682. }
  683. case DNSTypeSRV:
  684. binary.BigEndian.PutUint16(data[noff+10:], rr.SRV.Priority)
  685. binary.BigEndian.PutUint16(data[noff+12:], rr.SRV.Weight)
  686. binary.BigEndian.PutUint16(data[noff+14:], rr.SRV.Port)
  687. encodeName(rr.SRV.Name, data, noff+16)
  688. default:
  689. return 0, fmt.Errorf("serializing resource record of type %v not supported", rr.Type)
  690. }
  691. // DataLength
  692. dSz := recSize(rr)
  693. binary.BigEndian.PutUint16(data[noff+8:], uint16(dSz))
  694. if opts.FixLengths {
  695. rr.DataLength = uint16(dSz)
  696. }
  697. return len(rr.Name) + 1 + 11 + dSz, nil
  698. }
  699. func (rr *DNSResourceRecord) String() string {
  700. if rr.Class == DNSClassIN {
  701. switch rr.Type {
  702. case DNSTypeA, DNSTypeAAAA:
  703. return rr.IP.String()
  704. case DNSTypeNS:
  705. return "NS " + string(rr.NS)
  706. case DNSTypeCNAME:
  707. return "CNAME " + string(rr.CNAME)
  708. case DNSTypePTR:
  709. return "PTR " + string(rr.PTR)
  710. case DNSTypeTXT:
  711. return "TXT " + string(rr.TXT)
  712. }
  713. }
  714. return fmt.Sprintf("<%v, %v>", rr.Class, rr.Type)
  715. }
  716. func decodeCharacterStrings(data []byte) ([][]byte, error) {
  717. strings := make([][]byte, 0, 1)
  718. end := len(data)
  719. for index, index2 := 0, 0; index != end; index = index2 {
  720. index2 = index + 1 + int(data[index]) // index increases by 1..256 and does not overflow
  721. if index2 > end {
  722. return nil, errCharStringMissData
  723. }
  724. strings = append(strings, data[index+1:index2])
  725. }
  726. return strings, nil
  727. }
  728. func (rr *DNSResourceRecord) decodeRData(data []byte, offset int, buffer *[]byte) error {
  729. switch rr.Type {
  730. case DNSTypeA:
  731. rr.IP = rr.Data
  732. case DNSTypeAAAA:
  733. rr.IP = rr.Data
  734. case DNSTypeTXT, DNSTypeHINFO:
  735. rr.TXT = rr.Data
  736. txts, err := decodeCharacterStrings(rr.Data)
  737. if err != nil {
  738. return err
  739. }
  740. rr.TXTs = txts
  741. case DNSTypeNS:
  742. name, _, err := decodeName(data, offset, buffer, 1)
  743. if err != nil {
  744. return err
  745. }
  746. rr.NS = name
  747. case DNSTypeCNAME:
  748. name, _, err := decodeName(data, offset, buffer, 1)
  749. if err != nil {
  750. return err
  751. }
  752. rr.CNAME = name
  753. case DNSTypePTR:
  754. name, _, err := decodeName(data, offset, buffer, 1)
  755. if err != nil {
  756. return err
  757. }
  758. rr.PTR = name
  759. case DNSTypeSOA:
  760. name, endq, err := decodeName(data, offset, buffer, 1)
  761. if err != nil {
  762. return err
  763. }
  764. rr.SOA.MName = name
  765. name, endq, err = decodeName(data, endq, buffer, 1)
  766. if err != nil {
  767. return err
  768. }
  769. rr.SOA.RName = name
  770. rr.SOA.Serial = binary.BigEndian.Uint32(data[endq : endq+4])
  771. rr.SOA.Refresh = binary.BigEndian.Uint32(data[endq+4 : endq+8])
  772. rr.SOA.Retry = binary.BigEndian.Uint32(data[endq+8 : endq+12])
  773. rr.SOA.Expire = binary.BigEndian.Uint32(data[endq+12 : endq+16])
  774. rr.SOA.Minimum = binary.BigEndian.Uint32(data[endq+16 : endq+20])
  775. case DNSTypeMX:
  776. rr.MX.Preference = binary.BigEndian.Uint16(data[offset : offset+2])
  777. name, _, err := decodeName(data, offset+2, buffer, 1)
  778. if err != nil {
  779. return err
  780. }
  781. rr.MX.Name = name
  782. case DNSTypeSRV:
  783. rr.SRV.Priority = binary.BigEndian.Uint16(data[offset : offset+2])
  784. rr.SRV.Weight = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  785. rr.SRV.Port = binary.BigEndian.Uint16(data[offset+4 : offset+6])
  786. name, _, err := decodeName(data, offset+6, buffer, 1)
  787. if err != nil {
  788. return err
  789. }
  790. rr.SRV.Name = name
  791. }
  792. return nil
  793. }
  794. // DNSSOA is a Start of Authority record. Each domain requires a SOA record at
  795. // the cutover where a domain is delegated from its parent.
  796. type DNSSOA struct {
  797. MName, RName []byte
  798. Serial, Refresh, Retry, Expire, Minimum uint32
  799. }
  800. // DNSSRV is a Service record, defining a location (hostname/port) of a
  801. // server/service.
  802. type DNSSRV struct {
  803. Priority, Weight, Port uint16
  804. Name []byte
  805. }
  806. // DNSMX is a mail exchange record, defining a mail server for a recipient's
  807. // domain.
  808. type DNSMX struct {
  809. Preference uint16
  810. Name []byte
  811. }
  812. var (
  813. errMaxRecursion = errors.New("max DNS recursion level hit")
  814. errDNSNameOffsetTooHigh = errors.New("dns name offset too high")
  815. errDNSNameOffsetNegative = errors.New("dns name offset is negative")
  816. errDNSPacketTooShort = errors.New("DNS packet too short")
  817. errDNSNameTooLong = errors.New("dns name is too long")
  818. errDNSNameInvalidIndex = errors.New("dns name uncomputable: invalid index")
  819. errDNSPointerOffsetTooHigh = errors.New("dns offset pointer too high")
  820. errDNSIndexOutOfRange = errors.New("dns index walked out of range")
  821. errDNSNameHasNoData = errors.New("no dns data found for name")
  822. errCharStringMissData = errors.New("Insufficient data for a <character-string>")
  823. errDecodeRecordLength = errors.New("resource record length exceeds data")
  824. errDecodeQueryBadQDCount = errors.New("Invalid query decoding, not the right number of questions")
  825. errDecodeQueryBadANCount = errors.New("Invalid query decoding, not the right number of answers")
  826. errDecodeQueryBadNSCount = errors.New("Invalid query decoding, not the right number of authorities")
  827. errDecodeQueryBadARCount = errors.New("Invalid query decoding, not the right number of additionals info")
  828. )