msg.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  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 isDDD(bs[i+1:]) {
  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) (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. offset, err = packTxtString(s, msg, offset)
  414. if err != nil {
  415. return offset, err
  416. }
  417. }
  418. return offset, nil
  419. }
  420. func packTxtString(s string, msg []byte, offset int) (int, error) {
  421. lenByteOffset := offset
  422. if offset >= len(msg) || len(s) > 256*4+1 /* If all \DDD */ {
  423. return offset, ErrBuf
  424. }
  425. offset++
  426. for i := 0; i < len(s); i++ {
  427. if len(msg) <= offset {
  428. return offset, ErrBuf
  429. }
  430. if s[i] == '\\' {
  431. i++
  432. if i == len(s) {
  433. break
  434. }
  435. // check for \DDD
  436. if isDDD(s[i:]) {
  437. msg[offset] = dddToByte(s[i:])
  438. i += 2
  439. } else {
  440. msg[offset] = s[i]
  441. }
  442. } else {
  443. msg[offset] = s[i]
  444. }
  445. offset++
  446. }
  447. l := offset - lenByteOffset - 1
  448. if l > 255 {
  449. return offset, &Error{err: "string exceeded 255 bytes in txt"}
  450. }
  451. msg[lenByteOffset] = byte(l)
  452. return offset, nil
  453. }
  454. func packOctetString(s string, msg []byte, offset int, tmp []byte) (int, error) {
  455. if offset >= len(msg) || len(s) > len(tmp) {
  456. return offset, ErrBuf
  457. }
  458. bs := tmp[:len(s)]
  459. copy(bs, s)
  460. for i := 0; i < len(bs); i++ {
  461. if len(msg) <= offset {
  462. return offset, ErrBuf
  463. }
  464. if bs[i] == '\\' {
  465. i++
  466. if i == len(bs) {
  467. break
  468. }
  469. // check for \DDD
  470. if isDDD(bs[i:]) {
  471. msg[offset] = dddToByte(bs[i:])
  472. i += 2
  473. } else {
  474. msg[offset] = bs[i]
  475. }
  476. } else {
  477. msg[offset] = bs[i]
  478. }
  479. offset++
  480. }
  481. return offset, nil
  482. }
  483. func unpackTxt(msg []byte, off0 int) (ss []string, off int, err error) {
  484. off = off0
  485. var s string
  486. for off < len(msg) && err == nil {
  487. s, off, err = unpackString(msg, off)
  488. if err == nil {
  489. ss = append(ss, s)
  490. }
  491. }
  492. return
  493. }
  494. // Helpers for dealing with escaped bytes
  495. func isDigit(b byte) bool { return b >= '0' && b <= '9' }
  496. func isDDD[T ~[]byte | ~string](s T) bool {
  497. return len(s) >= 3 && isDigit(s[0]) && isDigit(s[1]) && isDigit(s[2])
  498. }
  499. func dddToByte[T ~[]byte | ~string](s T) byte {
  500. _ = s[2] // bounds check hint to compiler; see golang.org/issue/14808
  501. return byte((s[0]-'0')*100 + (s[1]-'0')*10 + (s[2] - '0'))
  502. }
  503. // Helper function for packing and unpacking
  504. func intToBytes(i *big.Int, length int) []byte {
  505. buf := i.Bytes()
  506. if len(buf) < length {
  507. b := make([]byte, length)
  508. copy(b[length-len(buf):], buf)
  509. return b
  510. }
  511. return buf
  512. }
  513. // PackRR packs a resource record rr into msg[off:].
  514. // See PackDomainName for documentation about the compression.
  515. func PackRR(rr RR, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
  516. headerEnd, off1, err := packRR(rr, msg, off, compressionMap{ext: compression}, compress)
  517. if err == nil {
  518. // packRR no longer sets the Rdlength field on the rr, but
  519. // callers might be expecting it so we set it here.
  520. rr.Header().Rdlength = uint16(off1 - headerEnd)
  521. }
  522. return off1, err
  523. }
  524. func packRR(rr RR, msg []byte, off int, compression compressionMap, compress bool) (headerEnd int, off1 int, err error) {
  525. if rr == nil {
  526. return len(msg), len(msg), &Error{err: "nil rr"}
  527. }
  528. headerEnd, err = rr.Header().packHeader(msg, off, compression, compress)
  529. if err != nil {
  530. return headerEnd, len(msg), err
  531. }
  532. off1, err = rr.pack(msg, headerEnd, compression, compress)
  533. if err != nil {
  534. return headerEnd, len(msg), err
  535. }
  536. rdlength := off1 - headerEnd
  537. if int(uint16(rdlength)) != rdlength { // overflow
  538. return headerEnd, len(msg), ErrRdata
  539. }
  540. // The RDLENGTH field is the last field in the header and we set it here.
  541. binary.BigEndian.PutUint16(msg[headerEnd-2:], uint16(rdlength))
  542. return headerEnd, off1, nil
  543. }
  544. // UnpackRR unpacks msg[off:] into an RR.
  545. func UnpackRR(msg []byte, off int) (rr RR, off1 int, err error) {
  546. h, off, msg, err := unpackHeader(msg, off)
  547. if err != nil {
  548. return nil, len(msg), err
  549. }
  550. return UnpackRRWithHeader(h, msg, off)
  551. }
  552. // UnpackRRWithHeader unpacks the record type specific payload given an existing
  553. // RR_Header.
  554. func UnpackRRWithHeader(h RR_Header, msg []byte, off int) (rr RR, off1 int, err error) {
  555. if newFn, ok := TypeToRR[h.Rrtype]; ok {
  556. rr = newFn()
  557. *rr.Header() = h
  558. } else {
  559. rr = &RFC3597{Hdr: h}
  560. }
  561. if off < 0 || off > len(msg) {
  562. return &h, off, &Error{err: "bad off"}
  563. }
  564. end := off + int(h.Rdlength)
  565. if end < off || end > len(msg) {
  566. return &h, end, &Error{err: "bad rdlength"}
  567. }
  568. if noRdata(h) {
  569. return rr, off, nil
  570. }
  571. off, err = rr.unpack(msg, off)
  572. if err != nil {
  573. return nil, end, err
  574. }
  575. if off != end {
  576. return &h, end, &Error{err: "bad rdlength"}
  577. }
  578. return rr, off, nil
  579. }
  580. // unpackRRslice unpacks msg[off:] into an []RR.
  581. // If we cannot unpack the whole array, then it will return nil
  582. func unpackRRslice(l int, msg []byte, off int) (dst1 []RR, off1 int, err error) {
  583. var r RR
  584. // Don't pre-allocate, l may be under attacker control
  585. var dst []RR
  586. for i := 0; i < l; i++ {
  587. off1 := off
  588. r, off, err = UnpackRR(msg, off)
  589. if err != nil {
  590. off = len(msg)
  591. break
  592. }
  593. // If offset does not increase anymore, l is a lie
  594. if off1 == off {
  595. break
  596. }
  597. dst = append(dst, r)
  598. }
  599. if err != nil && off == len(msg) {
  600. dst = nil
  601. }
  602. return dst, off, err
  603. }
  604. // Convert a MsgHdr to a string, with dig-like headers:
  605. //
  606. // ;; opcode: QUERY, status: NOERROR, id: 48404
  607. //
  608. // ;; flags: qr aa rd ra;
  609. func (h *MsgHdr) String() string {
  610. if h == nil {
  611. return "<nil> MsgHdr"
  612. }
  613. s := ";; opcode: " + OpcodeToString[h.Opcode]
  614. s += ", status: " + RcodeToString[h.Rcode]
  615. s += ", id: " + strconv.Itoa(int(h.Id)) + "\n"
  616. s += ";; flags:"
  617. if h.Response {
  618. s += " qr"
  619. }
  620. if h.Authoritative {
  621. s += " aa"
  622. }
  623. if h.Truncated {
  624. s += " tc"
  625. }
  626. if h.RecursionDesired {
  627. s += " rd"
  628. }
  629. if h.RecursionAvailable {
  630. s += " ra"
  631. }
  632. if h.Zero { // Hmm
  633. s += " z"
  634. }
  635. if h.AuthenticatedData {
  636. s += " ad"
  637. }
  638. if h.CheckingDisabled {
  639. s += " cd"
  640. }
  641. s += ";"
  642. return s
  643. }
  644. // Pack packs a Msg: it is converted to to wire format.
  645. // If the dns.Compress is true the message will be in compressed wire format.
  646. func (dns *Msg) Pack() (msg []byte, err error) {
  647. return dns.PackBuffer(nil)
  648. }
  649. // PackBuffer packs a Msg, using the given buffer buf. If buf is too small a new buffer is allocated.
  650. func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error) {
  651. // If this message can't be compressed, avoid filling the
  652. // compression map and creating garbage.
  653. if dns.Compress && dns.isCompressible() {
  654. compression := make(map[string]uint16) // Compression pointer mappings.
  655. return dns.packBufferWithCompressionMap(buf, compressionMap{int: compression}, true)
  656. }
  657. return dns.packBufferWithCompressionMap(buf, compressionMap{}, false)
  658. }
  659. // packBufferWithCompressionMap packs a Msg, using the given buffer buf.
  660. func (dns *Msg) packBufferWithCompressionMap(buf []byte, compression compressionMap, compress bool) (msg []byte, err error) {
  661. if dns.Rcode < 0 || dns.Rcode > 0xFFF {
  662. return nil, ErrRcode
  663. }
  664. // Set extended rcode unconditionally if we have an opt, this will allow
  665. // resetting the extended rcode bits if they need to.
  666. if opt := dns.IsEdns0(); opt != nil {
  667. opt.SetExtendedRcode(uint16(dns.Rcode))
  668. } else if dns.Rcode > 0xF {
  669. // If Rcode is an extended one and opt is nil, error out.
  670. return nil, ErrExtendedRcode
  671. }
  672. // Convert convenient Msg into wire-like Header.
  673. var dh Header
  674. dh.Id = dns.Id
  675. dh.Bits = uint16(dns.Opcode)<<11 | uint16(dns.Rcode&0xF)
  676. if dns.Response {
  677. dh.Bits |= _QR
  678. }
  679. if dns.Authoritative {
  680. dh.Bits |= _AA
  681. }
  682. if dns.Truncated {
  683. dh.Bits |= _TC
  684. }
  685. if dns.RecursionDesired {
  686. dh.Bits |= _RD
  687. }
  688. if dns.RecursionAvailable {
  689. dh.Bits |= _RA
  690. }
  691. if dns.Zero {
  692. dh.Bits |= _Z
  693. }
  694. if dns.AuthenticatedData {
  695. dh.Bits |= _AD
  696. }
  697. if dns.CheckingDisabled {
  698. dh.Bits |= _CD
  699. }
  700. dh.Qdcount = uint16(len(dns.Question))
  701. dh.Ancount = uint16(len(dns.Answer))
  702. dh.Nscount = uint16(len(dns.Ns))
  703. dh.Arcount = uint16(len(dns.Extra))
  704. // We need the uncompressed length here, because we first pack it and then compress it.
  705. msg = buf
  706. uncompressedLen := msgLenWithCompressionMap(dns, nil)
  707. if packLen := uncompressedLen + 1; len(msg) < packLen {
  708. msg = make([]byte, packLen)
  709. }
  710. // Pack it in: header and then the pieces.
  711. off := 0
  712. off, err = dh.pack(msg, off, compression, compress)
  713. if err != nil {
  714. return nil, err
  715. }
  716. for _, r := range dns.Question {
  717. off, err = r.pack(msg, off, compression, compress)
  718. if err != nil {
  719. return nil, err
  720. }
  721. }
  722. for _, r := range dns.Answer {
  723. _, off, err = packRR(r, msg, off, compression, compress)
  724. if err != nil {
  725. return nil, err
  726. }
  727. }
  728. for _, r := range dns.Ns {
  729. _, off, err = packRR(r, msg, off, compression, compress)
  730. if err != nil {
  731. return nil, err
  732. }
  733. }
  734. for _, r := range dns.Extra {
  735. _, off, err = packRR(r, msg, off, compression, compress)
  736. if err != nil {
  737. return nil, err
  738. }
  739. }
  740. return msg[:off], nil
  741. }
  742. func (dns *Msg) unpack(dh Header, msg []byte, off int) (err error) {
  743. // If we are at the end of the message we should return *just* the
  744. // header. This can still be useful to the caller. 9.9.9.9 sends these
  745. // when responding with REFUSED for instance.
  746. if off == len(msg) {
  747. // reset sections before returning
  748. dns.Question, dns.Answer, dns.Ns, dns.Extra = nil, nil, nil, nil
  749. return nil
  750. }
  751. // Qdcount, Ancount, Nscount, Arcount can't be trusted, as they are
  752. // attacker controlled. This means we can't use them to pre-allocate
  753. // slices.
  754. dns.Question = nil
  755. for i := 0; i < int(dh.Qdcount); i++ {
  756. off1 := off
  757. var q Question
  758. q, off, err = unpackQuestion(msg, off)
  759. if err != nil {
  760. return err
  761. }
  762. if off1 == off { // Offset does not increase anymore, dh.Qdcount is a lie!
  763. dh.Qdcount = uint16(i)
  764. break
  765. }
  766. dns.Question = append(dns.Question, q)
  767. }
  768. dns.Answer, off, err = unpackRRslice(int(dh.Ancount), msg, off)
  769. // The header counts might have been wrong so we need to update it
  770. dh.Ancount = uint16(len(dns.Answer))
  771. if err == nil {
  772. dns.Ns, off, err = unpackRRslice(int(dh.Nscount), msg, off)
  773. }
  774. // The header counts might have been wrong so we need to update it
  775. dh.Nscount = uint16(len(dns.Ns))
  776. if err == nil {
  777. dns.Extra, _, err = unpackRRslice(int(dh.Arcount), msg, off)
  778. }
  779. // The header counts might have been wrong so we need to update it
  780. dh.Arcount = uint16(len(dns.Extra))
  781. // Set extended Rcode
  782. if opt := dns.IsEdns0(); opt != nil {
  783. dns.Rcode |= opt.ExtendedRcode()
  784. }
  785. // TODO(miek) make this an error?
  786. // use PackOpt to let people tell how detailed the error reporting should be?
  787. // if off != len(msg) {
  788. // // println("dns: extra bytes in dns packet", off, "<", len(msg))
  789. // }
  790. return err
  791. }
  792. // Unpack unpacks a binary message to a Msg structure.
  793. func (dns *Msg) Unpack(msg []byte) (err error) {
  794. dh, off, err := unpackMsgHdr(msg, 0)
  795. if err != nil {
  796. return err
  797. }
  798. dns.setHdr(dh)
  799. return dns.unpack(dh, msg, off)
  800. }
  801. // Convert a complete message to a string with dig-like output.
  802. func (dns *Msg) String() string {
  803. if dns == nil {
  804. return "<nil> MsgHdr"
  805. }
  806. s := dns.MsgHdr.String() + " "
  807. if dns.MsgHdr.Opcode == OpcodeUpdate {
  808. s += "ZONE: " + strconv.Itoa(len(dns.Question)) + ", "
  809. s += "PREREQ: " + strconv.Itoa(len(dns.Answer)) + ", "
  810. s += "UPDATE: " + strconv.Itoa(len(dns.Ns)) + ", "
  811. s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n"
  812. } else {
  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. }
  818. opt := dns.IsEdns0()
  819. if opt != nil {
  820. // OPT PSEUDOSECTION
  821. s += opt.String() + "\n"
  822. }
  823. if len(dns.Question) > 0 {
  824. if dns.MsgHdr.Opcode == OpcodeUpdate {
  825. s += "\n;; ZONE SECTION:\n"
  826. } else {
  827. s += "\n;; QUESTION SECTION:\n"
  828. }
  829. for _, r := range dns.Question {
  830. s += r.String() + "\n"
  831. }
  832. }
  833. if len(dns.Answer) > 0 {
  834. if dns.MsgHdr.Opcode == OpcodeUpdate {
  835. s += "\n;; PREREQUISITE SECTION:\n"
  836. } else {
  837. s += "\n;; ANSWER SECTION:\n"
  838. }
  839. for _, r := range dns.Answer {
  840. if r != nil {
  841. s += r.String() + "\n"
  842. }
  843. }
  844. }
  845. if len(dns.Ns) > 0 {
  846. if dns.MsgHdr.Opcode == OpcodeUpdate {
  847. s += "\n;; UPDATE SECTION:\n"
  848. } else {
  849. s += "\n;; AUTHORITY SECTION:\n"
  850. }
  851. for _, r := range dns.Ns {
  852. if r != nil {
  853. s += r.String() + "\n"
  854. }
  855. }
  856. }
  857. if len(dns.Extra) > 0 && (opt == nil || len(dns.Extra) > 1) {
  858. s += "\n;; ADDITIONAL SECTION:\n"
  859. for _, r := range dns.Extra {
  860. if r != nil && r.Header().Rrtype != TypeOPT {
  861. s += r.String() + "\n"
  862. }
  863. }
  864. }
  865. return s
  866. }
  867. // isCompressible returns whether the msg may be compressible.
  868. func (dns *Msg) isCompressible() bool {
  869. // If we only have one question, there is nothing we can ever compress.
  870. return len(dns.Question) > 1 || len(dns.Answer) > 0 ||
  871. len(dns.Ns) > 0 || len(dns.Extra) > 0
  872. }
  873. // Len returns the message length when in (un)compressed wire format.
  874. // If dns.Compress is true compression it is taken into account. Len()
  875. // is provided to be a faster way to get the size of the resulting packet,
  876. // than packing it, measuring the size and discarding the buffer.
  877. func (dns *Msg) Len() int {
  878. // If this message can't be compressed, avoid filling the
  879. // compression map and creating garbage.
  880. if dns.Compress && dns.isCompressible() {
  881. compression := make(map[string]struct{})
  882. return msgLenWithCompressionMap(dns, compression)
  883. }
  884. return msgLenWithCompressionMap(dns, nil)
  885. }
  886. func msgLenWithCompressionMap(dns *Msg, compression map[string]struct{}) int {
  887. l := headerSize
  888. for _, r := range dns.Question {
  889. l += r.len(l, compression)
  890. }
  891. for _, r := range dns.Answer {
  892. if r != nil {
  893. l += r.len(l, compression)
  894. }
  895. }
  896. for _, r := range dns.Ns {
  897. if r != nil {
  898. l += r.len(l, compression)
  899. }
  900. }
  901. for _, r := range dns.Extra {
  902. if r != nil {
  903. l += r.len(l, compression)
  904. }
  905. }
  906. return l
  907. }
  908. func domainNameLen(s string, off int, compression map[string]struct{}, compress bool) int {
  909. if s == "" || s == "." {
  910. return 1
  911. }
  912. escaped := strings.Contains(s, "\\")
  913. if compression != nil && (compress || off < maxCompressionOffset) {
  914. // compressionLenSearch will insert the entry into the compression
  915. // map if it doesn't contain it.
  916. if l, ok := compressionLenSearch(compression, s, off); ok && compress {
  917. if escaped {
  918. return escapedNameLen(s[:l]) + 2
  919. }
  920. return l + 2
  921. }
  922. }
  923. if escaped {
  924. return escapedNameLen(s) + 1
  925. }
  926. return len(s) + 1
  927. }
  928. func escapedNameLen(s string) int {
  929. nameLen := len(s)
  930. for i := 0; i < len(s); i++ {
  931. if s[i] != '\\' {
  932. continue
  933. }
  934. if isDDD(s[i+1:]) {
  935. nameLen -= 3
  936. i += 3
  937. } else {
  938. nameLen--
  939. i++
  940. }
  941. }
  942. return nameLen
  943. }
  944. func compressionLenSearch(c map[string]struct{}, s string, msgOff int) (int, bool) {
  945. for off, end := 0, false; !end; off, end = NextLabel(s, off) {
  946. if _, ok := c[s[off:]]; ok {
  947. return off, true
  948. }
  949. if msgOff+off < maxCompressionOffset {
  950. c[s[off:]] = struct{}{}
  951. }
  952. }
  953. return 0, false
  954. }
  955. // Copy returns a new RR which is a deep-copy of r.
  956. func Copy(r RR) RR { return r.copy() }
  957. // Len returns the length (in octets) of the uncompressed RR in wire format.
  958. func Len(r RR) int { return r.len(0, nil) }
  959. // Copy returns a new *Msg which is a deep-copy of dns.
  960. func (dns *Msg) Copy() *Msg { return dns.CopyTo(new(Msg)) }
  961. // CopyTo copies the contents to the provided message using a deep-copy and returns the copy.
  962. func (dns *Msg) CopyTo(r1 *Msg) *Msg {
  963. r1.MsgHdr = dns.MsgHdr
  964. r1.Compress = dns.Compress
  965. if len(dns.Question) > 0 {
  966. // TODO(miek): Question is an immutable value, ok to do a shallow-copy
  967. r1.Question = cloneSlice(dns.Question)
  968. }
  969. rrArr := make([]RR, len(dns.Answer)+len(dns.Ns)+len(dns.Extra))
  970. r1.Answer, rrArr = rrArr[:0:len(dns.Answer)], rrArr[len(dns.Answer):]
  971. r1.Ns, rrArr = rrArr[:0:len(dns.Ns)], rrArr[len(dns.Ns):]
  972. r1.Extra = rrArr[:0:len(dns.Extra)]
  973. for _, r := range dns.Answer {
  974. r1.Answer = append(r1.Answer, r.copy())
  975. }
  976. for _, r := range dns.Ns {
  977. r1.Ns = append(r1.Ns, r.copy())
  978. }
  979. for _, r := range dns.Extra {
  980. r1.Extra = append(r1.Extra, r.copy())
  981. }
  982. return r1
  983. }
  984. func (q *Question) pack(msg []byte, off int, compression compressionMap, compress bool) (int, error) {
  985. off, err := packDomainName(q.Name, msg, off, compression, compress)
  986. if err != nil {
  987. return off, err
  988. }
  989. off, err = packUint16(q.Qtype, msg, off)
  990. if err != nil {
  991. return off, err
  992. }
  993. off, err = packUint16(q.Qclass, msg, off)
  994. if err != nil {
  995. return off, err
  996. }
  997. return off, nil
  998. }
  999. func unpackQuestion(msg []byte, off int) (Question, int, error) {
  1000. var (
  1001. q Question
  1002. err error
  1003. )
  1004. q.Name, off, err = UnpackDomainName(msg, off)
  1005. if err != nil {
  1006. return q, off, err
  1007. }
  1008. if off == len(msg) {
  1009. return q, off, nil
  1010. }
  1011. q.Qtype, off, err = unpackUint16(msg, off)
  1012. if err != nil {
  1013. return q, off, err
  1014. }
  1015. if off == len(msg) {
  1016. return q, off, nil
  1017. }
  1018. q.Qclass, off, err = unpackUint16(msg, off)
  1019. if off == len(msg) {
  1020. return q, off, nil
  1021. }
  1022. return q, off, err
  1023. }
  1024. func (dh *Header) pack(msg []byte, off int, compression compressionMap, compress bool) (int, error) {
  1025. off, err := packUint16(dh.Id, msg, off)
  1026. if err != nil {
  1027. return off, err
  1028. }
  1029. off, err = packUint16(dh.Bits, msg, off)
  1030. if err != nil {
  1031. return off, err
  1032. }
  1033. off, err = packUint16(dh.Qdcount, msg, off)
  1034. if err != nil {
  1035. return off, err
  1036. }
  1037. off, err = packUint16(dh.Ancount, msg, off)
  1038. if err != nil {
  1039. return off, err
  1040. }
  1041. off, err = packUint16(dh.Nscount, msg, off)
  1042. if err != nil {
  1043. return off, err
  1044. }
  1045. off, err = packUint16(dh.Arcount, msg, off)
  1046. if err != nil {
  1047. return off, err
  1048. }
  1049. return off, nil
  1050. }
  1051. func unpackMsgHdr(msg []byte, off int) (Header, int, error) {
  1052. var (
  1053. dh Header
  1054. err error
  1055. )
  1056. dh.Id, off, err = unpackUint16(msg, off)
  1057. if err != nil {
  1058. return dh, off, err
  1059. }
  1060. dh.Bits, off, err = unpackUint16(msg, off)
  1061. if err != nil {
  1062. return dh, off, err
  1063. }
  1064. dh.Qdcount, off, err = unpackUint16(msg, off)
  1065. if err != nil {
  1066. return dh, off, err
  1067. }
  1068. dh.Ancount, off, err = unpackUint16(msg, off)
  1069. if err != nil {
  1070. return dh, off, err
  1071. }
  1072. dh.Nscount, off, err = unpackUint16(msg, off)
  1073. if err != nil {
  1074. return dh, off, err
  1075. }
  1076. dh.Arcount, off, err = unpackUint16(msg, off)
  1077. if err != nil {
  1078. return dh, off, err
  1079. }
  1080. return dh, off, nil
  1081. }
  1082. // setHdr set the header in the dns using the binary data in dh.
  1083. func (dns *Msg) setHdr(dh Header) {
  1084. dns.Id = dh.Id
  1085. dns.Response = dh.Bits&_QR != 0
  1086. dns.Opcode = int(dh.Bits>>11) & 0xF
  1087. dns.Authoritative = dh.Bits&_AA != 0
  1088. dns.Truncated = dh.Bits&_TC != 0
  1089. dns.RecursionDesired = dh.Bits&_RD != 0
  1090. dns.RecursionAvailable = dh.Bits&_RA != 0
  1091. dns.Zero = dh.Bits&_Z != 0 // _Z covers the zero bit, which should be zero; not sure why we set it to the opposite.
  1092. dns.AuthenticatedData = dh.Bits&_AD != 0
  1093. dns.CheckingDisabled = dh.Bits&_CD != 0
  1094. dns.Rcode = int(dh.Bits & 0xF)
  1095. }