dns.go 32 KB

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