dns.go 31 KB

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