msg.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  1. // DNS packet assembly, see RFC 1035. Converting from - Unpack() -
  2. // and to - Pack() - wire format.
  3. // All the packers and unpackers take a (msg []byte, off int)
  4. // and return (off1 int, ok bool). If they return ok==false, they
  5. // also return off1==len(msg), so that the next unpacker will
  6. // also fail. This lets us avoid checks of ok until the end of a
  7. // packing sequence.
  8. package dns
  9. //go:generate go run msg_generate.go
  10. import (
  11. "crypto/rand"
  12. "encoding/binary"
  13. "fmt"
  14. "math/big"
  15. "strconv"
  16. "strings"
  17. )
  18. const (
  19. maxCompressionOffset = 2 << 13 // We have 14 bits for the compression pointer
  20. maxDomainNameWireOctets = 255 // See RFC 1035 section 2.3.4
  21. // This is the maximum number of compression pointers that should occur in a
  22. // semantically valid message. Each label in a domain name must be at least one
  23. // octet and is separated by a period. The root label won't be represented by a
  24. // compression pointer to a compression pointer, hence the -2 to exclude the
  25. // smallest valid root label.
  26. //
  27. // It is possible to construct a valid message that has more compression pointers
  28. // than this, and still doesn't loop, by pointing to a previous pointer. This is
  29. // not something a well written implementation should ever do, so we leave them
  30. // to trip the maximum compression pointer check.
  31. maxCompressionPointers = (maxDomainNameWireOctets+1)/2 - 2
  32. // This is the maximum length of a domain name in presentation format. The
  33. // maximum wire length of a domain name is 255 octets (see above), with the
  34. // maximum label length being 63. The wire format requires one extra byte over
  35. // the presentation format, reducing the number of octets by 1. Each label in
  36. // the name will be separated by a single period, with each octet in the label
  37. // expanding to at most 4 bytes (\DDD). If all other labels are of the maximum
  38. // length, then the final label can only be 61 octets long to not exceed the
  39. // maximum allowed wire length.
  40. maxDomainNamePresentationLength = 61*4 + 1 + 63*4 + 1 + 63*4 + 1 + 63*4 + 1
  41. )
  42. // Errors defined in this package.
  43. var (
  44. ErrAlg error = &Error{err: "bad algorithm"} // ErrAlg indicates an error with the (DNSSEC) algorithm.
  45. ErrAuth error = &Error{err: "bad authentication"} // ErrAuth indicates an error in the TSIG authentication.
  46. ErrBuf error = &Error{err: "buffer size too small"} // ErrBuf indicates that the buffer used is too small for the message.
  47. ErrConnEmpty error = &Error{err: "conn has no connection"} // ErrConnEmpty indicates a connection is being used before it is initialized.
  48. ErrExtendedRcode error = &Error{err: "bad extended rcode"} // ErrExtendedRcode ...
  49. ErrFqdn error = &Error{err: "domain must be fully qualified"} // ErrFqdn indicates that a domain name does not have a closing dot.
  50. ErrId error = &Error{err: "id mismatch"} // ErrId indicates there is a mismatch with the message's ID.
  51. ErrKeyAlg error = &Error{err: "bad key algorithm"} // ErrKeyAlg indicates that the algorithm in the key is not valid.
  52. ErrKey error = &Error{err: "bad key"}
  53. ErrKeySize error = &Error{err: "bad key size"}
  54. ErrLongDomain error = &Error{err: fmt.Sprintf("domain name exceeded %d wire-format octets", maxDomainNameWireOctets)}
  55. ErrNoSig error = &Error{err: "no signature found"}
  56. ErrPrivKey error = &Error{err: "bad private key"}
  57. ErrRcode error = &Error{err: "bad rcode"}
  58. ErrRdata error = &Error{err: "bad rdata"}
  59. ErrRRset error = &Error{err: "bad rrset"}
  60. ErrSecret error = &Error{err: "no secrets defined"}
  61. ErrShortRead error = &Error{err: "short read"}
  62. ErrSig error = &Error{err: "bad signature"} // ErrSig indicates that a signature can not be cryptographically validated.
  63. ErrSoa error = &Error{err: "no SOA"} // ErrSOA indicates that no SOA RR was seen when doing zone transfers.
  64. ErrTime error = &Error{err: "bad time"} // ErrTime indicates a timing error in TSIG authentication.
  65. )
  66. // Id by default returns a 16-bit random number to be used as a message id. The
  67. // number is drawn from a cryptographically secure random number generator.
  68. // This being a variable the function can be reassigned to a custom function.
  69. // For instance, to make it return a static value for testing:
  70. //
  71. // dns.Id = func() uint16 { return 3 }
  72. var Id = id
  73. // id returns a 16 bits random number to be used as a
  74. // message id. The random provided should be good enough.
  75. func id() uint16 {
  76. var output uint16
  77. err := binary.Read(rand.Reader, binary.BigEndian, &output)
  78. if err != nil {
  79. panic("dns: reading random id failed: " + err.Error())
  80. }
  81. return output
  82. }
  83. // MsgHdr is a a manually-unpacked version of (id, bits).
  84. type MsgHdr struct {
  85. Id uint16
  86. Response bool
  87. Opcode int
  88. Authoritative bool
  89. Truncated bool
  90. RecursionDesired bool
  91. RecursionAvailable bool
  92. Zero bool
  93. AuthenticatedData bool
  94. CheckingDisabled bool
  95. Rcode int
  96. }
  97. // Msg contains the layout of a DNS message.
  98. type Msg struct {
  99. MsgHdr
  100. Compress bool `json:"-"` // If true, the message will be compressed when converted to wire format.
  101. Question []Question // Holds the RR(s) of the question section.
  102. Answer []RR // Holds the RR(s) of the answer section.
  103. Ns []RR // Holds the RR(s) of the authority section.
  104. Extra []RR // Holds the RR(s) of the additional section.
  105. }
  106. // ClassToString is a maps Classes to strings for each CLASS wire type.
  107. var ClassToString = map[uint16]string{
  108. ClassINET: "IN",
  109. ClassCSNET: "CS",
  110. ClassCHAOS: "CH",
  111. ClassHESIOD: "HS",
  112. ClassNONE: "NONE",
  113. ClassANY: "ANY",
  114. }
  115. // OpcodeToString maps Opcodes to strings.
  116. var OpcodeToString = map[int]string{
  117. OpcodeQuery: "QUERY",
  118. OpcodeIQuery: "IQUERY",
  119. OpcodeStatus: "STATUS",
  120. OpcodeNotify: "NOTIFY",
  121. OpcodeUpdate: "UPDATE",
  122. }
  123. // RcodeToString maps Rcodes to strings.
  124. var RcodeToString = map[int]string{
  125. RcodeSuccess: "NOERROR",
  126. RcodeFormatError: "FORMERR",
  127. RcodeServerFailure: "SERVFAIL",
  128. RcodeNameError: "NXDOMAIN",
  129. RcodeNotImplemented: "NOTIMP",
  130. RcodeRefused: "REFUSED",
  131. RcodeYXDomain: "YXDOMAIN", // See RFC 2136
  132. RcodeYXRrset: "YXRRSET",
  133. RcodeNXRrset: "NXRRSET",
  134. RcodeNotAuth: "NOTAUTH",
  135. RcodeNotZone: "NOTZONE",
  136. RcodeBadSig: "BADSIG", // Also known as RcodeBadVers, see RFC 6891
  137. // RcodeBadVers: "BADVERS",
  138. RcodeBadKey: "BADKEY",
  139. RcodeBadTime: "BADTIME",
  140. RcodeBadMode: "BADMODE",
  141. RcodeBadName: "BADNAME",
  142. RcodeBadAlg: "BADALG",
  143. RcodeBadTrunc: "BADTRUNC",
  144. RcodeBadCookie: "BADCOOKIE",
  145. }
  146. // compressionMap is used to allow a more efficient compression map
  147. // to be used for internal packDomainName calls without changing the
  148. // signature or functionality of public API.
  149. //
  150. // In particular, map[string]uint16 uses 25% less per-entry memory
  151. // than does map[string]int.
  152. type compressionMap struct {
  153. ext map[string]int // external callers
  154. int map[string]uint16 // internal callers
  155. }
  156. func (m compressionMap) valid() bool {
  157. return m.int != nil || m.ext != nil
  158. }
  159. func (m compressionMap) insert(s string, pos int) {
  160. if m.ext != nil {
  161. m.ext[s] = pos
  162. } else {
  163. m.int[s] = uint16(pos)
  164. }
  165. }
  166. func (m compressionMap) find(s string) (int, bool) {
  167. if m.ext != nil {
  168. pos, ok := m.ext[s]
  169. return pos, ok
  170. }
  171. pos, ok := m.int[s]
  172. return int(pos), ok
  173. }
  174. // Domain names are a sequence of counted strings
  175. // split at the dots. They end with a zero-length string.
  176. // PackDomainName packs a domain name s into msg[off:].
  177. // If compression is wanted compress must be true and the compression
  178. // map needs to hold a mapping between domain names and offsets
  179. // pointing into msg.
  180. func PackDomainName(s string, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
  181. return packDomainName(s, msg, off, compressionMap{ext: compression}, compress)
  182. }
  183. func packDomainName(s string, msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) {
  184. // XXX: A logical copy of this function exists in IsDomainName and
  185. // should be kept in sync with this function.
  186. ls := len(s)
  187. if ls == 0 { // Ok, for instance when dealing with update RR without any rdata.
  188. return off, nil
  189. }
  190. // If not fully qualified, error out.
  191. if !IsFqdn(s) {
  192. return len(msg), ErrFqdn
  193. }
  194. // Each dot ends a segment of the name.
  195. // We trade each dot byte for a length byte.
  196. // Except for escaped dots (\.), which are normal dots.
  197. // There is also a trailing zero.
  198. // Compression
  199. pointer := -1
  200. // Emit sequence of counted strings, chopping at dots.
  201. var (
  202. begin int
  203. compBegin int
  204. compOff int
  205. bs []byte
  206. wasDot bool
  207. )
  208. loop:
  209. for i := 0; i < ls; i++ {
  210. var c byte
  211. if bs == nil {
  212. c = s[i]
  213. } else {
  214. c = bs[i]
  215. }
  216. switch c {
  217. case '\\':
  218. if off+1 > len(msg) {
  219. return len(msg), ErrBuf
  220. }
  221. if bs == nil {
  222. bs = []byte(s)
  223. }
  224. // check for \DDD
  225. if i+3 < ls && isDigit(bs[i+1]) && isDigit(bs[i+2]) && isDigit(bs[i+3]) {
  226. bs[i] = dddToByte(bs[i+1:])
  227. copy(bs[i+1:ls-3], bs[i+4:])
  228. ls -= 3
  229. compOff += 3
  230. } else {
  231. copy(bs[i:ls-1], bs[i+1:])
  232. ls--
  233. compOff++
  234. }
  235. wasDot = false
  236. case '.':
  237. if wasDot {
  238. // two dots back to back is not legal
  239. return len(msg), ErrRdata
  240. }
  241. wasDot = true
  242. labelLen := i - begin
  243. if labelLen >= 1<<6 { // top two bits of length must be clear
  244. return len(msg), ErrRdata
  245. }
  246. // off can already (we're in a loop) be bigger than len(msg)
  247. // this happens when a name isn't fully qualified
  248. if off+1+labelLen > len(msg) {
  249. return len(msg), ErrBuf
  250. }
  251. // Don't try to compress '.'
  252. // We should only compress when compress is true, but we should also still pick
  253. // up names that can be used for *future* compression(s).
  254. if compression.valid() && !isRootLabel(s, bs, begin, ls) {
  255. if p, ok := compression.find(s[compBegin:]); ok {
  256. // The first hit is the longest matching dname
  257. // keep the pointer offset we get back and store
  258. // the offset of the current name, because that's
  259. // where we need to insert the pointer later
  260. // If compress is true, we're allowed to compress this dname
  261. if compress {
  262. pointer = p // Where to point to
  263. break loop
  264. }
  265. } else if off < maxCompressionOffset {
  266. // Only offsets smaller than maxCompressionOffset can be used.
  267. compression.insert(s[compBegin:], off)
  268. }
  269. }
  270. // The following is covered by the length check above.
  271. msg[off] = byte(labelLen)
  272. if bs == nil {
  273. copy(msg[off+1:], s[begin:i])
  274. } else {
  275. copy(msg[off+1:], bs[begin:i])
  276. }
  277. off += 1 + labelLen
  278. begin = i + 1
  279. compBegin = begin + compOff
  280. default:
  281. wasDot = false
  282. }
  283. }
  284. // Root label is special
  285. if isRootLabel(s, bs, 0, ls) {
  286. return off, nil
  287. }
  288. // If we did compression and we find something add the pointer here
  289. if pointer != -1 {
  290. // We have two bytes (14 bits) to put the pointer in
  291. binary.BigEndian.PutUint16(msg[off:], uint16(pointer^0xC000))
  292. return off + 2, nil
  293. }
  294. if off < len(msg) {
  295. msg[off] = 0
  296. }
  297. return off + 1, nil
  298. }
  299. // isRootLabel returns whether s or bs, from off to end, is the root
  300. // label ".".
  301. //
  302. // If bs is nil, s will be checked, otherwise bs will be checked.
  303. func isRootLabel(s string, bs []byte, off, end int) bool {
  304. if bs == nil {
  305. return s[off:end] == "."
  306. }
  307. return end-off == 1 && bs[off] == '.'
  308. }
  309. // Unpack a domain name.
  310. // In addition to the simple sequences of counted strings above,
  311. // domain names are allowed to refer to strings elsewhere in the
  312. // packet, to avoid repeating common suffixes when returning
  313. // many entries in a single domain. The pointers are marked
  314. // by a length byte with the top two bits set. Ignoring those
  315. // two bits, that byte and the next give a 14 bit offset from msg[0]
  316. // where we should pick up the trail.
  317. // Note that if we jump elsewhere in the packet,
  318. // we return off1 == the offset after the first pointer we found,
  319. // which is where the next record will start.
  320. // In theory, the pointers are only allowed to jump backward.
  321. // We let them jump anywhere and stop jumping after a while.
  322. // UnpackDomainName unpacks a domain name into a string. It returns
  323. // the name, the new offset into msg and any error that occurred.
  324. //
  325. // When an error is encountered, the unpacked name will be discarded
  326. // and len(msg) will be returned as the offset.
  327. func UnpackDomainName(msg []byte, off int) (string, int, error) {
  328. s := make([]byte, 0, maxDomainNamePresentationLength)
  329. off1 := 0
  330. lenmsg := len(msg)
  331. budget := maxDomainNameWireOctets
  332. ptr := 0 // number of pointers followed
  333. Loop:
  334. for {
  335. if off >= lenmsg {
  336. return "", lenmsg, ErrBuf
  337. }
  338. c := int(msg[off])
  339. off++
  340. switch c & 0xC0 {
  341. case 0x00:
  342. if c == 0x00 {
  343. // end of name
  344. break Loop
  345. }
  346. // literal string
  347. if off+c > lenmsg {
  348. return "", lenmsg, ErrBuf
  349. }
  350. budget -= c + 1 // +1 for the label separator
  351. if budget <= 0 {
  352. return "", lenmsg, ErrLongDomain
  353. }
  354. for _, b := range msg[off : off+c] {
  355. switch b {
  356. case '.', '(', ')', ';', ' ', '@':
  357. fallthrough
  358. case '"', '\\':
  359. s = append(s, '\\', b)
  360. default:
  361. if b < ' ' || b > '~' { // unprintable, use \DDD
  362. s = append(s, escapeByte(b)...)
  363. } else {
  364. s = append(s, b)
  365. }
  366. }
  367. }
  368. s = append(s, '.')
  369. off += c
  370. case 0xC0:
  371. // pointer to somewhere else in msg.
  372. // remember location after first ptr,
  373. // since that's how many bytes we consumed.
  374. // also, don't follow too many pointers --
  375. // maybe there's a loop.
  376. if off >= lenmsg {
  377. return "", lenmsg, ErrBuf
  378. }
  379. c1 := msg[off]
  380. off++
  381. if ptr == 0 {
  382. off1 = off
  383. }
  384. if ptr++; ptr > maxCompressionPointers {
  385. return "", lenmsg, &Error{err: "too many compression pointers"}
  386. }
  387. // pointer should guarantee that it advances and points forwards at least
  388. // but the condition on previous three lines guarantees that it's
  389. // at least loop-free
  390. off = (c^0xC0)<<8 | int(c1)
  391. default:
  392. // 0x80 and 0x40 are reserved
  393. return "", lenmsg, ErrRdata
  394. }
  395. }
  396. if ptr == 0 {
  397. off1 = off
  398. }
  399. if len(s) == 0 {
  400. return ".", off1, nil
  401. }
  402. return string(s), off1, nil
  403. }
  404. func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) {
  405. if len(txt) == 0 {
  406. if offset >= len(msg) {
  407. return offset, ErrBuf
  408. }
  409. msg[offset] = 0
  410. return offset, nil
  411. }
  412. var err error
  413. for _, s := range txt {
  414. if len(s) > len(tmp) {
  415. return offset, ErrBuf
  416. }
  417. offset, err = packTxtString(s, msg, offset, tmp)
  418. if err != nil {
  419. return offset, err
  420. }
  421. }
  422. return offset, nil
  423. }
  424. func packTxtString(s string, msg []byte, offset int, tmp []byte) (int, error) {
  425. lenByteOffset := offset
  426. if offset >= len(msg) || len(s) > len(tmp) {
  427. return offset, ErrBuf
  428. }
  429. offset++
  430. bs := tmp[:len(s)]
  431. copy(bs, s)
  432. for i := 0; i < len(bs); i++ {
  433. if len(msg) <= offset {
  434. return offset, ErrBuf
  435. }
  436. if bs[i] == '\\' {
  437. i++
  438. if i == len(bs) {
  439. break
  440. }
  441. // check for \DDD
  442. if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
  443. msg[offset] = dddToByte(bs[i:])
  444. i += 2
  445. } else {
  446. msg[offset] = bs[i]
  447. }
  448. } else {
  449. msg[offset] = bs[i]
  450. }
  451. offset++
  452. }
  453. l := offset - lenByteOffset - 1
  454. if l > 255 {
  455. return offset, &Error{err: "string exceeded 255 bytes in txt"}
  456. }
  457. msg[lenByteOffset] = byte(l)
  458. return offset, nil
  459. }
  460. func packOctetString(s string, msg []byte, offset int, tmp []byte) (int, error) {
  461. if offset >= len(msg) || len(s) > len(tmp) {
  462. return offset, ErrBuf
  463. }
  464. bs := tmp[:len(s)]
  465. copy(bs, s)
  466. for i := 0; i < len(bs); i++ {
  467. if len(msg) <= offset {
  468. return offset, ErrBuf
  469. }
  470. if bs[i] == '\\' {
  471. i++
  472. if i == len(bs) {
  473. break
  474. }
  475. // check for \DDD
  476. if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
  477. msg[offset] = dddToByte(bs[i:])
  478. i += 2
  479. } else {
  480. msg[offset] = bs[i]
  481. }
  482. } else {
  483. msg[offset] = bs[i]
  484. }
  485. offset++
  486. }
  487. return offset, nil
  488. }
  489. func unpackTxt(msg []byte, off0 int) (ss []string, off int, err error) {
  490. off = off0
  491. var s string
  492. for off < len(msg) && err == nil {
  493. s, off, err = unpackString(msg, off)
  494. if err == nil {
  495. ss = append(ss, s)
  496. }
  497. }
  498. return
  499. }
  500. // Helpers for dealing with escaped bytes
  501. func isDigit(b byte) bool { return b >= '0' && b <= '9' }
  502. func dddToByte(s []byte) byte {
  503. _ = s[2] // bounds check hint to compiler; see golang.org/issue/14808
  504. return byte((s[0]-'0')*100 + (s[1]-'0')*10 + (s[2] - '0'))
  505. }
  506. func dddStringToByte(s string) byte {
  507. _ = s[2] // bounds check hint to compiler; see golang.org/issue/14808
  508. return byte((s[0]-'0')*100 + (s[1]-'0')*10 + (s[2] - '0'))
  509. }
  510. // Helper function for packing and unpacking
  511. func intToBytes(i *big.Int, length int) []byte {
  512. buf := i.Bytes()
  513. if len(buf) < length {
  514. b := make([]byte, length)
  515. copy(b[length-len(buf):], buf)
  516. return b
  517. }
  518. return buf
  519. }
  520. // PackRR packs a resource record rr into msg[off:].
  521. // See PackDomainName for documentation about the compression.
  522. func PackRR(rr RR, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
  523. headerEnd, off1, err := packRR(rr, msg, off, compressionMap{ext: compression}, compress)
  524. if err == nil {
  525. // packRR no longer sets the Rdlength field on the rr, but
  526. // callers might be expecting it so we set it here.
  527. rr.Header().Rdlength = uint16(off1 - headerEnd)
  528. }
  529. return off1, err
  530. }
  531. func packRR(rr RR, msg []byte, off int, compression compressionMap, compress bool) (headerEnd int, off1 int, err error) {
  532. if rr == nil {
  533. return len(msg), len(msg), &Error{err: "nil rr"}
  534. }
  535. headerEnd, err = rr.Header().packHeader(msg, off, compression, compress)
  536. if err != nil {
  537. return headerEnd, len(msg), err
  538. }
  539. off1, err = rr.pack(msg, headerEnd, compression, compress)
  540. if err != nil {
  541. return headerEnd, len(msg), err
  542. }
  543. rdlength := off1 - headerEnd
  544. if int(uint16(rdlength)) != rdlength { // overflow
  545. return headerEnd, len(msg), ErrRdata
  546. }
  547. // The RDLENGTH field is the last field in the header and we set it here.
  548. binary.BigEndian.PutUint16(msg[headerEnd-2:], uint16(rdlength))
  549. return headerEnd, off1, nil
  550. }
  551. // UnpackRR unpacks msg[off:] into an RR.
  552. func UnpackRR(msg []byte, off int) (rr RR, off1 int, err error) {
  553. h, off, msg, err := unpackHeader(msg, off)
  554. if err != nil {
  555. return nil, len(msg), err
  556. }
  557. return UnpackRRWithHeader(h, msg, off)
  558. }
  559. // UnpackRRWithHeader unpacks the record type specific payload given an existing
  560. // RR_Header.
  561. func UnpackRRWithHeader(h RR_Header, msg []byte, off int) (rr RR, off1 int, err error) {
  562. if newFn, ok := TypeToRR[h.Rrtype]; ok {
  563. rr = newFn()
  564. *rr.Header() = h
  565. } else {
  566. rr = &RFC3597{Hdr: h}
  567. }
  568. if noRdata(h) {
  569. return rr, off, nil
  570. }
  571. end := off + int(h.Rdlength)
  572. off, err = rr.unpack(msg, off)
  573. if err != nil {
  574. return nil, end, err
  575. }
  576. if off != end {
  577. return &h, end, &Error{err: "bad rdlength"}
  578. }
  579. return rr, off, nil
  580. }
  581. // unpackRRslice unpacks msg[off:] into an []RR.
  582. // If we cannot unpack the whole array, then it will return nil
  583. func unpackRRslice(l int, msg []byte, off int) (dst1 []RR, off1 int, err error) {
  584. var r RR
  585. // Don't pre-allocate, l may be under attacker control
  586. var dst []RR
  587. for i := 0; i < l; i++ {
  588. off1 := off
  589. r, off, err = UnpackRR(msg, off)
  590. if err != nil {
  591. off = len(msg)
  592. break
  593. }
  594. // If offset does not increase anymore, l is a lie
  595. if off1 == off {
  596. break
  597. }
  598. dst = append(dst, r)
  599. }
  600. if err != nil && off == len(msg) {
  601. dst = nil
  602. }
  603. return dst, off, err
  604. }
  605. // Convert a MsgHdr to a string, with dig-like headers:
  606. //
  607. //;; opcode: QUERY, status: NOERROR, id: 48404
  608. //
  609. //;; flags: qr aa rd ra;
  610. func (h *MsgHdr) String() string {
  611. if h == nil {
  612. return "<nil> MsgHdr"
  613. }
  614. s := ";; opcode: " + OpcodeToString[h.Opcode]
  615. s += ", status: " + RcodeToString[h.Rcode]
  616. s += ", id: " + strconv.Itoa(int(h.Id)) + "\n"
  617. s += ";; flags:"
  618. if h.Response {
  619. s += " qr"
  620. }
  621. if h.Authoritative {
  622. s += " aa"
  623. }
  624. if h.Truncated {
  625. s += " tc"
  626. }
  627. if h.RecursionDesired {
  628. s += " rd"
  629. }
  630. if h.RecursionAvailable {
  631. s += " ra"
  632. }
  633. if h.Zero { // Hmm
  634. s += " z"
  635. }
  636. if h.AuthenticatedData {
  637. s += " ad"
  638. }
  639. if h.CheckingDisabled {
  640. s += " cd"
  641. }
  642. s += ";"
  643. return s
  644. }
  645. // Pack packs a Msg: it is converted to to wire format.
  646. // If the dns.Compress is true the message will be in compressed wire format.
  647. func (dns *Msg) Pack() (msg []byte, err error) {
  648. return dns.PackBuffer(nil)
  649. }
  650. // PackBuffer packs a Msg, using the given buffer buf. If buf is too small a new buffer is allocated.
  651. func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error) {
  652. // If this message can't be compressed, avoid filling the
  653. // compression map and creating garbage.
  654. if dns.Compress && dns.isCompressible() {
  655. compression := make(map[string]uint16) // Compression pointer mappings.
  656. return dns.packBufferWithCompressionMap(buf, compressionMap{int: compression}, true)
  657. }
  658. return dns.packBufferWithCompressionMap(buf, compressionMap{}, false)
  659. }
  660. // packBufferWithCompressionMap packs a Msg, using the given buffer buf.
  661. func (dns *Msg) packBufferWithCompressionMap(buf []byte, compression compressionMap, compress bool) (msg []byte, err error) {
  662. if dns.Rcode < 0 || dns.Rcode > 0xFFF {
  663. return nil, ErrRcode
  664. }
  665. // Set extended rcode unconditionally if we have an opt, this will allow
  666. // reseting the extended rcode bits if they need to.
  667. if opt := dns.IsEdns0(); opt != nil {
  668. opt.SetExtendedRcode(uint16(dns.Rcode))
  669. } else if dns.Rcode > 0xF {
  670. // If Rcode is an extended one and opt is nil, error out.
  671. return nil, ErrExtendedRcode
  672. }
  673. // Convert convenient Msg into wire-like Header.
  674. var dh Header
  675. dh.Id = dns.Id
  676. dh.Bits = uint16(dns.Opcode)<<11 | uint16(dns.Rcode&0xF)
  677. if dns.Response {
  678. dh.Bits |= _QR
  679. }
  680. if dns.Authoritative {
  681. dh.Bits |= _AA
  682. }
  683. if dns.Truncated {
  684. dh.Bits |= _TC
  685. }
  686. if dns.RecursionDesired {
  687. dh.Bits |= _RD
  688. }
  689. if dns.RecursionAvailable {
  690. dh.Bits |= _RA
  691. }
  692. if dns.Zero {
  693. dh.Bits |= _Z
  694. }
  695. if dns.AuthenticatedData {
  696. dh.Bits |= _AD
  697. }
  698. if dns.CheckingDisabled {
  699. dh.Bits |= _CD
  700. }
  701. dh.Qdcount = uint16(len(dns.Question))
  702. dh.Ancount = uint16(len(dns.Answer))
  703. dh.Nscount = uint16(len(dns.Ns))
  704. dh.Arcount = uint16(len(dns.Extra))
  705. // We need the uncompressed length here, because we first pack it and then compress it.
  706. msg = buf
  707. uncompressedLen := msgLenWithCompressionMap(dns, nil)
  708. if packLen := uncompressedLen + 1; len(msg) < packLen {
  709. msg = make([]byte, packLen)
  710. }
  711. // Pack it in: header and then the pieces.
  712. off := 0
  713. off, err = dh.pack(msg, off, compression, compress)
  714. if err != nil {
  715. return nil, err
  716. }
  717. for _, r := range dns.Question {
  718. off, err = r.pack(msg, off, compression, compress)
  719. if err != nil {
  720. return nil, err
  721. }
  722. }
  723. for _, r := range dns.Answer {
  724. _, off, err = packRR(r, msg, off, compression, compress)
  725. if err != nil {
  726. return nil, err
  727. }
  728. }
  729. for _, r := range dns.Ns {
  730. _, off, err = packRR(r, msg, off, compression, compress)
  731. if err != nil {
  732. return nil, err
  733. }
  734. }
  735. for _, r := range dns.Extra {
  736. _, off, err = packRR(r, msg, off, compression, compress)
  737. if err != nil {
  738. return nil, err
  739. }
  740. }
  741. return msg[:off], nil
  742. }
  743. func (dns *Msg) unpack(dh Header, msg []byte, off int) (err error) {
  744. // If we are at the end of the message we should return *just* the
  745. // header. This can still be useful to the caller. 9.9.9.9 sends these
  746. // when responding with REFUSED for instance.
  747. if off == len(msg) {
  748. // reset sections before returning
  749. dns.Question, dns.Answer, dns.Ns, dns.Extra = nil, nil, nil, nil
  750. return nil
  751. }
  752. // Qdcount, Ancount, Nscount, Arcount can't be trusted, as they are
  753. // attacker controlled. This means we can't use them to pre-allocate
  754. // slices.
  755. dns.Question = nil
  756. for i := 0; i < int(dh.Qdcount); i++ {
  757. off1 := off
  758. var q Question
  759. q, off, err = unpackQuestion(msg, off)
  760. if err != nil {
  761. return err
  762. }
  763. if off1 == off { // Offset does not increase anymore, dh.Qdcount is a lie!
  764. dh.Qdcount = uint16(i)
  765. break
  766. }
  767. dns.Question = append(dns.Question, q)
  768. }
  769. dns.Answer, off, err = unpackRRslice(int(dh.Ancount), msg, off)
  770. // The header counts might have been wrong so we need to update it
  771. dh.Ancount = uint16(len(dns.Answer))
  772. if err == nil {
  773. dns.Ns, off, err = unpackRRslice(int(dh.Nscount), msg, off)
  774. }
  775. // The header counts might have been wrong so we need to update it
  776. dh.Nscount = uint16(len(dns.Ns))
  777. if err == nil {
  778. dns.Extra, off, err = unpackRRslice(int(dh.Arcount), msg, off)
  779. }
  780. // The header counts might have been wrong so we need to update it
  781. dh.Arcount = uint16(len(dns.Extra))
  782. // Set extended Rcode
  783. if opt := dns.IsEdns0(); opt != nil {
  784. dns.Rcode |= opt.ExtendedRcode()
  785. }
  786. if off != len(msg) {
  787. // TODO(miek) make this an error?
  788. // use PackOpt to let people tell how detailed the error reporting should be?
  789. // println("dns: extra bytes in dns packet", off, "<", len(msg))
  790. }
  791. return err
  792. }
  793. // Unpack unpacks a binary message to a Msg structure.
  794. func (dns *Msg) Unpack(msg []byte) (err error) {
  795. dh, off, err := unpackMsgHdr(msg, 0)
  796. if err != nil {
  797. return err
  798. }
  799. dns.setHdr(dh)
  800. return dns.unpack(dh, msg, off)
  801. }
  802. // Convert a complete message to a string with dig-like output.
  803. func (dns *Msg) String() string {
  804. if dns == nil {
  805. return "<nil> MsgHdr"
  806. }
  807. s := dns.MsgHdr.String() + " "
  808. s += "QUERY: " + strconv.Itoa(len(dns.Question)) + ", "
  809. s += "ANSWER: " + strconv.Itoa(len(dns.Answer)) + ", "
  810. s += "AUTHORITY: " + strconv.Itoa(len(dns.Ns)) + ", "
  811. s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n"
  812. if len(dns.Question) > 0 {
  813. s += "\n;; QUESTION SECTION:\n"
  814. for _, r := range dns.Question {
  815. s += r.String() + "\n"
  816. }
  817. }
  818. if len(dns.Answer) > 0 {
  819. s += "\n;; ANSWER SECTION:\n"
  820. for _, r := range dns.Answer {
  821. if r != nil {
  822. s += r.String() + "\n"
  823. }
  824. }
  825. }
  826. if len(dns.Ns) > 0 {
  827. s += "\n;; AUTHORITY SECTION:\n"
  828. for _, r := range dns.Ns {
  829. if r != nil {
  830. s += r.String() + "\n"
  831. }
  832. }
  833. }
  834. if len(dns.Extra) > 0 {
  835. s += "\n;; ADDITIONAL SECTION:\n"
  836. for _, r := range dns.Extra {
  837. if r != nil {
  838. s += r.String() + "\n"
  839. }
  840. }
  841. }
  842. return s
  843. }
  844. // isCompressible returns whether the msg may be compressible.
  845. func (dns *Msg) isCompressible() bool {
  846. // If we only have one question, there is nothing we can ever compress.
  847. return len(dns.Question) > 1 || len(dns.Answer) > 0 ||
  848. len(dns.Ns) > 0 || len(dns.Extra) > 0
  849. }
  850. // Len returns the message length when in (un)compressed wire format.
  851. // If dns.Compress is true compression it is taken into account. Len()
  852. // is provided to be a faster way to get the size of the resulting packet,
  853. // than packing it, measuring the size and discarding the buffer.
  854. func (dns *Msg) Len() int {
  855. // If this message can't be compressed, avoid filling the
  856. // compression map and creating garbage.
  857. if dns.Compress && dns.isCompressible() {
  858. compression := make(map[string]struct{})
  859. return msgLenWithCompressionMap(dns, compression)
  860. }
  861. return msgLenWithCompressionMap(dns, nil)
  862. }
  863. func msgLenWithCompressionMap(dns *Msg, compression map[string]struct{}) int {
  864. l := headerSize
  865. for _, r := range dns.Question {
  866. l += r.len(l, compression)
  867. }
  868. for _, r := range dns.Answer {
  869. if r != nil {
  870. l += r.len(l, compression)
  871. }
  872. }
  873. for _, r := range dns.Ns {
  874. if r != nil {
  875. l += r.len(l, compression)
  876. }
  877. }
  878. for _, r := range dns.Extra {
  879. if r != nil {
  880. l += r.len(l, compression)
  881. }
  882. }
  883. return l
  884. }
  885. func domainNameLen(s string, off int, compression map[string]struct{}, compress bool) int {
  886. if s == "" || s == "." {
  887. return 1
  888. }
  889. escaped := strings.Contains(s, "\\")
  890. if compression != nil && (compress || off < maxCompressionOffset) {
  891. // compressionLenSearch will insert the entry into the compression
  892. // map if it doesn't contain it.
  893. if l, ok := compressionLenSearch(compression, s, off); ok && compress {
  894. if escaped {
  895. return escapedNameLen(s[:l]) + 2
  896. }
  897. return l + 2
  898. }
  899. }
  900. if escaped {
  901. return escapedNameLen(s) + 1
  902. }
  903. return len(s) + 1
  904. }
  905. func escapedNameLen(s string) int {
  906. nameLen := len(s)
  907. for i := 0; i < len(s); i++ {
  908. if s[i] != '\\' {
  909. continue
  910. }
  911. if i+3 < len(s) && isDigit(s[i+1]) && isDigit(s[i+2]) && isDigit(s[i+3]) {
  912. nameLen -= 3
  913. i += 3
  914. } else {
  915. nameLen--
  916. i++
  917. }
  918. }
  919. return nameLen
  920. }
  921. func compressionLenSearch(c map[string]struct{}, s string, msgOff int) (int, bool) {
  922. for off, end := 0, false; !end; off, end = NextLabel(s, off) {
  923. if _, ok := c[s[off:]]; ok {
  924. return off, true
  925. }
  926. if msgOff+off < maxCompressionOffset {
  927. c[s[off:]] = struct{}{}
  928. }
  929. }
  930. return 0, false
  931. }
  932. // Copy returns a new RR which is a deep-copy of r.
  933. func Copy(r RR) RR { return r.copy() }
  934. // Len returns the length (in octets) of the uncompressed RR in wire format.
  935. func Len(r RR) int { return r.len(0, nil) }
  936. // Copy returns a new *Msg which is a deep-copy of dns.
  937. func (dns *Msg) Copy() *Msg { return dns.CopyTo(new(Msg)) }
  938. // CopyTo copies the contents to the provided message using a deep-copy and returns the copy.
  939. func (dns *Msg) CopyTo(r1 *Msg) *Msg {
  940. r1.MsgHdr = dns.MsgHdr
  941. r1.Compress = dns.Compress
  942. if len(dns.Question) > 0 {
  943. r1.Question = make([]Question, len(dns.Question))
  944. copy(r1.Question, dns.Question) // TODO(miek): Question is an immutable value, ok to do a shallow-copy
  945. }
  946. rrArr := make([]RR, len(dns.Answer)+len(dns.Ns)+len(dns.Extra))
  947. r1.Answer, rrArr = rrArr[:0:len(dns.Answer)], rrArr[len(dns.Answer):]
  948. r1.Ns, rrArr = rrArr[:0:len(dns.Ns)], rrArr[len(dns.Ns):]
  949. r1.Extra = rrArr[:0:len(dns.Extra)]
  950. for _, r := range dns.Answer {
  951. r1.Answer = append(r1.Answer, r.copy())
  952. }
  953. for _, r := range dns.Ns {
  954. r1.Ns = append(r1.Ns, r.copy())
  955. }
  956. for _, r := range dns.Extra {
  957. r1.Extra = append(r1.Extra, r.copy())
  958. }
  959. return r1
  960. }
  961. func (q *Question) pack(msg []byte, off int, compression compressionMap, compress bool) (int, error) {
  962. off, err := packDomainName(q.Name, msg, off, compression, compress)
  963. if err != nil {
  964. return off, err
  965. }
  966. off, err = packUint16(q.Qtype, msg, off)
  967. if err != nil {
  968. return off, err
  969. }
  970. off, err = packUint16(q.Qclass, msg, off)
  971. if err != nil {
  972. return off, err
  973. }
  974. return off, nil
  975. }
  976. func unpackQuestion(msg []byte, off int) (Question, int, error) {
  977. var (
  978. q Question
  979. err error
  980. )
  981. q.Name, off, err = UnpackDomainName(msg, off)
  982. if err != nil {
  983. return q, off, err
  984. }
  985. if off == len(msg) {
  986. return q, off, nil
  987. }
  988. q.Qtype, off, err = unpackUint16(msg, off)
  989. if err != nil {
  990. return q, off, err
  991. }
  992. if off == len(msg) {
  993. return q, off, nil
  994. }
  995. q.Qclass, off, err = unpackUint16(msg, off)
  996. if off == len(msg) {
  997. return q, off, nil
  998. }
  999. return q, off, err
  1000. }
  1001. func (dh *Header) pack(msg []byte, off int, compression compressionMap, compress bool) (int, error) {
  1002. off, err := packUint16(dh.Id, msg, off)
  1003. if err != nil {
  1004. return off, err
  1005. }
  1006. off, err = packUint16(dh.Bits, msg, off)
  1007. if err != nil {
  1008. return off, err
  1009. }
  1010. off, err = packUint16(dh.Qdcount, msg, off)
  1011. if err != nil {
  1012. return off, err
  1013. }
  1014. off, err = packUint16(dh.Ancount, msg, off)
  1015. if err != nil {
  1016. return off, err
  1017. }
  1018. off, err = packUint16(dh.Nscount, msg, off)
  1019. if err != nil {
  1020. return off, err
  1021. }
  1022. off, err = packUint16(dh.Arcount, msg, off)
  1023. if err != nil {
  1024. return off, err
  1025. }
  1026. return off, nil
  1027. }
  1028. func unpackMsgHdr(msg []byte, off int) (Header, int, error) {
  1029. var (
  1030. dh Header
  1031. err error
  1032. )
  1033. dh.Id, off, err = unpackUint16(msg, off)
  1034. if err != nil {
  1035. return dh, off, err
  1036. }
  1037. dh.Bits, off, err = unpackUint16(msg, off)
  1038. if err != nil {
  1039. return dh, off, err
  1040. }
  1041. dh.Qdcount, off, err = unpackUint16(msg, off)
  1042. if err != nil {
  1043. return dh, off, err
  1044. }
  1045. dh.Ancount, off, err = unpackUint16(msg, off)
  1046. if err != nil {
  1047. return dh, off, err
  1048. }
  1049. dh.Nscount, off, err = unpackUint16(msg, off)
  1050. if err != nil {
  1051. return dh, off, err
  1052. }
  1053. dh.Arcount, off, err = unpackUint16(msg, off)
  1054. if err != nil {
  1055. return dh, off, err
  1056. }
  1057. return dh, off, nil
  1058. }
  1059. // setHdr set the header in the dns using the binary data in dh.
  1060. func (dns *Msg) setHdr(dh Header) {
  1061. dns.Id = dh.Id
  1062. dns.Response = dh.Bits&_QR != 0
  1063. dns.Opcode = int(dh.Bits>>11) & 0xF
  1064. dns.Authoritative = dh.Bits&_AA != 0
  1065. dns.Truncated = dh.Bits&_TC != 0
  1066. dns.RecursionDesired = dh.Bits&_RD != 0
  1067. dns.RecursionAvailable = dh.Bits&_RA != 0
  1068. dns.Zero = dh.Bits&_Z != 0 // _Z covers the zero bit, which should be zero; not sure why we set it to the opposite.
  1069. dns.AuthenticatedData = dh.Bits&_AD != 0
  1070. dns.CheckingDisabled = dh.Bits&_CD != 0
  1071. dns.Rcode = int(dh.Bits & 0xF)
  1072. }