dns.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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 errors.New("DNS packet too short")
  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 errors.New("Invalid query decoding, not the right number of questions")
  339. } else if uint16(len(d.Answers)) != d.ANCount {
  340. return errors.New("Invalid query decoding, not the right number of answers")
  341. } else if uint16(len(d.Authorities)) != d.NSCount {
  342. return errors.New("Invalid query decoding, not the right number of authorities")
  343. } else if uint16(len(d.Additionals)) != d.ARCount {
  344. return errors.New("Invalid query decoding, not the right number of additionals info")
  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. var errMaxRecursion = errors.New("max DNS recursion level hit")
  462. const maxRecursionLevel = 255
  463. func decodeName(data []byte, offset int, buffer *[]byte, level int) ([]byte, int, error) {
  464. if level > maxRecursionLevel {
  465. return nil, 0, errMaxRecursion
  466. } else if offset >= len(data) {
  467. return nil, 0, errors.New("dns name offset too high")
  468. } else if offset < 0 {
  469. return nil, 0, errors.New("dns name offset is negative")
  470. }
  471. start := len(*buffer)
  472. index := offset
  473. if data[index] == 0x00 {
  474. return nil, index + 1, nil
  475. }
  476. loop:
  477. for data[index] != 0x00 {
  478. switch data[index] & 0xc0 {
  479. default:
  480. /* RFC 1035
  481. A domain name represented as a sequence of labels, where
  482. each label consists of a length octet followed by that
  483. number of octets. The domain name terminates with the
  484. zero length octet for the null label of the root. Note
  485. that this field may be an odd number of octets; no
  486. padding is used.
  487. */
  488. index2 := index + int(data[index]) + 1
  489. if index2-offset > 255 {
  490. return nil, 0, errors.New("dns name is too long")
  491. } else if index2 < index+1 || index2 > len(data) {
  492. return nil, 0, errors.New("dns name uncomputable: invalid index")
  493. }
  494. *buffer = append(*buffer, '.')
  495. *buffer = append(*buffer, data[index+1:index2]...)
  496. index = index2
  497. case 0xc0:
  498. /* RFC 1035
  499. The pointer takes the form of a two octet sequence.
  500. The first two bits are ones. This allows a pointer to
  501. be distinguished from a label, since the label must
  502. begin with two zero bits because labels are restricted
  503. to 63 octets or less. (The 10 and 01 combinations are
  504. reserved for future use.) The OFFSET field specifies
  505. an offset from the start of the message (i.e., the
  506. first octet of the ID field in the domain header). A
  507. zero offset specifies the first byte of the ID field,
  508. etc.
  509. The compression scheme allows a domain name in a message to be
  510. represented as either:
  511. - a sequence of labels ending in a zero octet
  512. - a pointer
  513. - a sequence of labels ending with a pointer
  514. */
  515. if index+2 > len(data) {
  516. return nil, 0, errors.New("dns offset pointer too high")
  517. }
  518. offsetp := int(binary.BigEndian.Uint16(data[index:index+2]) & 0x3fff)
  519. if offsetp > len(data) {
  520. return nil, 0, errors.New("dns offset pointer too high")
  521. }
  522. // This looks a little tricky, but actually isn't. Because of how
  523. // decodeName is written, calling it appends the decoded name to the
  524. // current buffer. We already have the start of the buffer, then, so
  525. // once this call is done buffer[start:] will contain our full name.
  526. _, _, err := decodeName(data, offsetp, buffer, level+1)
  527. if err != nil {
  528. return nil, 0, err
  529. }
  530. index++ // pointer is two bytes, so add an extra byte here.
  531. break loop
  532. /* EDNS, or other DNS option ? */
  533. case 0x40: // RFC 2673
  534. return nil, 0, fmt.Errorf("qname '0x40' - RFC 2673 unsupported yet (data=%x index=%d)",
  535. data[index], index)
  536. case 0x80:
  537. return nil, 0, fmt.Errorf("qname '0x80' unsupported yet (data=%x index=%d)",
  538. data[index], index)
  539. }
  540. if index >= len(data) {
  541. return nil, 0, errors.New("dns index walked out of range")
  542. }
  543. }
  544. if len(*buffer) <= start {
  545. return nil, 0, errors.New("no dns data found for name")
  546. }
  547. return (*buffer)[start+1:], index + 1, nil
  548. }
  549. // DNSQuestion wraps a single request (question) within a DNS query.
  550. type DNSQuestion struct {
  551. Name []byte
  552. Type DNSType
  553. Class DNSClass
  554. }
  555. func (q *DNSQuestion) decode(data []byte, offset int, df gopacket.DecodeFeedback, buffer *[]byte) (int, error) {
  556. name, endq, err := decodeName(data, offset, buffer, 1)
  557. if err != nil {
  558. return 0, err
  559. }
  560. q.Name = name
  561. q.Type = DNSType(binary.BigEndian.Uint16(data[endq : endq+2]))
  562. q.Class = DNSClass(binary.BigEndian.Uint16(data[endq+2 : endq+4]))
  563. return endq + 4, nil
  564. }
  565. func (q *DNSQuestion) encode(data []byte, offset int) int {
  566. noff := encodeName(q.Name, data, offset)
  567. binary.BigEndian.PutUint16(data[noff:], uint16(q.Type))
  568. binary.BigEndian.PutUint16(data[noff+2:], uint16(q.Class))
  569. return len(q.Name) + 6
  570. }
  571. // DNSResourceRecord
  572. // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
  573. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  574. // | |
  575. // / /
  576. // / NAME /
  577. // | |
  578. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  579. // | TYPE |
  580. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  581. // | CLASS |
  582. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  583. // | TTL |
  584. // | |
  585. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  586. // | RDLENGTH |
  587. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
  588. // / RDATA /
  589. // / /
  590. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  591. // DNSResourceRecord wraps the data from a single DNS resource within a
  592. // response.
  593. type DNSResourceRecord struct {
  594. // Header
  595. Name []byte
  596. Type DNSType
  597. Class DNSClass
  598. TTL uint32
  599. // RDATA Raw Values
  600. DataLength uint16
  601. Data []byte
  602. // RDATA Decoded Values
  603. IP net.IP
  604. NS, CNAME, PTR []byte
  605. TXTs [][]byte
  606. SOA DNSSOA
  607. SRV DNSSRV
  608. MX DNSMX
  609. // Undecoded TXT for backward compatibility
  610. TXT []byte
  611. }
  612. // decode decodes the resource record, returning the total length of the record.
  613. func (rr *DNSResourceRecord) decode(data []byte, offset int, df gopacket.DecodeFeedback, buffer *[]byte) (int, error) {
  614. name, endq, err := decodeName(data, offset, buffer, 1)
  615. if err != nil {
  616. return 0, err
  617. }
  618. rr.Name = name
  619. rr.Type = DNSType(binary.BigEndian.Uint16(data[endq : endq+2]))
  620. rr.Class = DNSClass(binary.BigEndian.Uint16(data[endq+2 : endq+4]))
  621. rr.TTL = binary.BigEndian.Uint32(data[endq+4 : endq+8])
  622. rr.DataLength = binary.BigEndian.Uint16(data[endq+8 : endq+10])
  623. end := endq + 10 + int(rr.DataLength)
  624. if end > len(data) {
  625. return 0, fmt.Errorf("resource record length exceeds data")
  626. }
  627. rr.Data = data[endq+10 : end]
  628. if err = rr.decodeRData(data, endq+10, buffer); err != nil {
  629. return 0, err
  630. }
  631. return endq + 10 + int(rr.DataLength), nil
  632. }
  633. func encodeName(name []byte, data []byte, offset int) int {
  634. l := 0
  635. for i := range name {
  636. if name[i] == '.' {
  637. data[offset+i-l] = byte(l)
  638. l = 0
  639. } else {
  640. // skip one to write the length
  641. data[offset+i+1] = name[i]
  642. l++
  643. }
  644. }
  645. // length for final portion
  646. data[offset+len(name)-l] = byte(l)
  647. data[offset+len(name)+1] = 0x00 // terminal
  648. return offset + len(name) + 2
  649. }
  650. func (rr *DNSResourceRecord) encode(data []byte, offset int, opts gopacket.SerializeOptions) (int, error) {
  651. noff := encodeName(rr.Name, data, offset)
  652. binary.BigEndian.PutUint16(data[noff:], uint16(rr.Type))
  653. binary.BigEndian.PutUint16(data[noff+2:], uint16(rr.Class))
  654. binary.BigEndian.PutUint32(data[noff+4:], uint32(rr.TTL))
  655. switch rr.Type {
  656. case DNSTypeA:
  657. copy(data[noff+10:], rr.IP.To4())
  658. case DNSTypeAAAA:
  659. copy(data[noff+10:], rr.IP)
  660. case DNSTypeNS:
  661. encodeName(rr.NS, data, noff+10)
  662. case DNSTypeCNAME:
  663. encodeName(rr.CNAME, data, noff+10)
  664. case DNSTypePTR:
  665. encodeName(rr.PTR, data, noff+10)
  666. case DNSTypeSOA:
  667. noff2 := encodeName(rr.SOA.MName, data, noff+10)
  668. noff2 = encodeName(rr.SOA.RName, data, noff2)
  669. binary.BigEndian.PutUint32(data[noff2:], rr.SOA.Serial)
  670. binary.BigEndian.PutUint32(data[noff2+4:], rr.SOA.Refresh)
  671. binary.BigEndian.PutUint32(data[noff2+8:], rr.SOA.Retry)
  672. binary.BigEndian.PutUint32(data[noff2+12:], rr.SOA.Expire)
  673. binary.BigEndian.PutUint32(data[noff2+16:], rr.SOA.Minimum)
  674. case DNSTypeMX:
  675. binary.BigEndian.PutUint16(data[noff+10:], rr.MX.Preference)
  676. encodeName(rr.MX.Name, data, noff+12)
  677. case DNSTypeTXT:
  678. noff2 := noff + 10
  679. for _, txt := range rr.TXTs {
  680. data[noff2] = byte(len(txt))
  681. copy(data[noff2+1:], txt)
  682. noff2 += 1 + len(txt)
  683. }
  684. case DNSTypeSRV:
  685. binary.BigEndian.PutUint16(data[noff+10:], rr.SRV.Priority)
  686. binary.BigEndian.PutUint16(data[noff+12:], rr.SRV.Weight)
  687. binary.BigEndian.PutUint16(data[noff+14:], rr.SRV.Port)
  688. encodeName(rr.SRV.Name, data, noff+16)
  689. default:
  690. return 0, fmt.Errorf("serializing resource record of type %v not supported", rr.Type)
  691. }
  692. // DataLength
  693. dSz := recSize(rr)
  694. binary.BigEndian.PutUint16(data[noff+8:], uint16(dSz))
  695. if opts.FixLengths {
  696. rr.DataLength = uint16(dSz)
  697. }
  698. return len(rr.Name) + 1 + 11 + dSz, nil
  699. }
  700. func (rr *DNSResourceRecord) String() string {
  701. if rr.Class == DNSClassIN {
  702. switch rr.Type {
  703. case DNSTypeA, DNSTypeAAAA:
  704. return rr.IP.String()
  705. case DNSTypeNS:
  706. return "NS " + string(rr.NS)
  707. case DNSTypeCNAME:
  708. return "CNAME " + string(rr.CNAME)
  709. case DNSTypePTR:
  710. return "PTR " + string(rr.PTR)
  711. case DNSTypeTXT:
  712. return "TXT " + string(rr.TXT)
  713. }
  714. }
  715. return fmt.Sprintf("<%v, %v>", rr.Class, rr.Type)
  716. }
  717. func decodeCharacterStrings(data []byte) ([][]byte, error) {
  718. strings := make([][]byte, 0, 1)
  719. end := len(data)
  720. for index, index2 := 0, 0; index != end; index = index2 {
  721. index2 = index + 1 + int(data[index]) // index increases by 1..256 and does not overflow
  722. if index2 > end {
  723. return nil, errors.New("Insufficient data for a <character-string>")
  724. }
  725. strings = append(strings, data[index+1:index2])
  726. }
  727. return strings, nil
  728. }
  729. func (rr *DNSResourceRecord) decodeRData(data []byte, offset int, buffer *[]byte) error {
  730. switch rr.Type {
  731. case DNSTypeA:
  732. rr.IP = rr.Data
  733. case DNSTypeAAAA:
  734. rr.IP = rr.Data
  735. case DNSTypeTXT, DNSTypeHINFO:
  736. rr.TXT = rr.Data
  737. txts, err := decodeCharacterStrings(rr.Data)
  738. if err != nil {
  739. return err
  740. }
  741. rr.TXTs = txts
  742. case DNSTypeNS:
  743. name, _, err := decodeName(data, offset, buffer, 1)
  744. if err != nil {
  745. return err
  746. }
  747. rr.NS = name
  748. case DNSTypeCNAME:
  749. name, _, err := decodeName(data, offset, buffer, 1)
  750. if err != nil {
  751. return err
  752. }
  753. rr.CNAME = name
  754. case DNSTypePTR:
  755. name, _, err := decodeName(data, offset, buffer, 1)
  756. if err != nil {
  757. return err
  758. }
  759. rr.PTR = name
  760. case DNSTypeSOA:
  761. name, endq, err := decodeName(data, offset, buffer, 1)
  762. if err != nil {
  763. return err
  764. }
  765. rr.SOA.MName = name
  766. name, endq, err = decodeName(data, endq, buffer, 1)
  767. if err != nil {
  768. return err
  769. }
  770. rr.SOA.RName = name
  771. rr.SOA.Serial = binary.BigEndian.Uint32(data[endq : endq+4])
  772. rr.SOA.Refresh = binary.BigEndian.Uint32(data[endq+4 : endq+8])
  773. rr.SOA.Retry = binary.BigEndian.Uint32(data[endq+8 : endq+12])
  774. rr.SOA.Expire = binary.BigEndian.Uint32(data[endq+12 : endq+16])
  775. rr.SOA.Minimum = binary.BigEndian.Uint32(data[endq+16 : endq+20])
  776. case DNSTypeMX:
  777. rr.MX.Preference = binary.BigEndian.Uint16(data[offset : offset+2])
  778. name, _, err := decodeName(data, offset+2, buffer, 1)
  779. if err != nil {
  780. return err
  781. }
  782. rr.MX.Name = name
  783. case DNSTypeSRV:
  784. rr.SRV.Priority = binary.BigEndian.Uint16(data[offset : offset+2])
  785. rr.SRV.Weight = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  786. rr.SRV.Port = binary.BigEndian.Uint16(data[offset+4 : offset+6])
  787. name, _, err := decodeName(data, offset+6, buffer, 1)
  788. if err != nil {
  789. return err
  790. }
  791. rr.SRV.Name = name
  792. }
  793. return nil
  794. }
  795. // DNSSOA is a Start of Authority record. Each domain requires a SOA record at
  796. // the cutover where a domain is delegated from its parent.
  797. type DNSSOA struct {
  798. MName, RName []byte
  799. Serial, Refresh, Retry, Expire, Minimum uint32
  800. }
  801. // DNSSRV is a Service record, defining a location (hostname/port) of a
  802. // server/service.
  803. type DNSSRV struct {
  804. Priority, Weight, Port uint16
  805. Name []byte
  806. }
  807. // DNSMX is a mail exchange record, defining a mail server for a recipient's
  808. // domain.
  809. type DNSMX struct {
  810. Preference uint16
  811. Name []byte
  812. }