msg.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  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 i == 0 && len(s) > 1 {
  238. // leading dots are not legal except for the root zone
  239. return len(msg), ErrRdata
  240. }
  241. if wasDot {
  242. // two dots back to back is not legal
  243. return len(msg), ErrRdata
  244. }
  245. wasDot = true
  246. labelLen := i - begin
  247. if labelLen >= 1<<6 { // top two bits of length must be clear
  248. return len(msg), ErrRdata
  249. }
  250. // off can already (we're in a loop) be bigger than len(msg)
  251. // this happens when a name isn't fully qualified
  252. if off+1+labelLen > len(msg) {
  253. return len(msg), ErrBuf
  254. }
  255. // Don't try to compress '.'
  256. // We should only compress when compress is true, but we should also still pick
  257. // up names that can be used for *future* compression(s).
  258. if compression.valid() && !isRootLabel(s, bs, begin, ls) {
  259. if p, ok := compression.find(s[compBegin:]); ok {
  260. // The first hit is the longest matching dname
  261. // keep the pointer offset we get back and store
  262. // the offset of the current name, because that's
  263. // where we need to insert the pointer later
  264. // If compress is true, we're allowed to compress this dname
  265. if compress {
  266. pointer = p // Where to point to
  267. break loop
  268. }
  269. } else if off < maxCompressionOffset {
  270. // Only offsets smaller than maxCompressionOffset can be used.
  271. compression.insert(s[compBegin:], off)
  272. }
  273. }
  274. // The following is covered by the length check above.
  275. msg[off] = byte(labelLen)
  276. if bs == nil {
  277. copy(msg[off+1:], s[begin:i])
  278. } else {
  279. copy(msg[off+1:], bs[begin:i])
  280. }
  281. off += 1 + labelLen
  282. begin = i + 1
  283. compBegin = begin + compOff
  284. default:
  285. wasDot = false
  286. }
  287. }
  288. // Root label is special
  289. if isRootLabel(s, bs, 0, ls) {
  290. return off, nil
  291. }
  292. // If we did compression and we find something add the pointer here
  293. if pointer != -1 {
  294. // We have two bytes (14 bits) to put the pointer in
  295. binary.BigEndian.PutUint16(msg[off:], uint16(pointer^0xC000))
  296. return off + 2, nil
  297. }
  298. if off < len(msg) {
  299. msg[off] = 0
  300. }
  301. return off + 1, nil
  302. }
  303. // isRootLabel returns whether s or bs, from off to end, is the root
  304. // label ".".
  305. //
  306. // If bs is nil, s will be checked, otherwise bs will be checked.
  307. func isRootLabel(s string, bs []byte, off, end int) bool {
  308. if bs == nil {
  309. return s[off:end] == "."
  310. }
  311. return end-off == 1 && bs[off] == '.'
  312. }
  313. // Unpack a domain name.
  314. // In addition to the simple sequences of counted strings above,
  315. // domain names are allowed to refer to strings elsewhere in the
  316. // packet, to avoid repeating common suffixes when returning
  317. // many entries in a single domain. The pointers are marked
  318. // by a length byte with the top two bits set. Ignoring those
  319. // two bits, that byte and the next give a 14 bit offset from msg[0]
  320. // where we should pick up the trail.
  321. // Note that if we jump elsewhere in the packet,
  322. // we return off1 == the offset after the first pointer we found,
  323. // which is where the next record will start.
  324. // In theory, the pointers are only allowed to jump backward.
  325. // We let them jump anywhere and stop jumping after a while.
  326. // UnpackDomainName unpacks a domain name into a string. It returns
  327. // the name, the new offset into msg and any error that occurred.
  328. //
  329. // When an error is encountered, the unpacked name will be discarded
  330. // and len(msg) will be returned as the offset.
  331. func UnpackDomainName(msg []byte, off int) (string, int, error) {
  332. s := make([]byte, 0, maxDomainNamePresentationLength)
  333. off1 := 0
  334. lenmsg := len(msg)
  335. budget := maxDomainNameWireOctets
  336. ptr := 0 // number of pointers followed
  337. Loop:
  338. for {
  339. if off >= lenmsg {
  340. return "", lenmsg, ErrBuf
  341. }
  342. c := int(msg[off])
  343. off++
  344. switch c & 0xC0 {
  345. case 0x00:
  346. if c == 0x00 {
  347. // end of name
  348. break Loop
  349. }
  350. // literal string
  351. if off+c > lenmsg {
  352. return "", lenmsg, ErrBuf
  353. }
  354. budget -= c + 1 // +1 for the label separator
  355. if budget <= 0 {
  356. return "", lenmsg, ErrLongDomain
  357. }
  358. for _, b := range msg[off : off+c] {
  359. if isDomainNameLabelSpecial(b) {
  360. s = append(s, '\\', b)
  361. } else if b < ' ' || b > '~' {
  362. s = append(s, escapeByte(b)...)
  363. } else {
  364. s = append(s, b)
  365. }
  366. }
  367. s = append(s, '.')
  368. off += c
  369. case 0xC0:
  370. // pointer to somewhere else in msg.
  371. // remember location after first ptr,
  372. // since that's how many bytes we consumed.
  373. // also, don't follow too many pointers --
  374. // maybe there's a loop.
  375. if off >= lenmsg {
  376. return "", lenmsg, ErrBuf
  377. }
  378. c1 := msg[off]
  379. off++
  380. if ptr == 0 {
  381. off1 = off
  382. }
  383. if ptr++; ptr > maxCompressionPointers {
  384. return "", lenmsg, &Error{err: "too many compression pointers"}
  385. }
  386. // pointer should guarantee that it advances and points forwards at least
  387. // but the condition on previous three lines guarantees that it's
  388. // at least loop-free
  389. off = (c^0xC0)<<8 | int(c1)
  390. default:
  391. // 0x80 and 0x40 are reserved
  392. return "", lenmsg, ErrRdata
  393. }
  394. }
  395. if ptr == 0 {
  396. off1 = off
  397. }
  398. if len(s) == 0 {
  399. return ".", off1, nil
  400. }
  401. return string(s), off1, nil
  402. }
  403. func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) {
  404. if len(txt) == 0 {
  405. if offset >= len(msg) {
  406. return offset, ErrBuf
  407. }
  408. msg[offset] = 0
  409. return offset, nil
  410. }
  411. var err error
  412. for _, s := range txt {
  413. if len(s) > len(tmp) {
  414. return offset, ErrBuf
  415. }
  416. offset, err = packTxtString(s, msg, offset, tmp)
  417. if err != nil {
  418. return offset, err
  419. }
  420. }
  421. return offset, nil
  422. }
  423. func packTxtString(s string, msg []byte, offset int, tmp []byte) (int, error) {
  424. lenByteOffset := offset
  425. if offset >= len(msg) || len(s) > len(tmp) {
  426. return offset, ErrBuf
  427. }
  428. offset++
  429. bs := tmp[:len(s)]
  430. copy(bs, s)
  431. for i := 0; i < len(bs); i++ {
  432. if len(msg) <= offset {
  433. return offset, ErrBuf
  434. }
  435. if bs[i] == '\\' {
  436. i++
  437. if i == len(bs) {
  438. break
  439. }
  440. // check for \DDD
  441. if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
  442. msg[offset] = dddToByte(bs[i:])
  443. i += 2
  444. } else {
  445. msg[offset] = bs[i]
  446. }
  447. } else {
  448. msg[offset] = bs[i]
  449. }
  450. offset++
  451. }
  452. l := offset - lenByteOffset - 1
  453. if l > 255 {
  454. return offset, &Error{err: "string exceeded 255 bytes in txt"}
  455. }
  456. msg[lenByteOffset] = byte(l)
  457. return offset, nil
  458. }
  459. func packOctetString(s string, msg []byte, offset int, tmp []byte) (int, error) {
  460. if offset >= len(msg) || len(s) > len(tmp) {
  461. return offset, ErrBuf
  462. }
  463. bs := tmp[:len(s)]
  464. copy(bs, s)
  465. for i := 0; i < len(bs); i++ {
  466. if len(msg) <= offset {
  467. return offset, ErrBuf
  468. }
  469. if bs[i] == '\\' {
  470. i++
  471. if i == len(bs) {
  472. break
  473. }
  474. // check for \DDD
  475. if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
  476. msg[offset] = dddToByte(bs[i:])
  477. i += 2
  478. } else {
  479. msg[offset] = bs[i]
  480. }
  481. } else {
  482. msg[offset] = bs[i]
  483. }
  484. offset++
  485. }
  486. return offset, nil
  487. }
  488. func unpackTxt(msg []byte, off0 int) (ss []string, off int, err error) {
  489. off = off0
  490. var s string
  491. for off < len(msg) && err == nil {
  492. s, off, err = unpackString(msg, off)
  493. if err == nil {
  494. ss = append(ss, s)
  495. }
  496. }
  497. return
  498. }
  499. // Helpers for dealing with escaped bytes
  500. func isDigit(b byte) bool { return b >= '0' && b <= '9' }
  501. func dddToByte(s []byte) byte {
  502. _ = s[2] // bounds check hint to compiler; see golang.org/issue/14808
  503. return byte((s[0]-'0')*100 + (s[1]-'0')*10 + (s[2] - '0'))
  504. }
  505. func dddStringToByte(s string) byte {
  506. _ = s[2] // bounds check hint to compiler; see golang.org/issue/14808
  507. return byte((s[0]-'0')*100 + (s[1]-'0')*10 + (s[2] - '0'))
  508. }
  509. // Helper function for packing and unpacking
  510. func intToBytes(i *big.Int, length int) []byte {
  511. buf := i.Bytes()
  512. if len(buf) < length {
  513. b := make([]byte, length)
  514. copy(b[length-len(buf):], buf)
  515. return b
  516. }
  517. return buf
  518. }
  519. // PackRR packs a resource record rr into msg[off:].
  520. // See PackDomainName for documentation about the compression.
  521. func PackRR(rr RR, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
  522. headerEnd, off1, err := packRR(rr, msg, off, compressionMap{ext: compression}, compress)
  523. if err == nil {
  524. // packRR no longer sets the Rdlength field on the rr, but
  525. // callers might be expecting it so we set it here.
  526. rr.Header().Rdlength = uint16(off1 - headerEnd)
  527. }
  528. return off1, err
  529. }
  530. func packRR(rr RR, msg []byte, off int, compression compressionMap, compress bool) (headerEnd int, off1 int, err error) {
  531. if rr == nil {
  532. return len(msg), len(msg), &Error{err: "nil rr"}
  533. }
  534. headerEnd, err = rr.Header().packHeader(msg, off, compression, compress)
  535. if err != nil {
  536. return headerEnd, len(msg), err
  537. }
  538. off1, err = rr.pack(msg, headerEnd, compression, compress)
  539. if err != nil {
  540. return headerEnd, len(msg), err
  541. }
  542. rdlength := off1 - headerEnd
  543. if int(uint16(rdlength)) != rdlength { // overflow
  544. return headerEnd, len(msg), ErrRdata
  545. }
  546. // The RDLENGTH field is the last field in the header and we set it here.
  547. binary.BigEndian.PutUint16(msg[headerEnd-2:], uint16(rdlength))
  548. return headerEnd, off1, nil
  549. }
  550. // UnpackRR unpacks msg[off:] into an RR.
  551. func UnpackRR(msg []byte, off int) (rr RR, off1 int, err error) {
  552. h, off, msg, err := unpackHeader(msg, off)
  553. if err != nil {
  554. return nil, len(msg), err
  555. }
  556. return UnpackRRWithHeader(h, msg, off)
  557. }
  558. // UnpackRRWithHeader unpacks the record type specific payload given an existing
  559. // RR_Header.
  560. func UnpackRRWithHeader(h RR_Header, msg []byte, off int) (rr RR, off1 int, err error) {
  561. if newFn, ok := TypeToRR[h.Rrtype]; ok {
  562. rr = newFn()
  563. *rr.Header() = h
  564. } else {
  565. rr = &RFC3597{Hdr: h}
  566. }
  567. if off < 0 || off > len(msg) {
  568. return &h, off, &Error{err: "bad off"}
  569. }
  570. end := off + int(h.Rdlength)
  571. if end < off || end > len(msg) {
  572. return &h, end, &Error{err: "bad rdlength"}
  573. }
  574. if noRdata(h) {
  575. return rr, off, nil
  576. }
  577. off, err = rr.unpack(msg, off)
  578. if err != nil {
  579. return nil, end, err
  580. }
  581. if off != end {
  582. return &h, end, &Error{err: "bad rdlength"}
  583. }
  584. return rr, off, nil
  585. }
  586. // unpackRRslice unpacks msg[off:] into an []RR.
  587. // If we cannot unpack the whole array, then it will return nil
  588. func unpackRRslice(l int, msg []byte, off int) (dst1 []RR, off1 int, err error) {
  589. var r RR
  590. // Don't pre-allocate, l may be under attacker control
  591. var dst []RR
  592. for i := 0; i < l; i++ {
  593. off1 := off
  594. r, off, err = UnpackRR(msg, off)
  595. if err != nil {
  596. off = len(msg)
  597. break
  598. }
  599. // If offset does not increase anymore, l is a lie
  600. if off1 == off {
  601. break
  602. }
  603. dst = append(dst, r)
  604. }
  605. if err != nil && off == len(msg) {
  606. dst = nil
  607. }
  608. return dst, off, err
  609. }
  610. // Convert a MsgHdr to a string, with dig-like headers:
  611. //
  612. //;; opcode: QUERY, status: NOERROR, id: 48404
  613. //
  614. //;; flags: qr aa rd ra;
  615. func (h *MsgHdr) String() string {
  616. if h == nil {
  617. return "<nil> MsgHdr"
  618. }
  619. s := ";; opcode: " + OpcodeToString[h.Opcode]
  620. s += ", status: " + RcodeToString[h.Rcode]
  621. s += ", id: " + strconv.Itoa(int(h.Id)) + "\n"
  622. s += ";; flags:"
  623. if h.Response {
  624. s += " qr"
  625. }
  626. if h.Authoritative {
  627. s += " aa"
  628. }
  629. if h.Truncated {
  630. s += " tc"
  631. }
  632. if h.RecursionDesired {
  633. s += " rd"
  634. }
  635. if h.RecursionAvailable {
  636. s += " ra"
  637. }
  638. if h.Zero { // Hmm
  639. s += " z"
  640. }
  641. if h.AuthenticatedData {
  642. s += " ad"
  643. }
  644. if h.CheckingDisabled {
  645. s += " cd"
  646. }
  647. s += ";"
  648. return s
  649. }
  650. // Pack packs a Msg: it is converted to to wire format.
  651. // If the dns.Compress is true the message will be in compressed wire format.
  652. func (dns *Msg) Pack() (msg []byte, err error) {
  653. return dns.PackBuffer(nil)
  654. }
  655. // PackBuffer packs a Msg, using the given buffer buf. If buf is too small a new buffer is allocated.
  656. func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error) {
  657. // If this message can't be compressed, avoid filling the
  658. // compression map and creating garbage.
  659. if dns.Compress && dns.isCompressible() {
  660. compression := make(map[string]uint16) // Compression pointer mappings.
  661. return dns.packBufferWithCompressionMap(buf, compressionMap{int: compression}, true)
  662. }
  663. return dns.packBufferWithCompressionMap(buf, compressionMap{}, false)
  664. }
  665. // packBufferWithCompressionMap packs a Msg, using the given buffer buf.
  666. func (dns *Msg) packBufferWithCompressionMap(buf []byte, compression compressionMap, compress bool) (msg []byte, err error) {
  667. if dns.Rcode < 0 || dns.Rcode > 0xFFF {
  668. return nil, ErrRcode
  669. }
  670. // Set extended rcode unconditionally if we have an opt, this will allow
  671. // resetting the extended rcode bits if they need to.
  672. if opt := dns.IsEdns0(); opt != nil {
  673. opt.SetExtendedRcode(uint16(dns.Rcode))
  674. } else if dns.Rcode > 0xF {
  675. // If Rcode is an extended one and opt is nil, error out.
  676. return nil, ErrExtendedRcode
  677. }
  678. // Convert convenient Msg into wire-like Header.
  679. var dh Header
  680. dh.Id = dns.Id
  681. dh.Bits = uint16(dns.Opcode)<<11 | uint16(dns.Rcode&0xF)
  682. if dns.Response {
  683. dh.Bits |= _QR
  684. }
  685. if dns.Authoritative {
  686. dh.Bits |= _AA
  687. }
  688. if dns.Truncated {
  689. dh.Bits |= _TC
  690. }
  691. if dns.RecursionDesired {
  692. dh.Bits |= _RD
  693. }
  694. if dns.RecursionAvailable {
  695. dh.Bits |= _RA
  696. }
  697. if dns.Zero {
  698. dh.Bits |= _Z
  699. }
  700. if dns.AuthenticatedData {
  701. dh.Bits |= _AD
  702. }
  703. if dns.CheckingDisabled {
  704. dh.Bits |= _CD
  705. }
  706. dh.Qdcount = uint16(len(dns.Question))
  707. dh.Ancount = uint16(len(dns.Answer))
  708. dh.Nscount = uint16(len(dns.Ns))
  709. dh.Arcount = uint16(len(dns.Extra))
  710. // We need the uncompressed length here, because we first pack it and then compress it.
  711. msg = buf
  712. uncompressedLen := msgLenWithCompressionMap(dns, nil)
  713. if packLen := uncompressedLen + 1; len(msg) < packLen {
  714. msg = make([]byte, packLen)
  715. }
  716. // Pack it in: header and then the pieces.
  717. off := 0
  718. off, err = dh.pack(msg, off, compression, compress)
  719. if err != nil {
  720. return nil, err
  721. }
  722. for _, r := range dns.Question {
  723. off, err = r.pack(msg, off, compression, compress)
  724. if err != nil {
  725. return nil, err
  726. }
  727. }
  728. for _, r := range dns.Answer {
  729. _, off, err = packRR(r, msg, off, compression, compress)
  730. if err != nil {
  731. return nil, err
  732. }
  733. }
  734. for _, r := range dns.Ns {
  735. _, off, err = packRR(r, msg, off, compression, compress)
  736. if err != nil {
  737. return nil, err
  738. }
  739. }
  740. for _, r := range dns.Extra {
  741. _, off, err = packRR(r, msg, off, compression, compress)
  742. if err != nil {
  743. return nil, err
  744. }
  745. }
  746. return msg[:off], nil
  747. }
  748. func (dns *Msg) unpack(dh Header, msg []byte, off int) (err error) {
  749. // If we are at the end of the message we should return *just* the
  750. // header. This can still be useful to the caller. 9.9.9.9 sends these
  751. // when responding with REFUSED for instance.
  752. if off == len(msg) {
  753. // reset sections before returning
  754. dns.Question, dns.Answer, dns.Ns, dns.Extra = nil, nil, nil, nil
  755. return nil
  756. }
  757. // Qdcount, Ancount, Nscount, Arcount can't be trusted, as they are
  758. // attacker controlled. This means we can't use them to pre-allocate
  759. // slices.
  760. dns.Question = nil
  761. for i := 0; i < int(dh.Qdcount); i++ {
  762. off1 := off
  763. var q Question
  764. q, off, err = unpackQuestion(msg, off)
  765. if err != nil {
  766. return err
  767. }
  768. if off1 == off { // Offset does not increase anymore, dh.Qdcount is a lie!
  769. dh.Qdcount = uint16(i)
  770. break
  771. }
  772. dns.Question = append(dns.Question, q)
  773. }
  774. dns.Answer, off, err = unpackRRslice(int(dh.Ancount), msg, off)
  775. // The header counts might have been wrong so we need to update it
  776. dh.Ancount = uint16(len(dns.Answer))
  777. if err == nil {
  778. dns.Ns, off, err = unpackRRslice(int(dh.Nscount), msg, off)
  779. }
  780. // The header counts might have been wrong so we need to update it
  781. dh.Nscount = uint16(len(dns.Ns))
  782. if err == nil {
  783. dns.Extra, off, err = unpackRRslice(int(dh.Arcount), msg, off)
  784. }
  785. // The header counts might have been wrong so we need to update it
  786. dh.Arcount = uint16(len(dns.Extra))
  787. // Set extended Rcode
  788. if opt := dns.IsEdns0(); opt != nil {
  789. dns.Rcode |= opt.ExtendedRcode()
  790. }
  791. if off != len(msg) {
  792. // TODO(miek) make this an error?
  793. // use PackOpt to let people tell how detailed the error reporting should be?
  794. // println("dns: extra bytes in dns packet", off, "<", len(msg))
  795. }
  796. return err
  797. }
  798. // Unpack unpacks a binary message to a Msg structure.
  799. func (dns *Msg) Unpack(msg []byte) (err error) {
  800. dh, off, err := unpackMsgHdr(msg, 0)
  801. if err != nil {
  802. return err
  803. }
  804. dns.setHdr(dh)
  805. return dns.unpack(dh, msg, off)
  806. }
  807. // Convert a complete message to a string with dig-like output.
  808. func (dns *Msg) String() string {
  809. if dns == nil {
  810. return "<nil> MsgHdr"
  811. }
  812. s := dns.MsgHdr.String() + " "
  813. s += "QUERY: " + strconv.Itoa(len(dns.Question)) + ", "
  814. s += "ANSWER: " + strconv.Itoa(len(dns.Answer)) + ", "
  815. s += "AUTHORITY: " + strconv.Itoa(len(dns.Ns)) + ", "
  816. s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n"
  817. opt := dns.IsEdns0()
  818. if opt != nil {
  819. // OPT PSEUDOSECTION
  820. s += opt.String() + "\n"
  821. }
  822. if len(dns.Question) > 0 {
  823. s += "\n;; QUESTION SECTION:\n"
  824. for _, r := range dns.Question {
  825. s += r.String() + "\n"
  826. }
  827. }
  828. if len(dns.Answer) > 0 {
  829. s += "\n;; ANSWER SECTION:\n"
  830. for _, r := range dns.Answer {
  831. if r != nil {
  832. s += r.String() + "\n"
  833. }
  834. }
  835. }
  836. if len(dns.Ns) > 0 {
  837. s += "\n;; AUTHORITY SECTION:\n"
  838. for _, r := range dns.Ns {
  839. if r != nil {
  840. s += r.String() + "\n"
  841. }
  842. }
  843. }
  844. if len(dns.Extra) > 0 && (opt == nil || len(dns.Extra) > 1) {
  845. s += "\n;; ADDITIONAL SECTION:\n"
  846. for _, r := range dns.Extra {
  847. if r != nil && r.Header().Rrtype != TypeOPT {
  848. s += r.String() + "\n"
  849. }
  850. }
  851. }
  852. return s
  853. }
  854. // isCompressible returns whether the msg may be compressible.
  855. func (dns *Msg) isCompressible() bool {
  856. // If we only have one question, there is nothing we can ever compress.
  857. return len(dns.Question) > 1 || len(dns.Answer) > 0 ||
  858. len(dns.Ns) > 0 || len(dns.Extra) > 0
  859. }
  860. // Len returns the message length when in (un)compressed wire format.
  861. // If dns.Compress is true compression it is taken into account. Len()
  862. // is provided to be a faster way to get the size of the resulting packet,
  863. // than packing it, measuring the size and discarding the buffer.
  864. func (dns *Msg) Len() int {
  865. // If this message can't be compressed, avoid filling the
  866. // compression map and creating garbage.
  867. if dns.Compress && dns.isCompressible() {
  868. compression := make(map[string]struct{})
  869. return msgLenWithCompressionMap(dns, compression)
  870. }
  871. return msgLenWithCompressionMap(dns, nil)
  872. }
  873. func msgLenWithCompressionMap(dns *Msg, compression map[string]struct{}) int {
  874. l := headerSize
  875. for _, r := range dns.Question {
  876. l += r.len(l, compression)
  877. }
  878. for _, r := range dns.Answer {
  879. if r != nil {
  880. l += r.len(l, compression)
  881. }
  882. }
  883. for _, r := range dns.Ns {
  884. if r != nil {
  885. l += r.len(l, compression)
  886. }
  887. }
  888. for _, r := range dns.Extra {
  889. if r != nil {
  890. l += r.len(l, compression)
  891. }
  892. }
  893. return l
  894. }
  895. func domainNameLen(s string, off int, compression map[string]struct{}, compress bool) int {
  896. if s == "" || s == "." {
  897. return 1
  898. }
  899. escaped := strings.Contains(s, "\\")
  900. if compression != nil && (compress || off < maxCompressionOffset) {
  901. // compressionLenSearch will insert the entry into the compression
  902. // map if it doesn't contain it.
  903. if l, ok := compressionLenSearch(compression, s, off); ok && compress {
  904. if escaped {
  905. return escapedNameLen(s[:l]) + 2
  906. }
  907. return l + 2
  908. }
  909. }
  910. if escaped {
  911. return escapedNameLen(s) + 1
  912. }
  913. return len(s) + 1
  914. }
  915. func escapedNameLen(s string) int {
  916. nameLen := len(s)
  917. for i := 0; i < len(s); i++ {
  918. if s[i] != '\\' {
  919. continue
  920. }
  921. if i+3 < len(s) && isDigit(s[i+1]) && isDigit(s[i+2]) && isDigit(s[i+3]) {
  922. nameLen -= 3
  923. i += 3
  924. } else {
  925. nameLen--
  926. i++
  927. }
  928. }
  929. return nameLen
  930. }
  931. func compressionLenSearch(c map[string]struct{}, s string, msgOff int) (int, bool) {
  932. for off, end := 0, false; !end; off, end = NextLabel(s, off) {
  933. if _, ok := c[s[off:]]; ok {
  934. return off, true
  935. }
  936. if msgOff+off < maxCompressionOffset {
  937. c[s[off:]] = struct{}{}
  938. }
  939. }
  940. return 0, false
  941. }
  942. // Copy returns a new RR which is a deep-copy of r.
  943. func Copy(r RR) RR { return r.copy() }
  944. // Len returns the length (in octets) of the uncompressed RR in wire format.
  945. func Len(r RR) int { return r.len(0, nil) }
  946. // Copy returns a new *Msg which is a deep-copy of dns.
  947. func (dns *Msg) Copy() *Msg { return dns.CopyTo(new(Msg)) }
  948. // CopyTo copies the contents to the provided message using a deep-copy and returns the copy.
  949. func (dns *Msg) CopyTo(r1 *Msg) *Msg {
  950. r1.MsgHdr = dns.MsgHdr
  951. r1.Compress = dns.Compress
  952. if len(dns.Question) > 0 {
  953. r1.Question = make([]Question, len(dns.Question))
  954. copy(r1.Question, dns.Question) // TODO(miek): Question is an immutable value, ok to do a shallow-copy
  955. }
  956. rrArr := make([]RR, len(dns.Answer)+len(dns.Ns)+len(dns.Extra))
  957. r1.Answer, rrArr = rrArr[:0:len(dns.Answer)], rrArr[len(dns.Answer):]
  958. r1.Ns, rrArr = rrArr[:0:len(dns.Ns)], rrArr[len(dns.Ns):]
  959. r1.Extra = rrArr[:0:len(dns.Extra)]
  960. for _, r := range dns.Answer {
  961. r1.Answer = append(r1.Answer, r.copy())
  962. }
  963. for _, r := range dns.Ns {
  964. r1.Ns = append(r1.Ns, r.copy())
  965. }
  966. for _, r := range dns.Extra {
  967. r1.Extra = append(r1.Extra, r.copy())
  968. }
  969. return r1
  970. }
  971. func (q *Question) pack(msg []byte, off int, compression compressionMap, compress bool) (int, error) {
  972. off, err := packDomainName(q.Name, msg, off, compression, compress)
  973. if err != nil {
  974. return off, err
  975. }
  976. off, err = packUint16(q.Qtype, msg, off)
  977. if err != nil {
  978. return off, err
  979. }
  980. off, err = packUint16(q.Qclass, msg, off)
  981. if err != nil {
  982. return off, err
  983. }
  984. return off, nil
  985. }
  986. func unpackQuestion(msg []byte, off int) (Question, int, error) {
  987. var (
  988. q Question
  989. err error
  990. )
  991. q.Name, off, err = UnpackDomainName(msg, off)
  992. if err != nil {
  993. return q, off, err
  994. }
  995. if off == len(msg) {
  996. return q, off, nil
  997. }
  998. q.Qtype, off, err = unpackUint16(msg, off)
  999. if err != nil {
  1000. return q, off, err
  1001. }
  1002. if off == len(msg) {
  1003. return q, off, nil
  1004. }
  1005. q.Qclass, off, err = unpackUint16(msg, off)
  1006. if off == len(msg) {
  1007. return q, off, nil
  1008. }
  1009. return q, off, err
  1010. }
  1011. func (dh *Header) pack(msg []byte, off int, compression compressionMap, compress bool) (int, error) {
  1012. off, err := packUint16(dh.Id, msg, off)
  1013. if err != nil {
  1014. return off, err
  1015. }
  1016. off, err = packUint16(dh.Bits, msg, off)
  1017. if err != nil {
  1018. return off, err
  1019. }
  1020. off, err = packUint16(dh.Qdcount, msg, off)
  1021. if err != nil {
  1022. return off, err
  1023. }
  1024. off, err = packUint16(dh.Ancount, msg, off)
  1025. if err != nil {
  1026. return off, err
  1027. }
  1028. off, err = packUint16(dh.Nscount, msg, off)
  1029. if err != nil {
  1030. return off, err
  1031. }
  1032. off, err = packUint16(dh.Arcount, msg, off)
  1033. if err != nil {
  1034. return off, err
  1035. }
  1036. return off, nil
  1037. }
  1038. func unpackMsgHdr(msg []byte, off int) (Header, int, error) {
  1039. var (
  1040. dh Header
  1041. err error
  1042. )
  1043. dh.Id, off, err = unpackUint16(msg, off)
  1044. if err != nil {
  1045. return dh, off, err
  1046. }
  1047. dh.Bits, off, err = unpackUint16(msg, off)
  1048. if err != nil {
  1049. return dh, off, err
  1050. }
  1051. dh.Qdcount, off, err = unpackUint16(msg, off)
  1052. if err != nil {
  1053. return dh, off, err
  1054. }
  1055. dh.Ancount, off, err = unpackUint16(msg, off)
  1056. if err != nil {
  1057. return dh, off, err
  1058. }
  1059. dh.Nscount, off, err = unpackUint16(msg, off)
  1060. if err != nil {
  1061. return dh, off, err
  1062. }
  1063. dh.Arcount, off, err = unpackUint16(msg, off)
  1064. if err != nil {
  1065. return dh, off, err
  1066. }
  1067. return dh, off, nil
  1068. }
  1069. // setHdr set the header in the dns using the binary data in dh.
  1070. func (dns *Msg) setHdr(dh Header) {
  1071. dns.Id = dh.Id
  1072. dns.Response = dh.Bits&_QR != 0
  1073. dns.Opcode = int(dh.Bits>>11) & 0xF
  1074. dns.Authoritative = dh.Bits&_AA != 0
  1075. dns.Truncated = dh.Bits&_TC != 0
  1076. dns.RecursionDesired = dh.Bits&_RD != 0
  1077. dns.RecursionAvailable = dh.Bits&_RA != 0
  1078. dns.Zero = dh.Bits&_Z != 0 // _Z covers the zero bit, which should be zero; not sure why we set it to the opposite.
  1079. dns.AuthenticatedData = dh.Bits&_AD != 0
  1080. dns.CheckingDisabled = dh.Bits&_CD != 0
  1081. dns.Rcode = int(dh.Bits & 0xF)
  1082. }