doc.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. Package dns implements a full featured interface to the Domain Name System.
  3. Both server- and client-side programming is supported. The package allows
  4. complete control over what is sent out to the DNS. The API follows the
  5. less-is-more principle, by presenting a small, clean interface.
  6. It supports (asynchronous) querying/replying, incoming/outgoing zone transfers,
  7. TSIG, EDNS0, dynamic updates, notifies and DNSSEC validation/signing.
  8. Note that domain names MUST be fully qualified before sending them, unqualified
  9. names in a message will result in a packing failure.
  10. Resource records are native types. They are not stored in wire format. Basic
  11. usage pattern for creating a new resource record:
  12. r := new(dns.MX)
  13. r.Hdr = dns.RR_Header{Name: "miek.nl.", Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: 3600}
  14. r.Preference = 10
  15. r.Mx = "mx.miek.nl."
  16. Or directly from a string:
  17. mx, err := dns.NewRR("miek.nl. 3600 IN MX 10 mx.miek.nl.")
  18. Or when the default origin (.) and TTL (3600) and class (IN) suit you:
  19. mx, err := dns.NewRR("miek.nl MX 10 mx.miek.nl")
  20. Or even:
  21. mx, err := dns.NewRR("$ORIGIN nl.\nmiek 1H IN MX 10 mx.miek")
  22. In the DNS messages are exchanged, these messages contain resource records
  23. (sets). Use pattern for creating a message:
  24. m := new(dns.Msg)
  25. m.SetQuestion("miek.nl.", dns.TypeMX)
  26. Or when not certain if the domain name is fully qualified:
  27. m.SetQuestion(dns.Fqdn("miek.nl"), dns.TypeMX)
  28. The message m is now a message with the question section set to ask the MX
  29. records for the miek.nl. zone.
  30. The following is slightly more verbose, but more flexible:
  31. m1 := new(dns.Msg)
  32. m1.Id = dns.Id()
  33. m1.RecursionDesired = true
  34. m1.Question = make([]dns.Question, 1)
  35. m1.Question[0] = dns.Question{"miek.nl.", dns.TypeMX, dns.ClassINET}
  36. After creating a message it can be sent. Basic use pattern for synchronous
  37. querying the DNS at a server configured on 127.0.0.1 and port 53:
  38. c := new(dns.Client)
  39. in, rtt, err := c.Exchange(m1, "127.0.0.1:53")
  40. Suppressing multiple outstanding queries (with the same question, type and
  41. class) is as easy as setting:
  42. c.SingleInflight = true
  43. More advanced options are available using a net.Dialer and the corresponding API.
  44. For example it is possible to set a timeout, or to specify a source IP address
  45. and port to use for the connection:
  46. c := new(dns.Client)
  47. laddr := net.UDPAddr{
  48. IP: net.ParseIP("[::1]"),
  49. Port: 12345,
  50. Zone: "",
  51. }
  52. c.Dialer := &net.Dialer{
  53. Timeout: 200 * time.Millisecond,
  54. LocalAddr: &laddr,
  55. }
  56. in, rtt, err := c.Exchange(m1, "8.8.8.8:53")
  57. If these "advanced" features are not needed, a simple UDP query can be sent,
  58. with:
  59. in, err := dns.Exchange(m1, "127.0.0.1:53")
  60. When this functions returns you will get DNS message. A DNS message consists
  61. out of four sections.
  62. The question section: in.Question, the answer section: in.Answer,
  63. the authority section: in.Ns and the additional section: in.Extra.
  64. Each of these sections (except the Question section) contain a []RR. Basic
  65. use pattern for accessing the rdata of a TXT RR as the first RR in
  66. the Answer section:
  67. if t, ok := in.Answer[0].(*dns.TXT); ok {
  68. // do something with t.Txt
  69. }
  70. Domain Name and TXT Character String Representations
  71. Both domain names and TXT character strings are converted to presentation form
  72. both when unpacked and when converted to strings.
  73. For TXT character strings, tabs, carriage returns and line feeds will be
  74. converted to \t, \r and \n respectively. Back slashes and quotations marks will
  75. be escaped. Bytes below 32 and above 127 will be converted to \DDD form.
  76. For domain names, in addition to the above rules brackets, periods, spaces,
  77. semicolons and the at symbol are escaped.
  78. DNSSEC
  79. DNSSEC (DNS Security Extension) adds a layer of security to the DNS. It uses
  80. public key cryptography to sign resource records. The public keys are stored in
  81. DNSKEY records and the signatures in RRSIG records.
  82. Requesting DNSSEC information for a zone is done by adding the DO (DNSSEC OK)
  83. bit to a request.
  84. m := new(dns.Msg)
  85. m.SetEdns0(4096, true)
  86. Signature generation, signature verification and key generation are all supported.
  87. DYNAMIC UPDATES
  88. Dynamic updates reuses the DNS message format, but renames three of the
  89. sections. Question is Zone, Answer is Prerequisite, Authority is Update, only
  90. the Additional is not renamed. See RFC 2136 for the gory details.
  91. You can set a rather complex set of rules for the existence of absence of
  92. certain resource records or names in a zone to specify if resource records
  93. should be added or removed. The table from RFC 2136 supplemented with the Go
  94. DNS function shows which functions exist to specify the prerequisites.
  95. 3.2.4 - Table Of Metavalues Used In Prerequisite Section
  96. CLASS TYPE RDATA Meaning Function
  97. --------------------------------------------------------------
  98. ANY ANY empty Name is in use dns.NameUsed
  99. ANY rrset empty RRset exists (value indep) dns.RRsetUsed
  100. NONE ANY empty Name is not in use dns.NameNotUsed
  101. NONE rrset empty RRset does not exist dns.RRsetNotUsed
  102. zone rrset rr RRset exists (value dep) dns.Used
  103. The prerequisite section can also be left empty. If you have decided on the
  104. prerequisites you can tell what RRs should be added or deleted. The next table
  105. shows the options you have and what functions to call.
  106. 3.4.2.6 - Table Of Metavalues Used In Update Section
  107. CLASS TYPE RDATA Meaning Function
  108. ---------------------------------------------------------------
  109. ANY ANY empty Delete all RRsets from name dns.RemoveName
  110. ANY rrset empty Delete an RRset dns.RemoveRRset
  111. NONE rrset rr Delete an RR from RRset dns.Remove
  112. zone rrset rr Add to an RRset dns.Insert
  113. TRANSACTION SIGNATURE
  114. An TSIG or transaction signature adds a HMAC TSIG record to each message sent.
  115. The supported algorithms include: HmacSHA1, HmacSHA256 and HmacSHA512.
  116. Basic use pattern when querying with a TSIG name "axfr." (note that these key names
  117. must be fully qualified - as they are domain names) and the base64 secret
  118. "so6ZGir4GPAqINNh9U5c3A==":
  119. If an incoming message contains a TSIG record it MUST be the last record in
  120. the additional section (RFC2845 3.2). This means that you should make the
  121. call to SetTsig last, right before executing the query. If you make any
  122. changes to the RRset after calling SetTsig() the signature will be incorrect.
  123. c := new(dns.Client)
  124. c.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
  125. m := new(dns.Msg)
  126. m.SetQuestion("miek.nl.", dns.TypeMX)
  127. m.SetTsig("axfr.", dns.HmacSHA256, 300, time.Now().Unix())
  128. ...
  129. // When sending the TSIG RR is calculated and filled in before sending
  130. When requesting an zone transfer (almost all TSIG usage is when requesting zone
  131. transfers), with TSIG, this is the basic use pattern. In this example we
  132. request an AXFR for miek.nl. with TSIG key named "axfr." and secret
  133. "so6ZGir4GPAqINNh9U5c3A==" and using the server 176.58.119.54:
  134. t := new(dns.Transfer)
  135. m := new(dns.Msg)
  136. t.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
  137. m.SetAxfr("miek.nl.")
  138. m.SetTsig("axfr.", dns.HmacSHA256, 300, time.Now().Unix())
  139. c, err := t.In(m, "176.58.119.54:53")
  140. for r := range c { ... }
  141. You can now read the records from the transfer as they come in. Each envelope
  142. is checked with TSIG. If something is not correct an error is returned.
  143. A custom TSIG implementation can be used. This requires additional code to
  144. perform any session establishment and signature generation/verification. The
  145. client must be configured with an implementation of the TsigProvider interface:
  146. type Provider struct{}
  147. func (*Provider) Generate(msg []byte, tsig *dns.TSIG) ([]byte, error) {
  148. // Use tsig.Hdr.Name and tsig.Algorithm in your code to
  149. // generate the MAC using msg as the payload.
  150. }
  151. func (*Provider) Verify(msg []byte, tsig *dns.TSIG) error {
  152. // Use tsig.Hdr.Name and tsig.Algorithm in your code to verify
  153. // that msg matches the value in tsig.MAC.
  154. }
  155. c := new(dns.Client)
  156. c.TsigProvider = new(Provider)
  157. m := new(dns.Msg)
  158. m.SetQuestion("miek.nl.", dns.TypeMX)
  159. m.SetTsig(keyname, dns.HmacSHA256, 300, time.Now().Unix())
  160. ...
  161. // TSIG RR is calculated by calling your Generate method
  162. Basic use pattern validating and replying to a message that has TSIG set.
  163. server := &dns.Server{Addr: ":53", Net: "udp"}
  164. server.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
  165. go server.ListenAndServe()
  166. dns.HandleFunc(".", handleRequest)
  167. func handleRequest(w dns.ResponseWriter, r *dns.Msg) {
  168. m := new(dns.Msg)
  169. m.SetReply(r)
  170. if r.IsTsig() != nil {
  171. if w.TsigStatus() == nil {
  172. // *Msg r has an TSIG record and it was validated
  173. m.SetTsig("axfr.", dns.HmacSHA256, 300, time.Now().Unix())
  174. } else {
  175. // *Msg r has an TSIG records and it was not validated
  176. }
  177. }
  178. w.WriteMsg(m)
  179. }
  180. PRIVATE RRS
  181. RFC 6895 sets aside a range of type codes for private use. This range is 65,280
  182. - 65,534 (0xFF00 - 0xFFFE). When experimenting with new Resource Records these
  183. can be used, before requesting an official type code from IANA.
  184. See https://miek.nl/2014/september/21/idn-and-private-rr-in-go-dns/ for more
  185. information.
  186. EDNS0
  187. EDNS0 is an extension mechanism for the DNS defined in RFC 2671 and updated by
  188. RFC 6891. It defines an new RR type, the OPT RR, which is then completely
  189. abused.
  190. Basic use pattern for creating an (empty) OPT RR:
  191. o := new(dns.OPT)
  192. o.Hdr.Name = "." // MUST be the root zone, per definition.
  193. o.Hdr.Rrtype = dns.TypeOPT
  194. The rdata of an OPT RR consists out of a slice of EDNS0 (RFC 6891) interfaces.
  195. Currently only a few have been standardized: EDNS0_NSID (RFC 5001) and
  196. EDNS0_SUBNET (RFC 7871). Note that these options may be combined in an OPT RR.
  197. Basic use pattern for a server to check if (and which) options are set:
  198. // o is a dns.OPT
  199. for _, s := range o.Option {
  200. switch e := s.(type) {
  201. case *dns.EDNS0_NSID:
  202. // do stuff with e.Nsid
  203. case *dns.EDNS0_SUBNET:
  204. // access e.Family, e.Address, etc.
  205. }
  206. }
  207. SIG(0)
  208. From RFC 2931:
  209. SIG(0) provides protection for DNS transactions and requests ....
  210. ... protection for glue records, DNS requests, protection for message headers
  211. on requests and responses, and protection of the overall integrity of a response.
  212. It works like TSIG, except that SIG(0) uses public key cryptography, instead of
  213. the shared secret approach in TSIG. Supported algorithms: ECDSAP256SHA256,
  214. ECDSAP384SHA384, RSASHA1, RSASHA256 and RSASHA512.
  215. Signing subsequent messages in multi-message sessions is not implemented.
  216. */
  217. package dns