You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

msg.go 32KB

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