├── .github └── workflows │ └── semgrep.yml ├── .gitignore ├── .travis.yml ├── AUTHORS ├── CONTRIBUTORS ├── COPYRIGHT ├── LICENSE ├── README.md ├── client.go ├── client_test.go ├── clientconfig.go ├── clientconfig_test.go ├── defaults.go ├── dns.go ├── dns_test.go ├── dnssec.go ├── dnssec_keygen.go ├── dnssec_keyscan.go ├── dnssec_privkey.go ├── dnssec_test.go ├── doc.go ├── dyn_test.go ├── edns.go ├── edns_test.go ├── example_test.go ├── format.go ├── fuzz_test.go ├── idn ├── code_points.go ├── example_test.go ├── punycode.go └── punycode_test.go ├── labels.go ├── labels_test.go ├── msg.go ├── nsecx.go ├── nsecx_test.go ├── parse_test.go ├── privaterr.go ├── privaterr_test.go ├── rawmsg.go ├── remote_test.go ├── sanitize.go ├── sanitize_test.go ├── scanner.go ├── server.go ├── server_test.go ├── sig0.go ├── sig0_test.go ├── singleinflight.go ├── tlsa.go ├── tsig.go ├── types.go ├── types_test.go ├── udp.go ├── udp_linux.go ├── udp_other.go ├── udp_windows.go ├── update.go ├── update_test.go ├── xfr.go ├── xfr_test.go ├── zgenerate.go ├── zscan.go └── zscan_rr.go /.github/workflows/semgrep.yml: -------------------------------------------------------------------------------- 1 | 2 | on: 3 | pull_request: {} 4 | workflow_dispatch: {} 5 | push: 6 | branches: 7 | - main 8 | - master 9 | name: Semgrep config 10 | jobs: 11 | semgrep: 12 | name: semgrep/ci 13 | runs-on: ubuntu-20.04 14 | env: 15 | SEMGREP_APP_TOKEN: ${{ secrets.SEMGREP_APP_TOKEN }} 16 | SEMGREP_URL: https://cloudflare.semgrep.dev 17 | SEMGREP_APP_URL: https://cloudflare.semgrep.dev 18 | SEMGREP_VERSION_CHECK_URL: https://cloudflare.semgrep.dev/api/check-version 19 | container: 20 | image: returntocorp/semgrep 21 | steps: 22 | - uses: actions/checkout@v3 23 | - run: semgrep ci 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.6 2 | tags 3 | test.out 4 | a.out 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | sudo: false 3 | go: 4 | - 1.4 5 | - 1.5 6 | script: 7 | - go test -race -v -bench=. 8 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Miek Gieben 2 | -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | Alex A. Skinner 2 | Andrew Tunnell-Jones 3 | Ask Bjørn Hansen 4 | Dave Cheney 5 | Dusty Wilson 6 | Marek Majkowski 7 | Peter van Dijk 8 | Omri Bahumi 9 | Alex Sergeyev 10 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | Copyright 2009 The Go Authors. All rights reserved. Use of this source code 2 | is governed by a BSD-style license that can be found in the LICENSE file. 3 | Extensions of the original work are copyright (c) 2011 Miek Gieben 4 | 5 | Copyright 2011 Miek Gieben. All rights reserved. Use of this source code is 6 | governed by a BSD-style license that can be found in the LICENSE file. 7 | 8 | Copyright 2014 CloudFlare. All rights reserved. Use of this source code is 9 | governed by a BSD-style license that can be found in the LICENSE file. 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Extensions of the original work are copyright (c) 2011 Miek Gieben 2 | 3 | As this is fork of the official Go code the same license applies: 4 | 5 | Copyright (c) 2009 The Go Authors. All rights reserved. 6 | 7 | Redistribution and use in source and binary forms, with or without 8 | modification, are permitted provided that the following conditions are 9 | met: 10 | 11 | * Redistributions of source code must retain the above copyright 12 | notice, this list of conditions and the following disclaimer. 13 | * Redistributions in binary form must reproduce the above 14 | copyright notice, this list of conditions and the following disclaimer 15 | in the documentation and/or other materials provided with the 16 | distribution. 17 | * Neither the name of Google Inc. nor the names of its 18 | contributors may be used to endorse or promote products derived from 19 | this software without specific prior written permission. 20 | 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 24 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/miekg/dns.svg?branch=master)](https://travis-ci.org/miekg/dns) 2 | 3 | # Alternative (more granular) approach to a DNS library 4 | 5 | > Less is more. 6 | 7 | Complete and usable DNS library. All widely used Resource Records are 8 | supported, including the DNSSEC types. It follows a lean and mean philosophy. 9 | If there is stuff you should know as a DNS programmer there isn't a convenience 10 | function for it. Server side and client side programming is supported, i.e. you 11 | can build servers and resolvers with it. 12 | 13 | If you like this, you may also be interested in: 14 | 15 | * https://github.com/miekg/unbound -- Go wrapper for the Unbound resolver. 16 | 17 | # Goals 18 | 19 | * KISS; 20 | * Fast; 21 | * Small API, if its easy to code in Go, don't make a function for it. 22 | 23 | # Users 24 | 25 | A not-so-up-to-date-list-that-may-be-actually-current: 26 | 27 | * https://cloudflare.com 28 | * https://github.com/abh/geodns 29 | * http://www.statdns.com/ 30 | * http://www.dnsinspect.com/ 31 | * https://github.com/chuangbo/jianbing-dictionary-dns 32 | * http://www.dns-lg.com/ 33 | * https://github.com/fcambus/rrda 34 | * https://github.com/kenshinx/godns 35 | * https://github.com/skynetservices/skydns 36 | * https://github.com/DevelopersPL/godnsagent 37 | * https://github.com/duedil-ltd/discodns 38 | * https://github.com/StalkR/dns-reverse-proxy 39 | * https://github.com/tianon/rawdns 40 | * https://mesosphere.github.io/mesos-dns/ 41 | * https://pulse.turbobytes.com/ 42 | * https://play.google.com/store/apps/details?id=com.turbobytes.dig 43 | * https://github.com/fcambus/statzone 44 | * https://github.com/benschw/dns-clb-go 45 | * https://github.com/corny/dnscheck for http://public-dns.tk/ 46 | 47 | Send pull request if you want to be listed here. 48 | 49 | # Features 50 | 51 | * UDP/TCP queries, IPv4 and IPv6; 52 | * RFC 1035 zone file parsing ($INCLUDE, $ORIGIN, $TTL and $GENERATE (for all record types) are supported; 53 | * Fast: 54 | * Reply speed around ~ 80K qps (faster hardware results in more qps); 55 | * Parsing RRs ~ 100K RR/s, that's 5M records in about 50 seconds; 56 | * Server side programming (mimicking the net/http package); 57 | * Client side programming; 58 | * DNSSEC: signing, validating and key generation for DSA, RSA and ECDSA; 59 | * EDNS0, NSID; 60 | * AXFR/IXFR; 61 | * TSIG, SIG(0); 62 | * DNS name compression; 63 | * Depends only on the standard library. 64 | 65 | Have fun! 66 | 67 | Miek Gieben - 2010-2012 - 68 | 69 | # Building 70 | 71 | Building is done with the `go` tool. If you have setup your GOPATH 72 | correctly, the following should work: 73 | 74 | go get github.com/miekg/dns 75 | go build github.com/miekg/dns 76 | 77 | ## Examples 78 | 79 | A short "how to use the API" is at the beginning of doc.go (this also will show 80 | when you call `godoc github.com/miekg/dns`). 81 | 82 | Example programs can be found in the `github.com/miekg/exdns` repository. 83 | 84 | ## Supported RFCs 85 | 86 | *all of them* 87 | 88 | * 103{4,5} - DNS standard 89 | * 1348 - NSAP record (removed the record) 90 | * 1982 - Serial Arithmetic 91 | * 1876 - LOC record 92 | * 1995 - IXFR 93 | * 1996 - DNS notify 94 | * 2136 - DNS Update (dynamic updates) 95 | * 2181 - RRset definition - there is no RRset type though, just []RR 96 | * 2537 - RSAMD5 DNS keys 97 | * 2065 - DNSSEC (updated in later RFCs) 98 | * 2671 - EDNS record 99 | * 2782 - SRV record 100 | * 2845 - TSIG record 101 | * 2915 - NAPTR record 102 | * 2929 - DNS IANA Considerations 103 | * 3110 - RSASHA1 DNS keys 104 | * 3225 - DO bit (DNSSEC OK) 105 | * 340{1,2,3} - NAPTR record 106 | * 3445 - Limiting the scope of (DNS)KEY 107 | * 3597 - Unknown RRs 108 | * 4025 - IPSECKEY 109 | * 403{3,4,5} - DNSSEC + validation functions 110 | * 4255 - SSHFP record 111 | * 4343 - Case insensitivity 112 | * 4408 - SPF record 113 | * 4509 - SHA256 Hash in DS 114 | * 4592 - Wildcards in the DNS 115 | * 4635 - HMAC SHA TSIG 116 | * 4701 - DHCID 117 | * 4892 - id.server 118 | * 5001 - NSID 119 | * 5155 - NSEC3 record 120 | * 5205 - HIP record 121 | * 5702 - SHA2 in the DNS 122 | * 5936 - AXFR 123 | * 5966 - TCP implementation recommendations 124 | * 6605 - ECDSA 125 | * 6725 - IANA Registry Update 126 | * 6742 - ILNP DNS 127 | * 6840 - Clarifications and Implementation Notes for DNS Security 128 | * 6844 - CAA record 129 | * 6891 - EDNS0 update 130 | * 6895 - DNS IANA considerations 131 | * 6975 - Algorithm Understanding in DNSSEC 132 | * 7043 - EUI48/EUI64 records 133 | * 7314 - DNS (EDNS) EXPIRE Option 134 | * 7553 - URI record 135 | * xxxx - EDNS0 DNS Update Lease (draft) 136 | 137 | ## Loosely based upon 138 | 139 | * `ldns` 140 | * `NSD` 141 | * `Net::DNS` 142 | * `GRONG` 143 | 144 | ## TODO 145 | 146 | * privatekey.Precompute() when signing? 147 | * Last remaining RRs: APL, ATMA, A6, NSAP and NXT. 148 | * Missing in parsing: ISDN, UNSPEC, NSAP and ATMA. 149 | * NSEC(3) cover/match/closest enclose. 150 | * Replies with TC bit are not parsed to the end. 151 | -------------------------------------------------------------------------------- /client.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | // A client implementation. 4 | 5 | import ( 6 | "bytes" 7 | "io" 8 | "net" 9 | "time" 10 | ) 11 | 12 | const dnsTimeout time.Duration = 2 * time.Second 13 | const tcpIdleTimeout time.Duration = 8 * time.Second 14 | 15 | // A Conn represents a connection to a DNS server. 16 | type Conn struct { 17 | net.Conn // a net.Conn holding the connection 18 | UDPSize uint16 // minimum receive buffer for UDP messages 19 | TsigSecret map[string]string // secret(s) for Tsig map[], zonename must be fully qualified 20 | rtt time.Duration 21 | t time.Time 22 | tsigRequestMAC string 23 | } 24 | 25 | // A Client defines parameters for a DNS client. 26 | type Client struct { 27 | Net string // if "tcp" a TCP query will be initiated, otherwise an UDP one (default is "" for UDP) 28 | UDPSize uint16 // minimum receive buffer for UDP messages 29 | DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds 30 | ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds 31 | WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds 32 | TsigSecret map[string]string // secret(s) for Tsig map[], zonename must be fully qualified 33 | SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass 34 | group singleflight 35 | } 36 | 37 | // Exchange performs a synchronous UDP query. It sends the message m to the address 38 | // contained in a and waits for an reply. Exchange does not retry a failed query, nor 39 | // will it fall back to TCP in case of truncation. 40 | // If you need to send a DNS message on an already existing connection, you can use the 41 | // following: 42 | // 43 | // co := &dns.Conn{Conn: c} // c is your net.Conn 44 | // co.WriteMsg(m) 45 | // in, err := co.ReadMsg() 46 | // co.Close() 47 | // 48 | func Exchange(m *Msg, a string) (r *Msg, err error) { 49 | var co *Conn 50 | co, err = DialTimeout("udp", a, dnsTimeout) 51 | if err != nil { 52 | return nil, err 53 | } 54 | 55 | defer co.Close() 56 | 57 | opt := m.IsEdns0() 58 | // If EDNS0 is used use that for size. 59 | if opt != nil && opt.UDPSize() >= MinMsgSize { 60 | co.UDPSize = opt.UDPSize() 61 | } 62 | 63 | co.SetWriteDeadline(time.Now().Add(dnsTimeout)) 64 | if err = co.WriteMsg(m); err != nil { 65 | return nil, err 66 | } 67 | 68 | co.SetReadDeadline(time.Now().Add(dnsTimeout)) 69 | r, err = co.ReadMsg() 70 | if err == nil && r.Id != m.Id { 71 | err = ErrId 72 | } 73 | return r, err 74 | } 75 | 76 | // ExchangeConn performs a synchronous query. It sends the message m via the connection 77 | // c and waits for a reply. The connection c is not closed by ExchangeConn. 78 | // This function is going away, but can easily be mimicked: 79 | // 80 | // co := &dns.Conn{Conn: c} // c is your net.Conn 81 | // co.WriteMsg(m) 82 | // in, _ := co.ReadMsg() 83 | // co.Close() 84 | // 85 | func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) { 86 | println("dns: this function is deprecated") 87 | co := new(Conn) 88 | co.Conn = c 89 | if err = co.WriteMsg(m); err != nil { 90 | return nil, err 91 | } 92 | r, err = co.ReadMsg() 93 | if err == nil && r.Id != m.Id { 94 | err = ErrId 95 | } 96 | return r, err 97 | } 98 | 99 | // Exchange performs an synchronous query. It sends the message m to the address 100 | // contained in a and waits for an reply. Basic use pattern with a *dns.Client: 101 | // 102 | // c := new(dns.Client) 103 | // in, rtt, err := c.Exchange(message, "127.0.0.1:53") 104 | // 105 | // Exchange does not retry a failed query, nor will it fall back to TCP in 106 | // case of truncation. 107 | func (c *Client) Exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) { 108 | if !c.SingleInflight { 109 | return c.exchange(m, a) 110 | } 111 | // This adds a bunch of garbage, TODO(miek). 112 | t := "nop" 113 | if t1, ok := TypeToString[m.Question[0].Qtype]; ok { 114 | t = t1 115 | } 116 | cl := "nop" 117 | if cl1, ok := ClassToString[m.Question[0].Qclass]; ok { 118 | cl = cl1 119 | } 120 | r, rtt, err, shared := c.group.Do(m.Question[0].Name+t+cl, func() (*Msg, time.Duration, error) { 121 | return c.exchange(m, a) 122 | }) 123 | if err != nil { 124 | return r, rtt, err 125 | } 126 | if shared { 127 | return r.Copy(), rtt, nil 128 | } 129 | return r, rtt, nil 130 | } 131 | 132 | func (c *Client) dialTimeout() time.Duration { 133 | if c.DialTimeout != 0 { 134 | return c.DialTimeout 135 | } 136 | return dnsTimeout 137 | } 138 | 139 | func (c *Client) readTimeout() time.Duration { 140 | if c.ReadTimeout != 0 { 141 | return c.ReadTimeout 142 | } 143 | return dnsTimeout 144 | } 145 | 146 | func (c *Client) writeTimeout() time.Duration { 147 | if c.WriteTimeout != 0 { 148 | return c.WriteTimeout 149 | } 150 | return dnsTimeout 151 | } 152 | 153 | func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) { 154 | var co *Conn 155 | if c.Net == "" { 156 | co, err = DialTimeout("udp", a, c.dialTimeout()) 157 | } else { 158 | co, err = DialTimeout(c.Net, a, c.dialTimeout()) 159 | } 160 | if err != nil { 161 | return nil, 0, err 162 | } 163 | defer co.Close() 164 | 165 | opt := m.IsEdns0() 166 | // If EDNS0 is used use that for size. 167 | if opt != nil && opt.UDPSize() >= MinMsgSize { 168 | co.UDPSize = opt.UDPSize() 169 | } 170 | // Otherwise use the client's configured UDP size. 171 | if opt == nil && c.UDPSize >= MinMsgSize { 172 | co.UDPSize = c.UDPSize 173 | } 174 | 175 | co.TsigSecret = c.TsigSecret 176 | co.SetWriteDeadline(time.Now().Add(c.writeTimeout())) 177 | if err = co.WriteMsg(m); err != nil { 178 | return nil, 0, err 179 | } 180 | 181 | co.SetReadDeadline(time.Now().Add(c.readTimeout())) 182 | r, err = co.ReadMsg() 183 | if err == nil && r.Id != m.Id { 184 | err = ErrId 185 | } 186 | return r, co.rtt, err 187 | } 188 | 189 | // ReadMsg reads a message from the connection co. 190 | // If the received message contains a TSIG record the transaction 191 | // signature is verified. 192 | func (co *Conn) ReadMsg() (*Msg, error) { 193 | p, err := co.ReadMsgHeader(nil) 194 | if err != nil { 195 | return nil, err 196 | } 197 | 198 | m := new(Msg) 199 | if err := m.Unpack(p); err != nil { 200 | return nil, err 201 | } 202 | if t := m.IsTsig(); t != nil { 203 | if _, ok := co.TsigSecret[t.Hdr.Name]; !ok { 204 | return m, ErrSecret 205 | } 206 | // Need to work on the original message p, as that was used to calculate the tsig. 207 | err = TsigVerify(p, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false) 208 | } 209 | return m, err 210 | } 211 | 212 | // ReadMsgHeader reads a DNS message, parses and populates hdr (when hdr is not nil). 213 | // Returns message as a byte slice to be parsed with Msg.Unpack later on. 214 | // Note that error handling on the message body is not possible as only the header is parsed. 215 | func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) { 216 | var ( 217 | p []byte 218 | n int 219 | err error 220 | ) 221 | 222 | if t, ok := co.Conn.(*net.TCPConn); ok { 223 | // First two bytes specify the length of the entire message. 224 | l, err := tcpMsgLen(t) 225 | if err != nil { 226 | return nil, err 227 | } 228 | p = make([]byte, l) 229 | n, err = tcpRead(t, p) 230 | } else { 231 | if co.UDPSize > MinMsgSize { 232 | p = make([]byte, co.UDPSize) 233 | } else { 234 | p = make([]byte, MinMsgSize) 235 | } 236 | n, err = co.Read(p) 237 | } 238 | 239 | if err != nil { 240 | return nil, err 241 | } else if n < headerSize { 242 | return nil, ErrShortRead 243 | } 244 | 245 | p = p[:n] 246 | if hdr != nil { 247 | if _, err = UnpackStruct(hdr, p, 0); err != nil { 248 | return nil, err 249 | } 250 | } 251 | return p, err 252 | } 253 | 254 | // tcpMsgLen is a helper func to read first two bytes of stream as uint16 packet length. 255 | func tcpMsgLen(t *net.TCPConn) (int, error) { 256 | p := []byte{0, 0} 257 | n, err := t.Read(p) 258 | if err != nil { 259 | return 0, err 260 | } 261 | if n != 2 { 262 | return 0, ErrShortRead 263 | } 264 | l, _ := unpackUint16(p, 0) 265 | if l == 0 { 266 | return 0, ErrShortRead 267 | } 268 | return int(l), nil 269 | } 270 | 271 | // tcpRead calls TCPConn.Read enough times to fill allocated buffer. 272 | func tcpRead(t *net.TCPConn, p []byte) (int, error) { 273 | n, err := t.Read(p) 274 | if err != nil { 275 | return n, err 276 | } 277 | for n < len(p) { 278 | j, err := t.Read(p[n:]) 279 | if err != nil { 280 | return n, err 281 | } 282 | n += j 283 | } 284 | return n, err 285 | } 286 | 287 | // Read implements the net.Conn read method. 288 | func (co *Conn) Read(p []byte) (n int, err error) { 289 | if co.Conn == nil { 290 | return 0, ErrConnEmpty 291 | } 292 | if len(p) < 2 { 293 | return 0, io.ErrShortBuffer 294 | } 295 | if t, ok := co.Conn.(*net.TCPConn); ok { 296 | l, err := tcpMsgLen(t) 297 | if err != nil { 298 | return 0, err 299 | } 300 | if l > len(p) { 301 | return int(l), io.ErrShortBuffer 302 | } 303 | return tcpRead(t, p[:l]) 304 | } 305 | // UDP connection 306 | n, err = co.Conn.Read(p) 307 | if err != nil { 308 | return n, err 309 | } 310 | 311 | co.rtt = time.Since(co.t) 312 | return n, err 313 | } 314 | 315 | // WriteMsg sends a message throught the connection co. 316 | // If the message m contains a TSIG record the transaction 317 | // signature is calculated. 318 | func (co *Conn) WriteMsg(m *Msg) (err error) { 319 | var out []byte 320 | if t := m.IsTsig(); t != nil { 321 | mac := "" 322 | if _, ok := co.TsigSecret[t.Hdr.Name]; !ok { 323 | return ErrSecret 324 | } 325 | out, mac, err = TsigGenerate(m, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false) 326 | // Set for the next read, allthough only used in zone transfers 327 | co.tsigRequestMAC = mac 328 | } else { 329 | out, err = m.Pack() 330 | } 331 | if err != nil { 332 | return err 333 | } 334 | co.t = time.Now() 335 | if _, err = co.Write(out); err != nil { 336 | return err 337 | } 338 | return nil 339 | } 340 | 341 | // Write implements the net.Conn Write method. 342 | func (co *Conn) Write(p []byte) (n int, err error) { 343 | if t, ok := co.Conn.(*net.TCPConn); ok { 344 | lp := len(p) 345 | if lp < 2 { 346 | return 0, io.ErrShortBuffer 347 | } 348 | if lp > MaxMsgSize { 349 | return 0, &Error{err: "message too large"} 350 | } 351 | l := make([]byte, 2, lp+2) 352 | l[0], l[1] = packUint16(uint16(lp)) 353 | p = append(l, p...) 354 | n, err := io.Copy(t, bytes.NewReader(p)) 355 | return int(n), err 356 | } 357 | n, err = co.Conn.(*net.UDPConn).Write(p) 358 | return n, err 359 | } 360 | 361 | // Dial connects to the address on the named network. 362 | func Dial(network, address string) (conn *Conn, err error) { 363 | conn = new(Conn) 364 | conn.Conn, err = net.Dial(network, address) 365 | if err != nil { 366 | return nil, err 367 | } 368 | return conn, nil 369 | } 370 | 371 | // DialTimeout acts like Dial but takes a timeout. 372 | func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error) { 373 | conn = new(Conn) 374 | conn.Conn, err = net.DialTimeout(network, address, timeout) 375 | if err != nil { 376 | return nil, err 377 | } 378 | return conn, nil 379 | } 380 | -------------------------------------------------------------------------------- /client_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "strconv" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestClientSync(t *testing.T) { 10 | HandleFunc("miek.nl.", HelloServer) 11 | defer HandleRemove("miek.nl.") 12 | 13 | s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") 14 | if err != nil { 15 | t.Fatalf("Unable to run test server: %v", err) 16 | } 17 | defer s.Shutdown() 18 | 19 | m := new(Msg) 20 | m.SetQuestion("miek.nl.", TypeSOA) 21 | 22 | c := new(Client) 23 | r, _, err := c.Exchange(m, addrstr) 24 | if err != nil { 25 | t.Errorf("failed to exchange: %v", err) 26 | } 27 | if r != nil && r.Rcode != RcodeSuccess { 28 | t.Errorf("failed to get an valid answer\n%v", r) 29 | } 30 | // And now with plain Exchange(). 31 | r, err = Exchange(m, addrstr) 32 | if err != nil { 33 | t.Errorf("failed to exchange: %v", err) 34 | } 35 | if r == nil || r.Rcode != RcodeSuccess { 36 | t.Errorf("failed to get an valid answer\n%v", r) 37 | } 38 | } 39 | 40 | func TestClientSyncBadId(t *testing.T) { 41 | HandleFunc("miek.nl.", HelloServerBadId) 42 | defer HandleRemove("miek.nl.") 43 | 44 | s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") 45 | if err != nil { 46 | t.Fatalf("Unable to run test server: %v", err) 47 | } 48 | defer s.Shutdown() 49 | 50 | m := new(Msg) 51 | m.SetQuestion("miek.nl.", TypeSOA) 52 | 53 | c := new(Client) 54 | if _, _, err := c.Exchange(m, addrstr); err != ErrId { 55 | t.Errorf("did not find a bad Id") 56 | } 57 | // And now with plain Exchange(). 58 | if _, err := Exchange(m, addrstr); err != ErrId { 59 | t.Errorf("did not find a bad Id") 60 | } 61 | } 62 | 63 | func TestClientEDNS0(t *testing.T) { 64 | HandleFunc("miek.nl.", HelloServer) 65 | defer HandleRemove("miek.nl.") 66 | 67 | s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") 68 | if err != nil { 69 | t.Fatalf("Unable to run test server: %v", err) 70 | } 71 | defer s.Shutdown() 72 | 73 | m := new(Msg) 74 | m.SetQuestion("miek.nl.", TypeDNSKEY) 75 | 76 | m.SetEdns0(2048, true) 77 | 78 | c := new(Client) 79 | r, _, err := c.Exchange(m, addrstr) 80 | if err != nil { 81 | t.Errorf("failed to exchange: %v", err) 82 | } 83 | 84 | if r != nil && r.Rcode != RcodeSuccess { 85 | t.Errorf("failed to get an valid answer\n%v", r) 86 | } 87 | } 88 | 89 | // Validates the transmission and parsing of local EDNS0 options. 90 | func TestClientEDNS0Local(t *testing.T) { 91 | optStr1 := "1979:0x0707" 92 | optStr2 := strconv.Itoa(EDNS0LOCALSTART) + ":0x0601" 93 | 94 | handler := func(w ResponseWriter, req *Msg) { 95 | m := new(Msg) 96 | m.SetReply(req) 97 | 98 | m.Extra = make([]RR, 1, 2) 99 | m.Extra[0] = &TXT{Hdr: RR_Header{Name: m.Question[0].Name, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}, Txt: []string{"Hello local edns"}} 100 | 101 | // If the local options are what we expect, then reflect them back. 102 | ec1 := req.Extra[0].(*OPT).Option[0].(*EDNS0_LOCAL).String() 103 | ec2 := req.Extra[0].(*OPT).Option[1].(*EDNS0_LOCAL).String() 104 | if ec1 == optStr1 && ec2 == optStr2 { 105 | m.Extra = append(m.Extra, req.Extra[0]) 106 | } 107 | 108 | w.WriteMsg(m) 109 | } 110 | 111 | HandleFunc("miek.nl.", handler) 112 | defer HandleRemove("miek.nl.") 113 | 114 | s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") 115 | if err != nil { 116 | t.Fatalf("Unable to run test server: %s", err) 117 | } 118 | defer s.Shutdown() 119 | 120 | m := new(Msg) 121 | m.SetQuestion("miek.nl.", TypeTXT) 122 | 123 | // Add two local edns options to the query. 124 | ec1 := &EDNS0_LOCAL{Code: 1979, Data: []byte{7, 7}} 125 | ec2 := &EDNS0_LOCAL{Code: EDNS0LOCALSTART, Data: []byte{6, 1}} 126 | o := &OPT{Hdr: RR_Header{Name: ".", Rrtype: TypeOPT}, Option: []EDNS0{ec1, ec2}} 127 | m.Extra = append(m.Extra, o) 128 | 129 | c := new(Client) 130 | r, _, e := c.Exchange(m, addrstr) 131 | if e != nil { 132 | t.Logf("failed to exchange: %s", e.Error()) 133 | t.Fail() 134 | } 135 | 136 | if r != nil && r.Rcode != RcodeSuccess { 137 | t.Log("failed to get a valid answer") 138 | t.Fail() 139 | t.Logf("%v\n", r) 140 | } 141 | 142 | txt := r.Extra[0].(*TXT).Txt[0] 143 | if txt != "Hello local edns" { 144 | t.Log("Unexpected result for miek.nl", txt, "!= Hello local edns") 145 | t.Fail() 146 | } 147 | 148 | // Validate the local options in the reply. 149 | got := r.Extra[1].(*OPT).Option[0].(*EDNS0_LOCAL).String() 150 | if got != optStr1 { 151 | t.Logf("failed to get local edns0 answer; got %s, expected %s", got, optStr1) 152 | t.Fail() 153 | t.Logf("%v\n", r) 154 | } 155 | 156 | got = r.Extra[1].(*OPT).Option[1].(*EDNS0_LOCAL).String() 157 | if got != optStr2 { 158 | t.Logf("failed to get local edns0 answer; got %s, expected %s", got, optStr2) 159 | t.Fail() 160 | t.Logf("%v\n", r) 161 | } 162 | } 163 | 164 | // ExampleUpdateLeaseTSIG shows how to update a lease signed with TSIG. 165 | func ExampleUpdateLeaseTSIG(t *testing.T) { 166 | m := new(Msg) 167 | m.SetUpdate("t.local.ip6.io.") 168 | rr, _ := NewRR("t.local.ip6.io. 30 A 127.0.0.1") 169 | rrs := make([]RR, 1) 170 | rrs[0] = rr 171 | m.Insert(rrs) 172 | 173 | leaseRr := new(OPT) 174 | leaseRr.Hdr.Name = "." 175 | leaseRr.Hdr.Rrtype = TypeOPT 176 | e := new(EDNS0_UL) 177 | e.Code = EDNS0UL 178 | e.Lease = 120 179 | leaseRr.Option = append(leaseRr.Option, e) 180 | m.Extra = append(m.Extra, leaseRr) 181 | 182 | c := new(Client) 183 | m.SetTsig("polvi.", HmacMD5, 300, time.Now().Unix()) 184 | c.TsigSecret = map[string]string{"polvi.": "pRZgBrBvI4NAHZYhxmhs/Q=="} 185 | 186 | _, _, err := c.Exchange(m, "127.0.0.1:53") 187 | if err != nil { 188 | t.Error(err) 189 | } 190 | } 191 | 192 | func TestClientConn(t *testing.T) { 193 | HandleFunc("miek.nl.", HelloServer) 194 | defer HandleRemove("miek.nl.") 195 | 196 | // This uses TCP just to make it slightly different than TestClientSync 197 | s, addrstr, err := RunLocalTCPServer("127.0.0.1:0") 198 | if err != nil { 199 | t.Fatalf("Unable to run test server: %v", err) 200 | } 201 | defer s.Shutdown() 202 | 203 | m := new(Msg) 204 | m.SetQuestion("miek.nl.", TypeSOA) 205 | 206 | cn, err := Dial("tcp", addrstr) 207 | if err != nil { 208 | t.Errorf("failed to dial %s: %v", addrstr, err) 209 | } 210 | 211 | err = cn.WriteMsg(m) 212 | if err != nil { 213 | t.Errorf("failed to exchange: %v", err) 214 | } 215 | r, err := cn.ReadMsg() 216 | if r == nil || r.Rcode != RcodeSuccess { 217 | t.Errorf("failed to get an valid answer\n%v", r) 218 | } 219 | 220 | err = cn.WriteMsg(m) 221 | if err != nil { 222 | t.Errorf("failed to exchange: %v", err) 223 | } 224 | h := new(Header) 225 | buf, err := cn.ReadMsgHeader(h) 226 | if buf == nil { 227 | t.Errorf("failed to get an valid answer\n%v", r) 228 | } 229 | if int(h.Bits&0xF) != RcodeSuccess { 230 | t.Errorf("failed to get an valid answer in ReadMsgHeader\n%v", r) 231 | } 232 | if h.Ancount != 0 || h.Qdcount != 1 || h.Nscount != 0 || h.Arcount != 1 { 233 | t.Errorf("expected to have question and additional in response; got something else: %+v", h) 234 | } 235 | if err = r.Unpack(buf); err != nil { 236 | t.Errorf("unable to unpack message fully: %v", err) 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /clientconfig.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "bufio" 5 | "os" 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | // ClientConfig wraps the contents of the /etc/resolv.conf file. 11 | type ClientConfig struct { 12 | Servers []string // servers to use 13 | Search []string // suffixes to append to local name 14 | Port string // what port to use 15 | Ndots int // number of dots in name to trigger absolute lookup 16 | Timeout int // seconds before giving up on packet 17 | Attempts int // lost packets before giving up on server, not used in the package dns 18 | } 19 | 20 | // ClientConfigFromFile parses a resolv.conf(5) like file and returns 21 | // a *ClientConfig. 22 | func ClientConfigFromFile(resolvconf string) (*ClientConfig, error) { 23 | file, err := os.Open(resolvconf) 24 | if err != nil { 25 | return nil, err 26 | } 27 | defer file.Close() 28 | c := new(ClientConfig) 29 | scanner := bufio.NewScanner(file) 30 | c.Servers = make([]string, 0) 31 | c.Search = make([]string, 0) 32 | c.Port = "53" 33 | c.Ndots = 1 34 | c.Timeout = 5 35 | c.Attempts = 2 36 | 37 | for scanner.Scan() { 38 | if err := scanner.Err(); err != nil { 39 | return nil, err 40 | } 41 | line := scanner.Text() 42 | f := strings.Fields(line) 43 | if len(f) < 1 { 44 | continue 45 | } 46 | switch f[0] { 47 | case "nameserver": // add one name server 48 | if len(f) > 1 { 49 | // One more check: make sure server name is 50 | // just an IP address. Otherwise we need DNS 51 | // to look it up. 52 | name := f[1] 53 | c.Servers = append(c.Servers, name) 54 | } 55 | 56 | case "domain": // set search path to just this domain 57 | if len(f) > 1 { 58 | c.Search = make([]string, 1) 59 | c.Search[0] = f[1] 60 | } else { 61 | c.Search = make([]string, 0) 62 | } 63 | 64 | case "search": // set search path to given servers 65 | c.Search = make([]string, len(f)-1) 66 | for i := 0; i < len(c.Search); i++ { 67 | c.Search[i] = f[i+1] 68 | } 69 | 70 | case "options": // magic options 71 | for i := 1; i < len(f); i++ { 72 | s := f[i] 73 | switch { 74 | case len(s) >= 6 && s[:6] == "ndots:": 75 | n, _ := strconv.Atoi(s[6:]) 76 | if n < 1 { 77 | n = 1 78 | } 79 | c.Ndots = n 80 | case len(s) >= 8 && s[:8] == "timeout:": 81 | n, _ := strconv.Atoi(s[8:]) 82 | if n < 1 { 83 | n = 1 84 | } 85 | c.Timeout = n 86 | case len(s) >= 8 && s[:9] == "attempts:": 87 | n, _ := strconv.Atoi(s[9:]) 88 | if n < 1 { 89 | n = 1 90 | } 91 | c.Attempts = n 92 | case s == "rotate": 93 | /* not imp */ 94 | } 95 | } 96 | } 97 | } 98 | return c, nil 99 | } 100 | -------------------------------------------------------------------------------- /clientconfig_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "path/filepath" 7 | "testing" 8 | ) 9 | 10 | const normal string = ` 11 | # Comment 12 | domain somedomain.com 13 | nameserver 10.28.10.2 14 | nameserver 11.28.10.1 15 | ` 16 | 17 | const missingNewline string = ` 18 | domain somedomain.com 19 | nameserver 10.28.10.2 20 | nameserver 11.28.10.1` // <- NOTE: NO newline. 21 | 22 | func testConfig(t *testing.T, data string) { 23 | tempDir, err := ioutil.TempDir("", "") 24 | if err != nil { 25 | t.Fatalf("TempDir: %v", err) 26 | } 27 | defer os.RemoveAll(tempDir) 28 | 29 | path := filepath.Join(tempDir, "resolv.conf") 30 | if err := ioutil.WriteFile(path, []byte(data), 0644); err != nil { 31 | t.Fatalf("WriteFile: %v", err) 32 | } 33 | cc, err := ClientConfigFromFile(path) 34 | if err != nil { 35 | t.Errorf("error parsing resolv.conf: %v", err) 36 | } 37 | if l := len(cc.Servers); l != 2 { 38 | t.Errorf("incorrect number of nameservers detected: %d", l) 39 | } 40 | if l := len(cc.Search); l != 1 { 41 | t.Errorf("domain directive not parsed correctly: %v", cc.Search) 42 | } else { 43 | if cc.Search[0] != "somedomain.com" { 44 | t.Errorf("domain is unexpected: %v", cc.Search[0]) 45 | } 46 | } 47 | } 48 | 49 | func TestNameserver(t *testing.T) { 50 | testConfig(t, normal) 51 | } 52 | 53 | func TestMissingFinalNewLine(t *testing.T) { 54 | testConfig(t, missingNewline) 55 | } 56 | -------------------------------------------------------------------------------- /defaults.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "errors" 5 | "net" 6 | "strconv" 7 | ) 8 | 9 | const hexDigit = "0123456789abcdef" 10 | 11 | // Everything is assumed in ClassINET. 12 | 13 | // SetReply creates a reply message from a request message. 14 | func (dns *Msg) SetReply(request *Msg) *Msg { 15 | dns.Id = request.Id 16 | dns.RecursionDesired = request.RecursionDesired // Copy rd bit 17 | dns.Response = true 18 | dns.Opcode = OpcodeQuery 19 | dns.Rcode = RcodeSuccess 20 | if len(request.Question) > 0 { 21 | dns.Question = make([]Question, 1) 22 | dns.Question[0] = request.Question[0] 23 | } 24 | return dns 25 | } 26 | 27 | // SetQuestion creates a question message, it sets the Question 28 | // section, generates an Id and sets the RecursionDesired (RD) 29 | // bit to true. 30 | func (dns *Msg) SetQuestion(z string, t uint16) *Msg { 31 | dns.Id = Id() 32 | dns.RecursionDesired = true 33 | dns.Question = make([]Question, 1) 34 | dns.Question[0] = Question{z, t, ClassINET} 35 | return dns 36 | } 37 | 38 | // SetNotify creates a notify message, it sets the Question 39 | // section, generates an Id and sets the Authoritative (AA) 40 | // bit to true. 41 | func (dns *Msg) SetNotify(z string) *Msg { 42 | dns.Opcode = OpcodeNotify 43 | dns.Authoritative = true 44 | dns.Id = Id() 45 | dns.Question = make([]Question, 1) 46 | dns.Question[0] = Question{z, TypeSOA, ClassINET} 47 | return dns 48 | } 49 | 50 | // SetRcode creates an error message suitable for the request. 51 | func (dns *Msg) SetRcode(request *Msg, rcode int) *Msg { 52 | dns.SetReply(request) 53 | dns.Rcode = rcode 54 | return dns 55 | } 56 | 57 | // SetRcodeFormatError creates a message with FormError set. 58 | func (dns *Msg) SetRcodeFormatError(request *Msg) *Msg { 59 | dns.Rcode = RcodeFormatError 60 | dns.Opcode = OpcodeQuery 61 | dns.Response = true 62 | dns.Authoritative = false 63 | dns.Id = request.Id 64 | return dns 65 | } 66 | 67 | // SetUpdate makes the message a dynamic update message. It 68 | // sets the ZONE section to: z, TypeSOA, ClassINET. 69 | func (dns *Msg) SetUpdate(z string) *Msg { 70 | dns.Id = Id() 71 | dns.Response = false 72 | dns.Opcode = OpcodeUpdate 73 | dns.Compress = false // BIND9 cannot handle compression 74 | dns.Question = make([]Question, 1) 75 | dns.Question[0] = Question{z, TypeSOA, ClassINET} 76 | return dns 77 | } 78 | 79 | // SetIxfr creates message for requesting an IXFR. 80 | func (dns *Msg) SetIxfr(z string, serial uint32, ns, mbox string) *Msg { 81 | dns.Id = Id() 82 | dns.Question = make([]Question, 1) 83 | dns.Ns = make([]RR, 1) 84 | s := new(SOA) 85 | s.Hdr = RR_Header{z, TypeSOA, ClassINET, defaultTtl, 0} 86 | s.Serial = serial 87 | s.Ns = ns 88 | s.Mbox = mbox 89 | dns.Question[0] = Question{z, TypeIXFR, ClassINET} 90 | dns.Ns[0] = s 91 | return dns 92 | } 93 | 94 | // SetAxfr creates message for requesting an AXFR. 95 | func (dns *Msg) SetAxfr(z string) *Msg { 96 | dns.Id = Id() 97 | dns.Question = make([]Question, 1) 98 | dns.Question[0] = Question{z, TypeAXFR, ClassINET} 99 | return dns 100 | } 101 | 102 | // SetTsig appends a TSIG RR to the message. 103 | // This is only a skeleton TSIG RR that is added as the last RR in the 104 | // additional section. The Tsig is calculated when the message is being send. 105 | func (dns *Msg) SetTsig(z, algo string, fudge, timesigned int64) *Msg { 106 | t := new(TSIG) 107 | t.Hdr = RR_Header{z, TypeTSIG, ClassANY, 0, 0} 108 | t.Algorithm = algo 109 | t.Fudge = 300 110 | t.TimeSigned = uint64(timesigned) 111 | t.OrigId = dns.Id 112 | dns.Extra = append(dns.Extra, t) 113 | return dns 114 | } 115 | 116 | // SetEdns0 appends a EDNS0 OPT RR to the message. 117 | // TSIG should always the last RR in a message. 118 | func (dns *Msg) SetEdns0(udpsize uint16, do bool) *Msg { 119 | e := new(OPT) 120 | e.Hdr.Name = "." 121 | e.Hdr.Rrtype = TypeOPT 122 | e.SetUDPSize(udpsize) 123 | if do { 124 | e.SetDo() 125 | } 126 | dns.Extra = append(dns.Extra, e) 127 | return dns 128 | } 129 | 130 | // IsTsig checks if the message has a TSIG record as the last record 131 | // in the additional section. It returns the TSIG record found or nil. 132 | func (dns *Msg) IsTsig() *TSIG { 133 | if len(dns.Extra) > 0 { 134 | if dns.Extra[len(dns.Extra)-1].Header().Rrtype == TypeTSIG { 135 | return dns.Extra[len(dns.Extra)-1].(*TSIG) 136 | } 137 | } 138 | return nil 139 | } 140 | 141 | // IsEdns0 checks if the message has a EDNS0 (OPT) record, any EDNS0 142 | // record in the additional section will do. It returns the OPT record 143 | // found or nil. 144 | func (dns *Msg) IsEdns0() *OPT { 145 | for _, r := range dns.Extra { 146 | if r.Header().Rrtype == TypeOPT { 147 | return r.(*OPT) 148 | } 149 | } 150 | return nil 151 | } 152 | 153 | // IsDomainName checks if s is a valid domain name, it returns the number of 154 | // labels and true, when a domain name is valid. Note that non fully qualified 155 | // domain name is considered valid, in this case the last label is counted in 156 | // the number of labels. When false is returned the number of labels is not 157 | // defined. Also note that this function is extremely liberal; almost any 158 | // string is a valid domain name as the DNS is 8 bit protocol. It checks if each 159 | // label fits in 63 characters, but there is no length check for the entire 160 | // string s. I.e. a domain name longer than 255 characters is considered valid. 161 | func IsDomainName(s string) (labels int, ok bool) { 162 | _, labels, err := packDomainName(s, nil, 0, nil, false) 163 | return labels, err == nil 164 | } 165 | 166 | // IsSubDomain checks if child is indeed a child of the parent. Both child and 167 | // parent are *not* downcased before doing the comparison. 168 | func IsSubDomain(parent, child string) bool { 169 | // Entire child is contained in parent 170 | return CompareDomainName(parent, child) == CountLabel(parent) 171 | } 172 | 173 | // IsMsg sanity checks buf and returns an error if it isn't a valid DNS packet. 174 | // The checking is performed on the binary payload. 175 | func IsMsg(buf []byte) error { 176 | // Header 177 | if len(buf) < 12 { 178 | return errors.New("dns: bad message header") 179 | } 180 | // Header: Opcode 181 | // TODO(miek): more checks here, e.g. check all header bits. 182 | return nil 183 | } 184 | 185 | // IsFqdn checks if a domain name is fully qualified. 186 | func IsFqdn(s string) bool { 187 | l := len(s) 188 | if l == 0 { 189 | return false 190 | } 191 | return s[l-1] == '.' 192 | } 193 | 194 | // IsRRset checks if a set of RRs is a valid RRset as defined by RFC 2181. 195 | // This means the RRs need to have the same type, name, and class. Returns true 196 | // if the RR set is valid, otherwise false. 197 | func IsRRset(rrset []RR) bool { 198 | if len(rrset) == 0 { 199 | return false 200 | } 201 | if len(rrset) == 1 { 202 | return true 203 | } 204 | rrHeader := rrset[0].Header() 205 | rrType := rrHeader.Rrtype 206 | rrClass := rrHeader.Class 207 | rrName := rrHeader.Name 208 | 209 | for _, rr := range rrset[1:] { 210 | curRRHeader := rr.Header() 211 | if curRRHeader.Rrtype != rrType || curRRHeader.Class != rrClass || curRRHeader.Name != rrName { 212 | // Mismatch between the records, so this is not a valid rrset for 213 | //signing/verifying 214 | return false 215 | } 216 | } 217 | 218 | return true 219 | } 220 | 221 | // Fqdn return the fully qualified domain name from s. 222 | // If s is already fully qualified, it behaves as the identity function. 223 | func Fqdn(s string) string { 224 | if IsFqdn(s) { 225 | return s 226 | } 227 | return s + "." 228 | } 229 | 230 | // Copied from the official Go code. 231 | 232 | // ReverseAddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP 233 | // address suitable for reverse DNS (PTR) record lookups or an error if it fails 234 | // to parse the IP address. 235 | func ReverseAddr(addr string) (arpa string, err error) { 236 | ip := net.ParseIP(addr) 237 | if ip == nil { 238 | return "", &Error{err: "unrecognized address: " + addr} 239 | } 240 | if ip.To4() != nil { 241 | return strconv.Itoa(int(ip[15])) + "." + strconv.Itoa(int(ip[14])) + "." + strconv.Itoa(int(ip[13])) + "." + 242 | strconv.Itoa(int(ip[12])) + ".in-addr.arpa.", nil 243 | } 244 | // Must be IPv6 245 | buf := make([]byte, 0, len(ip)*4+len("ip6.arpa.")) 246 | // Add it, in reverse, to the buffer 247 | for i := len(ip) - 1; i >= 0; i-- { 248 | v := ip[i] 249 | buf = append(buf, hexDigit[v&0xF]) 250 | buf = append(buf, '.') 251 | buf = append(buf, hexDigit[v>>4]) 252 | buf = append(buf, '.') 253 | } 254 | // Append "ip6.arpa." and return (buf already has the final .) 255 | buf = append(buf, "ip6.arpa."...) 256 | return string(buf), nil 257 | } 258 | 259 | // String returns the string representation for the type t. 260 | func (t Type) String() string { 261 | if t1, ok := TypeToString[uint16(t)]; ok { 262 | return t1 263 | } 264 | return "TYPE" + strconv.Itoa(int(t)) 265 | } 266 | 267 | // String returns the string representation for the class c. 268 | func (c Class) String() string { 269 | if c1, ok := ClassToString[uint16(c)]; ok { 270 | return c1 271 | } 272 | return "CLASS" + strconv.Itoa(int(c)) 273 | } 274 | 275 | // String returns the string representation for the name n. 276 | func (n Name) String() string { 277 | return sprintName(string(n)) 278 | } 279 | -------------------------------------------------------------------------------- /dns.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import "strconv" 4 | 5 | const ( 6 | year68 = 1 << 31 // For RFC1982 (Serial Arithmetic) calculations in 32 bits. 7 | // DefaultMsgSize is the standard default for messages larger than 512 bytes. 8 | DefaultMsgSize = 4096 9 | // MinMsgSize is the minimal size of a DNS packet. 10 | MinMsgSize = 512 11 | // MaxMsgSize is the largest possible DNS packet. 12 | MaxMsgSize = 65535 13 | defaultTtl = 3600 // Default internal TTL. 14 | ) 15 | 16 | // Error represents a DNS error 17 | type Error struct{ err string } 18 | 19 | func (e *Error) Error() string { 20 | if e == nil { 21 | return "dns: " 22 | } 23 | return "dns: " + e.err 24 | } 25 | 26 | // An RR represents a resource record. 27 | type RR interface { 28 | // Header returns the header of an resource record. The header contains 29 | // everything up to the rdata. 30 | Header() *RR_Header 31 | // String returns the text representation of the resource record. 32 | String() string 33 | // copy returns a copy of the RR 34 | copy() RR 35 | // len returns the length (in octets) of the uncompressed RR in wire format. 36 | len() int 37 | } 38 | 39 | // RR_Header is the header all DNS resource records share. 40 | type RR_Header struct { 41 | Name string `dns:"cdomain-name"` 42 | Rrtype uint16 43 | Class uint16 44 | Ttl uint32 45 | Rdlength uint16 // length of data after header 46 | } 47 | 48 | // Header returns itself. This is here to make RR_Header implement the RR interface. 49 | func (h *RR_Header) Header() *RR_Header { return h } 50 | 51 | // Just to imlement the RR interface. 52 | func (h *RR_Header) copy() RR { return nil } 53 | 54 | func (h *RR_Header) copyHeader() *RR_Header { 55 | r := new(RR_Header) 56 | r.Name = h.Name 57 | r.Rrtype = h.Rrtype 58 | r.Class = h.Class 59 | r.Ttl = h.Ttl 60 | r.Rdlength = h.Rdlength 61 | return r 62 | } 63 | 64 | func (h *RR_Header) String() string { 65 | var s string 66 | 67 | if h.Rrtype == TypeOPT { 68 | s = ";" 69 | // and maybe other things 70 | } 71 | 72 | s += sprintName(h.Name) + "\t" 73 | s += strconv.FormatInt(int64(h.Ttl), 10) + "\t" 74 | s += Class(h.Class).String() + "\t" 75 | s += Type(h.Rrtype).String() + "\t" 76 | return s 77 | } 78 | 79 | func (h *RR_Header) len() int { 80 | l := len(h.Name) + 1 81 | l += 10 // rrtype(2) + class(2) + ttl(4) + rdlength(2) 82 | return l 83 | } 84 | 85 | // ToRFC3597 converts a known RR to the unknown RR representation 86 | // from RFC 3597. 87 | func (rr *RFC3597) ToRFC3597(r RR) error { 88 | buf := make([]byte, r.len()*2) 89 | off, err := PackStruct(r, buf, 0) 90 | if err != nil { 91 | return err 92 | } 93 | buf = buf[:off] 94 | rawSetRdlength(buf, 0, off) 95 | _, err = UnpackStruct(rr, buf, 0) 96 | if err != nil { 97 | return err 98 | } 99 | return nil 100 | } 101 | -------------------------------------------------------------------------------- /dnssec.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "bytes" 5 | "crypto" 6 | "crypto/dsa" 7 | "crypto/ecdsa" 8 | "crypto/elliptic" 9 | _ "crypto/md5" 10 | "crypto/rand" 11 | "crypto/rsa" 12 | _ "crypto/sha1" 13 | _ "crypto/sha256" 14 | _ "crypto/sha512" 15 | "encoding/asn1" 16 | "encoding/hex" 17 | "math/big" 18 | "sort" 19 | "strings" 20 | "time" 21 | ) 22 | 23 | // DNSSEC encryption algorithm codes. 24 | const ( 25 | _ uint8 = iota 26 | RSAMD5 27 | DH 28 | DSA 29 | _ // Skip 4, RFC 6725, section 2.1 30 | RSASHA1 31 | DSANSEC3SHA1 32 | RSASHA1NSEC3SHA1 33 | RSASHA256 34 | _ // Skip 9, RFC 6725, section 2.1 35 | RSASHA512 36 | _ // Skip 11, RFC 6725, section 2.1 37 | ECCGOST 38 | ECDSAP256SHA256 39 | ECDSAP384SHA384 40 | INDIRECT uint8 = 252 41 | PRIVATEDNS uint8 = 253 // Private (experimental keys) 42 | PRIVATEOID uint8 = 254 43 | ) 44 | 45 | // Map for algorithm names. 46 | var AlgorithmToString = map[uint8]string{ 47 | RSAMD5: "RSAMD5", 48 | DH: "DH", 49 | DSA: "DSA", 50 | RSASHA1: "RSASHA1", 51 | DSANSEC3SHA1: "DSA-NSEC3-SHA1", 52 | RSASHA1NSEC3SHA1: "RSASHA1-NSEC3-SHA1", 53 | RSASHA256: "RSASHA256", 54 | RSASHA512: "RSASHA512", 55 | ECCGOST: "ECC-GOST", 56 | ECDSAP256SHA256: "ECDSAP256SHA256", 57 | ECDSAP384SHA384: "ECDSAP384SHA384", 58 | INDIRECT: "INDIRECT", 59 | PRIVATEDNS: "PRIVATEDNS", 60 | PRIVATEOID: "PRIVATEOID", 61 | } 62 | 63 | // Map of algorithm strings. 64 | var StringToAlgorithm = reverseInt8(AlgorithmToString) 65 | 66 | // Map of algorithm crypto hashes. 67 | var AlgorithmToHash = map[uint8]crypto.Hash{ 68 | RSAMD5: crypto.MD5, // Deprecated in RFC 6725 69 | RSASHA1: crypto.SHA1, 70 | RSASHA1NSEC3SHA1: crypto.SHA1, 71 | RSASHA256: crypto.SHA256, 72 | ECDSAP256SHA256: crypto.SHA256, 73 | ECDSAP384SHA384: crypto.SHA384, 74 | RSASHA512: crypto.SHA512, 75 | } 76 | 77 | // DNSSEC hashing algorithm codes. 78 | const ( 79 | _ uint8 = iota 80 | SHA1 // RFC 4034 81 | SHA256 // RFC 4509 82 | GOST94 // RFC 5933 83 | SHA384 // Experimental 84 | SHA512 // Experimental 85 | ) 86 | 87 | // Map for hash names. 88 | var HashToString = map[uint8]string{ 89 | SHA1: "SHA1", 90 | SHA256: "SHA256", 91 | GOST94: "GOST94", 92 | SHA384: "SHA384", 93 | SHA512: "SHA512", 94 | } 95 | 96 | // Map of hash strings. 97 | var StringToHash = reverseInt8(HashToString) 98 | 99 | // DNSKEY flag values. 100 | const ( 101 | SEP = 1 102 | REVOKE = 1 << 7 103 | ZONE = 1 << 8 104 | ) 105 | 106 | // The RRSIG needs to be converted to wireformat with some of 107 | // the rdata (the signature) missing. Use this struct to ease 108 | // the conversion (and re-use the pack/unpack functions). 109 | type rrsigWireFmt struct { 110 | TypeCovered uint16 111 | Algorithm uint8 112 | Labels uint8 113 | OrigTtl uint32 114 | Expiration uint32 115 | Inception uint32 116 | KeyTag uint16 117 | SignerName string `dns:"domain-name"` 118 | /* No Signature */ 119 | } 120 | 121 | // Used for converting DNSKEY's rdata to wirefmt. 122 | type dnskeyWireFmt struct { 123 | Flags uint16 124 | Protocol uint8 125 | Algorithm uint8 126 | PublicKey string `dns:"base64"` 127 | /* Nothing is left out */ 128 | } 129 | 130 | func divRoundUp(a, b int) int { 131 | return (a + b - 1) / b 132 | } 133 | 134 | // KeyTag calculates the keytag (or key-id) of the DNSKEY. 135 | func (k *DNSKEY) KeyTag() uint16 { 136 | if k == nil { 137 | return 0 138 | } 139 | var keytag int 140 | switch k.Algorithm { 141 | case RSAMD5: 142 | // Look at the bottom two bytes of the modules, which the last 143 | // item in the pubkey. We could do this faster by looking directly 144 | // at the base64 values. But I'm lazy. 145 | modulus, _ := fromBase64([]byte(k.PublicKey)) 146 | if len(modulus) > 1 { 147 | x, _ := unpackUint16(modulus, len(modulus)-2) 148 | keytag = int(x) 149 | } 150 | default: 151 | keywire := new(dnskeyWireFmt) 152 | keywire.Flags = k.Flags 153 | keywire.Protocol = k.Protocol 154 | keywire.Algorithm = k.Algorithm 155 | keywire.PublicKey = k.PublicKey 156 | wire := make([]byte, DefaultMsgSize) 157 | n, err := PackStruct(keywire, wire, 0) 158 | if err != nil { 159 | return 0 160 | } 161 | wire = wire[:n] 162 | for i, v := range wire { 163 | if i&1 != 0 { 164 | keytag += int(v) // must be larger than uint32 165 | } else { 166 | keytag += int(v) << 8 167 | } 168 | } 169 | keytag += (keytag >> 16) & 0xFFFF 170 | keytag &= 0xFFFF 171 | } 172 | return uint16(keytag) 173 | } 174 | 175 | // ToDS converts a DNSKEY record to a DS record. 176 | func (k *DNSKEY) ToDS(h uint8) *DS { 177 | if k == nil { 178 | return nil 179 | } 180 | ds := new(DS) 181 | ds.Hdr.Name = k.Hdr.Name 182 | ds.Hdr.Class = k.Hdr.Class 183 | ds.Hdr.Rrtype = TypeDS 184 | ds.Hdr.Ttl = k.Hdr.Ttl 185 | ds.Algorithm = k.Algorithm 186 | ds.DigestType = h 187 | ds.KeyTag = k.KeyTag() 188 | 189 | keywire := new(dnskeyWireFmt) 190 | keywire.Flags = k.Flags 191 | keywire.Protocol = k.Protocol 192 | keywire.Algorithm = k.Algorithm 193 | keywire.PublicKey = k.PublicKey 194 | wire := make([]byte, DefaultMsgSize) 195 | n, err := PackStruct(keywire, wire, 0) 196 | if err != nil { 197 | return nil 198 | } 199 | wire = wire[:n] 200 | 201 | owner := make([]byte, 255) 202 | off, err1 := PackDomainName(strings.ToLower(k.Hdr.Name), owner, 0, nil, false) 203 | if err1 != nil { 204 | return nil 205 | } 206 | owner = owner[:off] 207 | // RFC4034: 208 | // digest = digest_algorithm( DNSKEY owner name | DNSKEY RDATA); 209 | // "|" denotes concatenation 210 | // DNSKEY RDATA = Flags | Protocol | Algorithm | Public Key. 211 | 212 | // digest buffer 213 | digest := append(owner, wire...) // another copy 214 | 215 | var hash crypto.Hash 216 | switch h { 217 | case SHA1: 218 | hash = crypto.SHA1 219 | case SHA256: 220 | hash = crypto.SHA256 221 | case SHA384: 222 | hash = crypto.SHA384 223 | case SHA512: 224 | hash = crypto.SHA512 225 | default: 226 | return nil 227 | } 228 | 229 | s := hash.New() 230 | s.Write(digest) 231 | ds.Digest = hex.EncodeToString(s.Sum(nil)) 232 | return ds 233 | } 234 | 235 | // ToCDNSKEY converts a DNSKEY record to a CDNSKEY record. 236 | func (k *DNSKEY) ToCDNSKEY() *CDNSKEY { 237 | c := &CDNSKEY{DNSKEY: *k} 238 | c.Hdr = *k.Hdr.copyHeader() 239 | c.Hdr.Rrtype = TypeCDNSKEY 240 | return c 241 | } 242 | 243 | // ToCDS converts a DS record to a CDS record. 244 | func (d *DS) ToCDS() *CDS { 245 | c := &CDS{DS: *d} 246 | c.Hdr = *d.Hdr.copyHeader() 247 | c.Hdr.Rrtype = TypeCDS 248 | return c 249 | } 250 | 251 | // Sign signs an RRSet. The signature needs to be filled in with the values: 252 | // Inception, Expiration, KeyTag, SignerName and Algorithm. The rest is copied 253 | // from the RRset. Sign returns a non-nill error when the signing went OK. 254 | // There is no check if RRSet is a proper (RFC 2181) RRSet. If OrigTTL is non 255 | // zero, it is used as-is, otherwise the TTL of the RRset is used as the 256 | // OrigTTL. 257 | func (rr *RRSIG) Sign(k crypto.Signer, rrset []RR) error { 258 | if k == nil { 259 | return ErrPrivKey 260 | } 261 | // s.Inception and s.Expiration may be 0 (rollover etc.), the rest must be set 262 | if rr.KeyTag == 0 || len(rr.SignerName) == 0 || rr.Algorithm == 0 { 263 | return ErrKey 264 | } 265 | 266 | rr.Hdr.Rrtype = TypeRRSIG 267 | rr.Hdr.Name = rrset[0].Header().Name 268 | rr.Hdr.Class = rrset[0].Header().Class 269 | if rr.OrigTtl == 0 { // If set don't override 270 | rr.OrigTtl = rrset[0].Header().Ttl 271 | } 272 | rr.TypeCovered = rrset[0].Header().Rrtype 273 | rr.Labels = uint8(CountLabel(rrset[0].Header().Name)) 274 | 275 | if strings.HasPrefix(rrset[0].Header().Name, "*") { 276 | rr.Labels-- // wildcard, remove from label count 277 | } 278 | 279 | sigwire := new(rrsigWireFmt) 280 | sigwire.TypeCovered = rr.TypeCovered 281 | sigwire.Algorithm = rr.Algorithm 282 | sigwire.Labels = rr.Labels 283 | sigwire.OrigTtl = rr.OrigTtl 284 | sigwire.Expiration = rr.Expiration 285 | sigwire.Inception = rr.Inception 286 | sigwire.KeyTag = rr.KeyTag 287 | // For signing, lowercase this name 288 | sigwire.SignerName = strings.ToLower(rr.SignerName) 289 | 290 | // Create the desired binary blob 291 | signdata := make([]byte, DefaultMsgSize) 292 | n, err := PackStruct(sigwire, signdata, 0) 293 | if err != nil { 294 | return err 295 | } 296 | signdata = signdata[:n] 297 | wire, err := rawSignatureData(rrset, rr) 298 | if err != nil { 299 | return err 300 | } 301 | signdata = append(signdata, wire...) 302 | 303 | hash, ok := AlgorithmToHash[rr.Algorithm] 304 | if !ok { 305 | return ErrAlg 306 | } 307 | 308 | h := hash.New() 309 | h.Write(signdata) 310 | 311 | signature, err := sign(k, h.Sum(nil), hash, rr.Algorithm) 312 | if err != nil { 313 | return err 314 | } 315 | 316 | rr.Signature = toBase64(signature) 317 | 318 | return nil 319 | } 320 | 321 | func sign(k crypto.Signer, hashed []byte, hash crypto.Hash, alg uint8) ([]byte, error) { 322 | signature, err := k.Sign(rand.Reader, hashed, hash) 323 | if err != nil { 324 | return nil, err 325 | } 326 | 327 | switch alg { 328 | case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512: 329 | return signature, nil 330 | 331 | case ECDSAP256SHA256, ECDSAP384SHA384: 332 | ecdsaSignature := &struct { 333 | R, S *big.Int 334 | }{} 335 | if _, err := asn1.Unmarshal(signature, ecdsaSignature); err != nil { 336 | return nil, err 337 | } 338 | 339 | var intlen int 340 | switch alg { 341 | case ECDSAP256SHA256: 342 | intlen = 32 343 | case ECDSAP384SHA384: 344 | intlen = 48 345 | } 346 | 347 | signature := intToBytes(ecdsaSignature.R, intlen) 348 | signature = append(signature, intToBytes(ecdsaSignature.S, intlen)...) 349 | return signature, nil 350 | 351 | // There is no defined interface for what a DSA backed crypto.Signer returns 352 | case DSA, DSANSEC3SHA1: 353 | // t := divRoundUp(divRoundUp(p.PublicKey.Y.BitLen(), 8)-64, 8) 354 | // signature := []byte{byte(t)} 355 | // signature = append(signature, intToBytes(r1, 20)...) 356 | // signature = append(signature, intToBytes(s1, 20)...) 357 | // rr.Signature = signature 358 | } 359 | 360 | return nil, ErrAlg 361 | } 362 | 363 | // Verify validates an RRSet with the signature and key. This is only the 364 | // cryptographic test, the signature validity period must be checked separately. 365 | // This function copies the rdata of some RRs (to lowercase domain names) for the validation to work. 366 | func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error { 367 | // First the easy checks 368 | if !IsRRset(rrset) { 369 | return ErrRRset 370 | } 371 | if rr.KeyTag != k.KeyTag() { 372 | return ErrKey 373 | } 374 | if rr.Hdr.Class != k.Hdr.Class { 375 | return ErrKey 376 | } 377 | if rr.Algorithm != k.Algorithm { 378 | return ErrKey 379 | } 380 | if strings.ToLower(rr.SignerName) != strings.ToLower(k.Hdr.Name) { 381 | return ErrKey 382 | } 383 | if k.Protocol != 3 { 384 | return ErrKey 385 | } 386 | 387 | // IsRRset checked that we have at least one RR and that the RRs in 388 | // the set have consistent type, class, and name. Also check that type and 389 | // class matches the RRSIG record. 390 | if rrset[0].Header().Class != rr.Hdr.Class { 391 | return ErrRRset 392 | } 393 | if rrset[0].Header().Rrtype != rr.TypeCovered { 394 | return ErrRRset 395 | } 396 | 397 | // RFC 4035 5.3.2. Reconstructing the Signed Data 398 | // Copy the sig, except the rrsig data 399 | sigwire := new(rrsigWireFmt) 400 | sigwire.TypeCovered = rr.TypeCovered 401 | sigwire.Algorithm = rr.Algorithm 402 | sigwire.Labels = rr.Labels 403 | sigwire.OrigTtl = rr.OrigTtl 404 | sigwire.Expiration = rr.Expiration 405 | sigwire.Inception = rr.Inception 406 | sigwire.KeyTag = rr.KeyTag 407 | sigwire.SignerName = strings.ToLower(rr.SignerName) 408 | // Create the desired binary blob 409 | signeddata := make([]byte, DefaultMsgSize) 410 | n, err := PackStruct(sigwire, signeddata, 0) 411 | if err != nil { 412 | return err 413 | } 414 | signeddata = signeddata[:n] 415 | wire, err := rawSignatureData(rrset, rr) 416 | if err != nil { 417 | return err 418 | } 419 | signeddata = append(signeddata, wire...) 420 | 421 | sigbuf := rr.sigBuf() // Get the binary signature data 422 | if rr.Algorithm == PRIVATEDNS { // PRIVATEOID 423 | // TODO(miek) 424 | // remove the domain name and assume its ours? 425 | } 426 | 427 | hash, ok := AlgorithmToHash[rr.Algorithm] 428 | if !ok { 429 | return ErrAlg 430 | } 431 | 432 | switch rr.Algorithm { 433 | case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512, RSAMD5: 434 | // TODO(mg): this can be done quicker, ie. cache the pubkey data somewhere?? 435 | pubkey := k.publicKeyRSA() // Get the key 436 | if pubkey == nil { 437 | return ErrKey 438 | } 439 | 440 | h := hash.New() 441 | h.Write(signeddata) 442 | return rsa.VerifyPKCS1v15(pubkey, hash, h.Sum(nil), sigbuf) 443 | 444 | case ECDSAP256SHA256, ECDSAP384SHA384: 445 | pubkey := k.publicKeyECDSA() 446 | if pubkey == nil { 447 | return ErrKey 448 | } 449 | 450 | // Split sigbuf into the r and s coordinates 451 | r := new(big.Int).SetBytes(sigbuf[:len(sigbuf)/2]) 452 | s := new(big.Int).SetBytes(sigbuf[len(sigbuf)/2:]) 453 | 454 | h := hash.New() 455 | h.Write(signeddata) 456 | if ecdsa.Verify(pubkey, h.Sum(nil), r, s) { 457 | return nil 458 | } 459 | return ErrSig 460 | 461 | default: 462 | return ErrAlg 463 | } 464 | } 465 | 466 | // ValidityPeriod uses RFC1982 serial arithmetic to calculate 467 | // if a signature period is valid. If t is the zero time, the 468 | // current time is taken other t is. Returns true if the signature 469 | // is valid at the given time, otherwise returns false. 470 | func (rr *RRSIG) ValidityPeriod(t time.Time) bool { 471 | var utc int64 472 | if t.IsZero() { 473 | utc = time.Now().UTC().Unix() 474 | } else { 475 | utc = t.UTC().Unix() 476 | } 477 | modi := (int64(rr.Inception) - utc) / year68 478 | mode := (int64(rr.Expiration) - utc) / year68 479 | ti := int64(rr.Inception) + (modi * year68) 480 | te := int64(rr.Expiration) + (mode * year68) 481 | return ti <= utc && utc <= te 482 | } 483 | 484 | // Return the signatures base64 encodedig sigdata as a byte slice. 485 | func (rr *RRSIG) sigBuf() []byte { 486 | sigbuf, err := fromBase64([]byte(rr.Signature)) 487 | if err != nil { 488 | return nil 489 | } 490 | return sigbuf 491 | } 492 | 493 | // publicKeyRSA returns the RSA public key from a DNSKEY record. 494 | func (k *DNSKEY) publicKeyRSA() *rsa.PublicKey { 495 | keybuf, err := fromBase64([]byte(k.PublicKey)) 496 | if err != nil { 497 | return nil 498 | } 499 | 500 | // RFC 2537/3110, section 2. RSA Public KEY Resource Records 501 | // Length is in the 0th byte, unless its zero, then it 502 | // it in bytes 1 and 2 and its a 16 bit number 503 | explen := uint16(keybuf[0]) 504 | keyoff := 1 505 | if explen == 0 { 506 | explen = uint16(keybuf[1])<<8 | uint16(keybuf[2]) 507 | keyoff = 3 508 | } 509 | pubkey := new(rsa.PublicKey) 510 | 511 | pubkey.N = big.NewInt(0) 512 | shift := uint64((explen - 1) * 8) 513 | expo := uint64(0) 514 | for i := int(explen - 1); i > 0; i-- { 515 | expo += uint64(keybuf[keyoff+i]) << shift 516 | shift -= 8 517 | } 518 | // Remainder 519 | expo += uint64(keybuf[keyoff]) 520 | if expo > 2<<31 { 521 | // Larger expo than supported. 522 | // println("dns: F5 primes (or larger) are not supported") 523 | return nil 524 | } 525 | pubkey.E = int(expo) 526 | 527 | pubkey.N.SetBytes(keybuf[keyoff+int(explen):]) 528 | return pubkey 529 | } 530 | 531 | // publicKeyECDSA returns the Curve public key from the DNSKEY record. 532 | func (k *DNSKEY) publicKeyECDSA() *ecdsa.PublicKey { 533 | keybuf, err := fromBase64([]byte(k.PublicKey)) 534 | if err != nil { 535 | return nil 536 | } 537 | pubkey := new(ecdsa.PublicKey) 538 | switch k.Algorithm { 539 | case ECDSAP256SHA256: 540 | pubkey.Curve = elliptic.P256() 541 | if len(keybuf) != 64 { 542 | // wrongly encoded key 543 | return nil 544 | } 545 | case ECDSAP384SHA384: 546 | pubkey.Curve = elliptic.P384() 547 | if len(keybuf) != 96 { 548 | // Wrongly encoded key 549 | return nil 550 | } 551 | } 552 | pubkey.X = big.NewInt(0) 553 | pubkey.X.SetBytes(keybuf[:len(keybuf)/2]) 554 | pubkey.Y = big.NewInt(0) 555 | pubkey.Y.SetBytes(keybuf[len(keybuf)/2:]) 556 | return pubkey 557 | } 558 | 559 | func (k *DNSKEY) publicKeyDSA() *dsa.PublicKey { 560 | keybuf, err := fromBase64([]byte(k.PublicKey)) 561 | if err != nil { 562 | return nil 563 | } 564 | if len(keybuf) < 22 { 565 | return nil 566 | } 567 | t, keybuf := int(keybuf[0]), keybuf[1:] 568 | size := 64 + t*8 569 | q, keybuf := keybuf[:20], keybuf[20:] 570 | if len(keybuf) != 3*size { 571 | return nil 572 | } 573 | p, keybuf := keybuf[:size], keybuf[size:] 574 | g, y := keybuf[:size], keybuf[size:] 575 | pubkey := new(dsa.PublicKey) 576 | pubkey.Parameters.Q = big.NewInt(0).SetBytes(q) 577 | pubkey.Parameters.P = big.NewInt(0).SetBytes(p) 578 | pubkey.Parameters.G = big.NewInt(0).SetBytes(g) 579 | pubkey.Y = big.NewInt(0).SetBytes(y) 580 | return pubkey 581 | } 582 | 583 | type wireSlice [][]byte 584 | 585 | func (p wireSlice) Len() int { return len(p) } 586 | func (p wireSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 587 | func (p wireSlice) Less(i, j int) bool { 588 | _, ioff, _ := UnpackDomainName(p[i], 0) 589 | _, joff, _ := UnpackDomainName(p[j], 0) 590 | return bytes.Compare(p[i][ioff+10:], p[j][joff+10:]) < 0 591 | } 592 | 593 | // Return the raw signature data. 594 | func rawSignatureData(rrset []RR, s *RRSIG) (buf []byte, err error) { 595 | wires := make(wireSlice, len(rrset)) 596 | for i, r := range rrset { 597 | r1 := r.copy() 598 | r1.Header().Ttl = s.OrigTtl 599 | labels := SplitDomainName(r1.Header().Name) 600 | // 6.2. Canonical RR Form. (4) - wildcards 601 | if len(labels) > int(s.Labels) { 602 | // Wildcard 603 | r1.Header().Name = "*." + strings.Join(labels[len(labels)-int(s.Labels):], ".") + "." 604 | } 605 | // RFC 4034: 6.2. Canonical RR Form. (2) - domain name to lowercase 606 | r1.Header().Name = strings.ToLower(r1.Header().Name) 607 | // 6.2. Canonical RR Form. (3) - domain rdata to lowercase. 608 | // NS, MD, MF, CNAME, SOA, MB, MG, MR, PTR, 609 | // HINFO, MINFO, MX, RP, AFSDB, RT, SIG, PX, NXT, NAPTR, KX, 610 | // SRV, DNAME, A6 611 | // 612 | // RFC 6840 - Clarifications and Implementation Notes for DNS Security (DNSSEC): 613 | // Section 6.2 of [RFC4034] also erroneously lists HINFO as a record 614 | // that needs conversion to lowercase, and twice at that. Since HINFO 615 | // records contain no domain names, they are not subject to case 616 | // conversion. 617 | switch x := r1.(type) { 618 | case *NS: 619 | x.Ns = strings.ToLower(x.Ns) 620 | case *CNAME: 621 | x.Target = strings.ToLower(x.Target) 622 | case *SOA: 623 | x.Ns = strings.ToLower(x.Ns) 624 | x.Mbox = strings.ToLower(x.Mbox) 625 | case *MB: 626 | x.Mb = strings.ToLower(x.Mb) 627 | case *MG: 628 | x.Mg = strings.ToLower(x.Mg) 629 | case *MR: 630 | x.Mr = strings.ToLower(x.Mr) 631 | case *PTR: 632 | x.Ptr = strings.ToLower(x.Ptr) 633 | case *MINFO: 634 | x.Rmail = strings.ToLower(x.Rmail) 635 | x.Email = strings.ToLower(x.Email) 636 | case *MX: 637 | x.Mx = strings.ToLower(x.Mx) 638 | case *NAPTR: 639 | x.Replacement = strings.ToLower(x.Replacement) 640 | case *KX: 641 | x.Exchanger = strings.ToLower(x.Exchanger) 642 | case *SRV: 643 | x.Target = strings.ToLower(x.Target) 644 | case *DNAME: 645 | x.Target = strings.ToLower(x.Target) 646 | } 647 | // 6.2. Canonical RR Form. (5) - origTTL 648 | wire := make([]byte, r1.len()+1) // +1 to be safe(r) 649 | off, err1 := PackRR(r1, wire, 0, nil, false) 650 | if err1 != nil { 651 | return nil, err1 652 | } 653 | wire = wire[:off] 654 | wires[i] = wire 655 | } 656 | sort.Sort(wires) 657 | for i, wire := range wires { 658 | if i > 0 && bytes.Equal(wire, wires[i-1]) { 659 | continue 660 | } 661 | buf = append(buf, wire...) 662 | } 663 | return buf, nil 664 | } 665 | -------------------------------------------------------------------------------- /dnssec_keygen.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "crypto" 5 | "crypto/dsa" 6 | "crypto/ecdsa" 7 | "crypto/elliptic" 8 | "crypto/rand" 9 | "crypto/rsa" 10 | "math/big" 11 | ) 12 | 13 | // Generate generates a DNSKEY of the given bit size. 14 | // The public part is put inside the DNSKEY record. 15 | // The Algorithm in the key must be set as this will define 16 | // what kind of DNSKEY will be generated. 17 | // The ECDSA algorithms imply a fixed keysize, in that case 18 | // bits should be set to the size of the algorithm. 19 | func (k *DNSKEY) Generate(bits int) (crypto.PrivateKey, error) { 20 | switch k.Algorithm { 21 | case DSA, DSANSEC3SHA1: 22 | if bits != 1024 { 23 | return nil, ErrKeySize 24 | } 25 | case RSAMD5, RSASHA1, RSASHA256, RSASHA1NSEC3SHA1: 26 | if bits < 512 || bits > 4096 { 27 | return nil, ErrKeySize 28 | } 29 | case RSASHA512: 30 | if bits < 1024 || bits > 4096 { 31 | return nil, ErrKeySize 32 | } 33 | case ECDSAP256SHA256: 34 | if bits != 256 { 35 | return nil, ErrKeySize 36 | } 37 | case ECDSAP384SHA384: 38 | if bits != 384 { 39 | return nil, ErrKeySize 40 | } 41 | } 42 | 43 | switch k.Algorithm { 44 | case DSA, DSANSEC3SHA1: 45 | params := new(dsa.Parameters) 46 | if err := dsa.GenerateParameters(params, rand.Reader, dsa.L1024N160); err != nil { 47 | return nil, err 48 | } 49 | priv := new(dsa.PrivateKey) 50 | priv.PublicKey.Parameters = *params 51 | err := dsa.GenerateKey(priv, rand.Reader) 52 | if err != nil { 53 | return nil, err 54 | } 55 | k.setPublicKeyDSA(params.Q, params.P, params.G, priv.PublicKey.Y) 56 | return priv, nil 57 | case RSAMD5, RSASHA1, RSASHA256, RSASHA512, RSASHA1NSEC3SHA1: 58 | priv, err := rsa.GenerateKey(rand.Reader, bits) 59 | if err != nil { 60 | return nil, err 61 | } 62 | k.setPublicKeyRSA(priv.PublicKey.E, priv.PublicKey.N) 63 | return priv, nil 64 | case ECDSAP256SHA256, ECDSAP384SHA384: 65 | var c elliptic.Curve 66 | switch k.Algorithm { 67 | case ECDSAP256SHA256: 68 | c = elliptic.P256() 69 | case ECDSAP384SHA384: 70 | c = elliptic.P384() 71 | } 72 | priv, err := ecdsa.GenerateKey(c, rand.Reader) 73 | if err != nil { 74 | return nil, err 75 | } 76 | k.setPublicKeyECDSA(priv.PublicKey.X, priv.PublicKey.Y) 77 | return priv, nil 78 | default: 79 | return nil, ErrAlg 80 | } 81 | } 82 | 83 | // Set the public key (the value E and N) 84 | func (k *DNSKEY) setPublicKeyRSA(_E int, _N *big.Int) bool { 85 | if _E == 0 || _N == nil { 86 | return false 87 | } 88 | buf := exponentToBuf(_E) 89 | buf = append(buf, _N.Bytes()...) 90 | k.PublicKey = toBase64(buf) 91 | return true 92 | } 93 | 94 | // Set the public key for Elliptic Curves 95 | func (k *DNSKEY) setPublicKeyECDSA(_X, _Y *big.Int) bool { 96 | if _X == nil || _Y == nil { 97 | return false 98 | } 99 | var intlen int 100 | switch k.Algorithm { 101 | case ECDSAP256SHA256: 102 | intlen = 32 103 | case ECDSAP384SHA384: 104 | intlen = 48 105 | } 106 | k.PublicKey = toBase64(curveToBuf(_X, _Y, intlen)) 107 | return true 108 | } 109 | 110 | // Set the public key for DSA 111 | func (k *DNSKEY) setPublicKeyDSA(_Q, _P, _G, _Y *big.Int) bool { 112 | if _Q == nil || _P == nil || _G == nil || _Y == nil { 113 | return false 114 | } 115 | buf := dsaToBuf(_Q, _P, _G, _Y) 116 | k.PublicKey = toBase64(buf) 117 | return true 118 | } 119 | 120 | // Set the public key (the values E and N) for RSA 121 | // RFC 3110: Section 2. RSA Public KEY Resource Records 122 | func exponentToBuf(_E int) []byte { 123 | var buf []byte 124 | i := big.NewInt(int64(_E)) 125 | if len(i.Bytes()) < 256 { 126 | buf = make([]byte, 1) 127 | buf[0] = uint8(len(i.Bytes())) 128 | } else { 129 | buf = make([]byte, 3) 130 | buf[0] = 0 131 | buf[1] = uint8(len(i.Bytes()) >> 8) 132 | buf[2] = uint8(len(i.Bytes())) 133 | } 134 | buf = append(buf, i.Bytes()...) 135 | return buf 136 | } 137 | 138 | // Set the public key for X and Y for Curve. The two 139 | // values are just concatenated. 140 | func curveToBuf(_X, _Y *big.Int, intlen int) []byte { 141 | buf := intToBytes(_X, intlen) 142 | buf = append(buf, intToBytes(_Y, intlen)...) 143 | return buf 144 | } 145 | 146 | // Set the public key for X and Y for Curve. The two 147 | // values are just concatenated. 148 | func dsaToBuf(_Q, _P, _G, _Y *big.Int) []byte { 149 | t := divRoundUp(divRoundUp(_G.BitLen(), 8)-64, 8) 150 | buf := []byte{byte(t)} 151 | buf = append(buf, intToBytes(_Q, 20)...) 152 | buf = append(buf, intToBytes(_P, 64+t*8)...) 153 | buf = append(buf, intToBytes(_G, 64+t*8)...) 154 | buf = append(buf, intToBytes(_Y, 64+t*8)...) 155 | return buf 156 | } 157 | -------------------------------------------------------------------------------- /dnssec_keyscan.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "crypto" 5 | "crypto/dsa" 6 | "crypto/ecdsa" 7 | "crypto/rsa" 8 | "io" 9 | "math/big" 10 | "strconv" 11 | "strings" 12 | ) 13 | 14 | // NewPrivateKey returns a PrivateKey by parsing the string s. 15 | // s should be in the same form of the BIND private key files. 16 | func (k *DNSKEY) NewPrivateKey(s string) (crypto.PrivateKey, error) { 17 | if s[len(s)-1] != '\n' { // We need a closing newline 18 | return k.ReadPrivateKey(strings.NewReader(s+"\n"), "") 19 | } 20 | return k.ReadPrivateKey(strings.NewReader(s), "") 21 | } 22 | 23 | // ReadPrivateKey reads a private key from the io.Reader q. The string file is 24 | // only used in error reporting. 25 | // The public key must be known, because some cryptographic algorithms embed 26 | // the public inside the privatekey. 27 | func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, error) { 28 | m, e := parseKey(q, file) 29 | if m == nil { 30 | return nil, e 31 | } 32 | if _, ok := m["private-key-format"]; !ok { 33 | return nil, ErrPrivKey 34 | } 35 | if m["private-key-format"] != "v1.2" && m["private-key-format"] != "v1.3" { 36 | return nil, ErrPrivKey 37 | } 38 | // TODO(mg): check if the pubkey matches the private key 39 | algo, err := strconv.Atoi(strings.SplitN(m["algorithm"], " ", 2)[0]) 40 | if err != nil { 41 | return nil, ErrPrivKey 42 | } 43 | switch uint8(algo) { 44 | case DSA: 45 | priv, e := readPrivateKeyDSA(m) 46 | if e != nil { 47 | return nil, e 48 | } 49 | pub := k.publicKeyDSA() 50 | if pub == nil { 51 | return nil, ErrKey 52 | } 53 | priv.PublicKey = *pub 54 | return priv, e 55 | case RSAMD5: 56 | fallthrough 57 | case RSASHA1: 58 | fallthrough 59 | case RSASHA1NSEC3SHA1: 60 | fallthrough 61 | case RSASHA256: 62 | fallthrough 63 | case RSASHA512: 64 | priv, e := readPrivateKeyRSA(m) 65 | if e != nil { 66 | return nil, e 67 | } 68 | pub := k.publicKeyRSA() 69 | if pub == nil { 70 | return nil, ErrKey 71 | } 72 | priv.PublicKey = *pub 73 | return priv, e 74 | case ECCGOST: 75 | return nil, ErrPrivKey 76 | case ECDSAP256SHA256: 77 | fallthrough 78 | case ECDSAP384SHA384: 79 | priv, e := readPrivateKeyECDSA(m) 80 | if e != nil { 81 | return nil, e 82 | } 83 | pub := k.publicKeyECDSA() 84 | if pub == nil { 85 | return nil, ErrKey 86 | } 87 | priv.PublicKey = *pub 88 | return priv, e 89 | default: 90 | return nil, ErrPrivKey 91 | } 92 | } 93 | 94 | // Read a private key (file) string and create a public key. Return the private key. 95 | func readPrivateKeyRSA(m map[string]string) (*rsa.PrivateKey, error) { 96 | p := new(rsa.PrivateKey) 97 | p.Primes = []*big.Int{nil, nil} 98 | for k, v := range m { 99 | switch k { 100 | case "modulus", "publicexponent", "privateexponent", "prime1", "prime2": 101 | v1, err := fromBase64([]byte(v)) 102 | if err != nil { 103 | return nil, err 104 | } 105 | switch k { 106 | case "modulus": 107 | p.PublicKey.N = big.NewInt(0) 108 | p.PublicKey.N.SetBytes(v1) 109 | case "publicexponent": 110 | i := big.NewInt(0) 111 | i.SetBytes(v1) 112 | p.PublicKey.E = int(i.Int64()) // int64 should be large enough 113 | case "privateexponent": 114 | p.D = big.NewInt(0) 115 | p.D.SetBytes(v1) 116 | case "prime1": 117 | p.Primes[0] = big.NewInt(0) 118 | p.Primes[0].SetBytes(v1) 119 | case "prime2": 120 | p.Primes[1] = big.NewInt(0) 121 | p.Primes[1].SetBytes(v1) 122 | } 123 | case "exponent1", "exponent2", "coefficient": 124 | // not used in Go (yet) 125 | case "created", "publish", "activate": 126 | // not used in Go (yet) 127 | } 128 | } 129 | return p, nil 130 | } 131 | 132 | func readPrivateKeyDSA(m map[string]string) (*dsa.PrivateKey, error) { 133 | p := new(dsa.PrivateKey) 134 | p.X = big.NewInt(0) 135 | for k, v := range m { 136 | switch k { 137 | case "private_value(x)": 138 | v1, err := fromBase64([]byte(v)) 139 | if err != nil { 140 | return nil, err 141 | } 142 | p.X.SetBytes(v1) 143 | case "created", "publish", "activate": 144 | /* not used in Go (yet) */ 145 | } 146 | } 147 | return p, nil 148 | } 149 | 150 | func readPrivateKeyECDSA(m map[string]string) (*ecdsa.PrivateKey, error) { 151 | p := new(ecdsa.PrivateKey) 152 | p.D = big.NewInt(0) 153 | // TODO: validate that the required flags are present 154 | for k, v := range m { 155 | switch k { 156 | case "privatekey": 157 | v1, err := fromBase64([]byte(v)) 158 | if err != nil { 159 | return nil, err 160 | } 161 | p.D.SetBytes(v1) 162 | case "created", "publish", "activate": 163 | /* not used in Go (yet) */ 164 | } 165 | } 166 | return p, nil 167 | } 168 | 169 | // parseKey reads a private key from r. It returns a map[string]string, 170 | // with the key-value pairs, or an error when the file is not correct. 171 | func parseKey(r io.Reader, file string) (map[string]string, error) { 172 | s := scanInit(r) 173 | m := make(map[string]string) 174 | c := make(chan lex) 175 | k := "" 176 | // Start the lexer 177 | go klexer(s, c) 178 | for l := range c { 179 | // It should alternate 180 | switch l.value { 181 | case zKey: 182 | k = l.token 183 | case zValue: 184 | if k == "" { 185 | return nil, &ParseError{file, "no private key seen", l} 186 | } 187 | //println("Setting", strings.ToLower(k), "to", l.token, "b") 188 | m[strings.ToLower(k)] = l.token 189 | k = "" 190 | } 191 | } 192 | return m, nil 193 | } 194 | 195 | // klexer scans the sourcefile and returns tokens on the channel c. 196 | func klexer(s *scan, c chan lex) { 197 | var l lex 198 | str := "" // Hold the current read text 199 | commt := false 200 | key := true 201 | x, err := s.tokenText() 202 | defer close(c) 203 | for err == nil { 204 | l.column = s.position.Column 205 | l.line = s.position.Line 206 | switch x { 207 | case ':': 208 | if commt { 209 | break 210 | } 211 | l.token = str 212 | if key { 213 | l.value = zKey 214 | c <- l 215 | // Next token is a space, eat it 216 | s.tokenText() 217 | key = false 218 | str = "" 219 | } else { 220 | l.value = zValue 221 | } 222 | case ';': 223 | commt = true 224 | case '\n': 225 | if commt { 226 | // Reset a comment 227 | commt = false 228 | } 229 | l.value = zValue 230 | l.token = str 231 | c <- l 232 | str = "" 233 | commt = false 234 | key = true 235 | default: 236 | if commt { 237 | break 238 | } 239 | str += string(x) 240 | } 241 | x, err = s.tokenText() 242 | } 243 | if len(str) > 0 { 244 | // Send remainder 245 | l.token = str 246 | l.value = zValue 247 | c <- l 248 | } 249 | } 250 | -------------------------------------------------------------------------------- /dnssec_privkey.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "crypto" 5 | "crypto/dsa" 6 | "crypto/ecdsa" 7 | "crypto/rsa" 8 | "math/big" 9 | "strconv" 10 | ) 11 | 12 | const format = "Private-key-format: v1.3\n" 13 | 14 | // PrivateKeyString converts a PrivateKey to a string. This string has the same 15 | // format as the private-key-file of BIND9 (Private-key-format: v1.3). 16 | // It needs some info from the key (the algorithm), so its a method of the DNSKEY 17 | // It supports rsa.PrivateKey, ecdsa.PrivateKey and dsa.PrivateKey 18 | func (r *DNSKEY) PrivateKeyString(p crypto.PrivateKey) string { 19 | algorithm := strconv.Itoa(int(r.Algorithm)) 20 | algorithm += " (" + AlgorithmToString[r.Algorithm] + ")" 21 | 22 | switch p := p.(type) { 23 | case *rsa.PrivateKey: 24 | modulus := toBase64(p.PublicKey.N.Bytes()) 25 | e := big.NewInt(int64(p.PublicKey.E)) 26 | publicExponent := toBase64(e.Bytes()) 27 | privateExponent := toBase64(p.D.Bytes()) 28 | prime1 := toBase64(p.Primes[0].Bytes()) 29 | prime2 := toBase64(p.Primes[1].Bytes()) 30 | // Calculate Exponent1/2 and Coefficient as per: http://en.wikipedia.org/wiki/RSA#Using_the_Chinese_remainder_algorithm 31 | // and from: http://code.google.com/p/go/issues/detail?id=987 32 | one := big.NewInt(1) 33 | p1 := big.NewInt(0).Sub(p.Primes[0], one) 34 | q1 := big.NewInt(0).Sub(p.Primes[1], one) 35 | exp1 := big.NewInt(0).Mod(p.D, p1) 36 | exp2 := big.NewInt(0).Mod(p.D, q1) 37 | coeff := big.NewInt(0).ModInverse(p.Primes[1], p.Primes[0]) 38 | 39 | exponent1 := toBase64(exp1.Bytes()) 40 | exponent2 := toBase64(exp2.Bytes()) 41 | coefficient := toBase64(coeff.Bytes()) 42 | 43 | return format + 44 | "Algorithm: " + algorithm + "\n" + 45 | "Modulus: " + modulus + "\n" + 46 | "PublicExponent: " + publicExponent + "\n" + 47 | "PrivateExponent: " + privateExponent + "\n" + 48 | "Prime1: " + prime1 + "\n" + 49 | "Prime2: " + prime2 + "\n" + 50 | "Exponent1: " + exponent1 + "\n" + 51 | "Exponent2: " + exponent2 + "\n" + 52 | "Coefficient: " + coefficient + "\n" 53 | 54 | case *ecdsa.PrivateKey: 55 | var intlen int 56 | switch r.Algorithm { 57 | case ECDSAP256SHA256: 58 | intlen = 32 59 | case ECDSAP384SHA384: 60 | intlen = 48 61 | } 62 | private := toBase64(intToBytes(p.D, intlen)) 63 | return format + 64 | "Algorithm: " + algorithm + "\n" + 65 | "PrivateKey: " + private + "\n" 66 | 67 | case *dsa.PrivateKey: 68 | T := divRoundUp(divRoundUp(p.PublicKey.Parameters.G.BitLen(), 8)-64, 8) 69 | prime := toBase64(intToBytes(p.PublicKey.Parameters.P, 64+T*8)) 70 | subprime := toBase64(intToBytes(p.PublicKey.Parameters.Q, 20)) 71 | base := toBase64(intToBytes(p.PublicKey.Parameters.G, 64+T*8)) 72 | priv := toBase64(intToBytes(p.X, 20)) 73 | pub := toBase64(intToBytes(p.PublicKey.Y, 64+T*8)) 74 | return format + 75 | "Algorithm: " + algorithm + "\n" + 76 | "Prime(p): " + prime + "\n" + 77 | "Subprime(q): " + subprime + "\n" + 78 | "Base(g): " + base + "\n" + 79 | "Private_value(x): " + priv + "\n" + 80 | "Public_value(y): " + pub + "\n" 81 | 82 | default: 83 | return "" 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package dns implements a full featured interface to the Domain Name System. 3 | Server- and client-side programming is supported. 4 | The package allows complete control over what is send out to the DNS. The package 5 | API follows the less-is-more principle, by presenting a small, clean interface. 6 | 7 | The package dns supports (asynchronous) querying/replying, incoming/outgoing zone transfers, 8 | TSIG, EDNS0, dynamic updates, notifies and DNSSEC validation/signing. 9 | Note that domain names MUST be fully qualified, before sending them, unqualified 10 | names in a message will result in a packing failure. 11 | 12 | Resource records are native types. They are not stored in wire format. 13 | Basic usage pattern for creating a new resource record: 14 | 15 | r := new(dns.MX) 16 | r.Hdr = dns.RR_Header{Name: "miek.nl.", Rrtype: dns.TypeMX, 17 | Class: dns.ClassINET, Ttl: 3600} 18 | r.Preference = 10 19 | r.Mx = "mx.miek.nl." 20 | 21 | Or directly from a string: 22 | 23 | mx, err := dns.NewRR("miek.nl. 3600 IN MX 10 mx.miek.nl.") 24 | 25 | Or when the default TTL (3600) and class (IN) suit you: 26 | 27 | mx, err := dns.NewRR("miek.nl. MX 10 mx.miek.nl.") 28 | 29 | Or even: 30 | 31 | mx, err := dns.NewRR("$ORIGIN nl.\nmiek 1H IN MX 10 mx.miek") 32 | 33 | In the DNS messages are exchanged, these messages contain resource 34 | records (sets). Use pattern for creating a message: 35 | 36 | m := new(dns.Msg) 37 | m.SetQuestion("miek.nl.", dns.TypeMX) 38 | 39 | Or when not certain if the domain name is fully qualified: 40 | 41 | m.SetQuestion(dns.Fqdn("miek.nl"), dns.TypeMX) 42 | 43 | The message m is now a message with the question section set to ask 44 | the MX records for the miek.nl. zone. 45 | 46 | The following is slightly more verbose, but more flexible: 47 | 48 | m1 := new(dns.Msg) 49 | m1.Id = dns.Id() 50 | m1.RecursionDesired = true 51 | m1.Question = make([]dns.Question, 1) 52 | m1.Question[0] = dns.Question{"miek.nl.", dns.TypeMX, dns.ClassINET} 53 | 54 | After creating a message it can be send. 55 | Basic use pattern for synchronous querying the DNS at a 56 | server configured on 127.0.0.1 and port 53: 57 | 58 | c := new(dns.Client) 59 | in, rtt, err := c.Exchange(m1, "127.0.0.1:53") 60 | 61 | Suppressing multiple outstanding queries (with the same question, type and 62 | class) is as easy as setting: 63 | 64 | c.SingleInflight = true 65 | 66 | If these "advanced" features are not needed, a simple UDP query can be send, 67 | with: 68 | 69 | in, err := dns.Exchange(m1, "127.0.0.1:53") 70 | 71 | When this functions returns you will get dns message. A dns message consists 72 | out of four sections. 73 | The question section: in.Question, the answer section: in.Answer, 74 | the authority section: in.Ns and the additional section: in.Extra. 75 | 76 | Each of these sections (except the Question section) contain a []RR. Basic 77 | use pattern for accessing the rdata of a TXT RR as the first RR in 78 | the Answer section: 79 | 80 | if t, ok := in.Answer[0].(*dns.TXT); ok { 81 | // do something with t.Txt 82 | } 83 | 84 | Domain Name and TXT Character String Representations 85 | 86 | Both domain names and TXT character strings are converted to presentation 87 | form both when unpacked and when converted to strings. 88 | 89 | For TXT character strings, tabs, carriage returns and line feeds will be 90 | converted to \t, \r and \n respectively. Back slashes and quotations marks 91 | will be escaped. Bytes below 32 and above 127 will be converted to \DDD 92 | form. 93 | 94 | For domain names, in addition to the above rules brackets, periods, 95 | spaces, semicolons and the at symbol are escaped. 96 | 97 | DNSSEC 98 | 99 | DNSSEC (DNS Security Extension) adds a layer of security to the DNS. It 100 | uses public key cryptography to sign resource records. The 101 | public keys are stored in DNSKEY records and the signatures in RRSIG records. 102 | 103 | Requesting DNSSEC information for a zone is done by adding the DO (DNSSEC OK) bit 104 | to an request. 105 | 106 | m := new(dns.Msg) 107 | m.SetEdns0(4096, true) 108 | 109 | Signature generation, signature verification and key generation are all supported. 110 | 111 | DYNAMIC UPDATES 112 | 113 | Dynamic updates reuses the DNS message format, but renames three of 114 | the sections. Question is Zone, Answer is Prerequisite, Authority is 115 | Update, only the Additional is not renamed. See RFC 2136 for the gory details. 116 | 117 | You can set a rather complex set of rules for the existence of absence of 118 | certain resource records or names in a zone to specify if resource records 119 | should be added or removed. The table from RFC 2136 supplemented with the Go 120 | DNS function shows which functions exist to specify the prerequisites. 121 | 122 | 3.2.4 - Table Of Metavalues Used In Prerequisite Section 123 | 124 | CLASS TYPE RDATA Meaning Function 125 | -------------------------------------------------------------- 126 | ANY ANY empty Name is in use dns.NameUsed 127 | ANY rrset empty RRset exists (value indep) dns.RRsetUsed 128 | NONE ANY empty Name is not in use dns.NameNotUsed 129 | NONE rrset empty RRset does not exist dns.RRsetNotUsed 130 | zone rrset rr RRset exists (value dep) dns.Used 131 | 132 | The prerequisite section can also be left empty. 133 | If you have decided on the prerequisites you can tell what RRs should 134 | be added or deleted. The next table shows the options you have and 135 | what functions to call. 136 | 137 | 3.4.2.6 - Table Of Metavalues Used In Update Section 138 | 139 | CLASS TYPE RDATA Meaning Function 140 | --------------------------------------------------------------- 141 | ANY ANY empty Delete all RRsets from name dns.RemoveName 142 | ANY rrset empty Delete an RRset dns.RemoveRRset 143 | NONE rrset rr Delete an RR from RRset dns.Remove 144 | zone rrset rr Add to an RRset dns.Insert 145 | 146 | TRANSACTION SIGNATURE 147 | 148 | An TSIG or transaction signature adds a HMAC TSIG record to each message sent. 149 | The supported algorithms include: HmacMD5, HmacSHA1, HmacSHA256 and HmacSHA512. 150 | 151 | Basic use pattern when querying with a TSIG name "axfr." (note that these key names 152 | must be fully qualified - as they are domain names) and the base64 secret 153 | "so6ZGir4GPAqINNh9U5c3A==": 154 | 155 | c := new(dns.Client) 156 | c.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="} 157 | m := new(dns.Msg) 158 | m.SetQuestion("miek.nl.", dns.TypeMX) 159 | m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix()) 160 | ... 161 | // When sending the TSIG RR is calculated and filled in before sending 162 | 163 | When requesting an zone transfer (almost all TSIG usage is when requesting zone transfers), with 164 | TSIG, this is the basic use pattern. In this example we request an AXFR for 165 | miek.nl. with TSIG key named "axfr." and secret "so6ZGir4GPAqINNh9U5c3A==" 166 | and using the server 176.58.119.54: 167 | 168 | t := new(dns.Transfer) 169 | m := new(dns.Msg) 170 | t.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="} 171 | m.SetAxfr("miek.nl.") 172 | m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix()) 173 | c, err := t.In(m, "176.58.119.54:53") 174 | for r := range c { ... } 175 | 176 | You can now read the records from the transfer as they come in. Each envelope is checked with TSIG. 177 | If something is not correct an error is returned. 178 | 179 | Basic use pattern validating and replying to a message that has TSIG set. 180 | 181 | server := &dns.Server{Addr: ":53", Net: "udp"} 182 | server.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="} 183 | go server.ListenAndServe() 184 | dns.HandleFunc(".", handleRequest) 185 | 186 | func handleRequest(w dns.ResponseWriter, r *dns.Msg) { 187 | m := new(dns.Msg) 188 | m.SetReply(r) 189 | if r.IsTsig() { 190 | if w.TsigStatus() == nil { 191 | // *Msg r has an TSIG record and it was validated 192 | m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix()) 193 | } else { 194 | // *Msg r has an TSIG records and it was not valided 195 | } 196 | } 197 | w.WriteMsg(m) 198 | } 199 | 200 | PRIVATE RRS 201 | 202 | RFC 6895 sets aside a range of type codes for private use. This range 203 | is 65,280 - 65,534 (0xFF00 - 0xFFFE). When experimenting with new Resource Records these 204 | can be used, before requesting an official type code from IANA. 205 | 206 | see http://miek.nl/posts/2014/Sep/21/Private%20RRs%20and%20IDN%20in%20Go%20DNS/ for more 207 | information. 208 | 209 | EDNS0 210 | 211 | EDNS0 is an extension mechanism for the DNS defined in RFC 2671 and updated 212 | by RFC 6891. It defines an new RR type, the OPT RR, which is then completely 213 | abused. 214 | Basic use pattern for creating an (empty) OPT RR: 215 | 216 | o := new(dns.OPT) 217 | o.Hdr.Name = "." // MUST be the root zone, per definition. 218 | o.Hdr.Rrtype = dns.TypeOPT 219 | 220 | The rdata of an OPT RR consists out of a slice of EDNS0 (RFC 6891) 221 | interfaces. Currently only a few have been standardized: EDNS0_NSID 222 | (RFC 5001) and EDNS0_SUBNET (draft-vandergaast-edns-client-subnet-02). Note 223 | that these options may be combined in an OPT RR. 224 | Basic use pattern for a server to check if (and which) options are set: 225 | 226 | // o is a dns.OPT 227 | for _, s := range o.Option { 228 | switch e := s.(type) { 229 | case *dns.EDNS0_NSID: 230 | // do stuff with e.Nsid 231 | case *dns.EDNS0_SUBNET: 232 | // access e.Family, e.Address, etc. 233 | } 234 | } 235 | 236 | SIG(0) 237 | 238 | From RFC 2931: 239 | 240 | SIG(0) provides protection for DNS transactions and requests .... 241 | ... protection for glue records, DNS requests, protection for message headers 242 | on requests and responses, and protection of the overall integrity of a response. 243 | 244 | It works like TSIG, except that SIG(0) uses public key cryptography, instead of the shared 245 | secret approach in TSIG. 246 | Supported algorithms: DSA, ECDSAP256SHA256, ECDSAP384SHA384, RSASHA1, RSASHA256 and 247 | RSASHA512. 248 | 249 | Signing subsequent messages in multi-message sessions is not implemented. 250 | */ 251 | package dns 252 | -------------------------------------------------------------------------------- /dyn_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | // Find better solution 4 | -------------------------------------------------------------------------------- /edns.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "encoding/hex" 5 | "errors" 6 | "net" 7 | "strconv" 8 | ) 9 | 10 | // EDNS0 Option codes. 11 | const ( 12 | EDNS0LLQ = 0x1 // long lived queries: http://tools.ietf.org/html/draft-sekar-dns-llq-01 13 | EDNS0UL = 0x2 // update lease draft: http://files.dns-sd.org/draft-sekar-dns-ul.txt 14 | EDNS0NSID = 0x3 // nsid (RFC5001) 15 | EDNS0DAU = 0x5 // DNSSEC Algorithm Understood 16 | EDNS0DHU = 0x6 // DS Hash Understood 17 | EDNS0N3U = 0x7 // NSEC3 Hash Understood 18 | EDNS0SUBNET = 0x8 // client-subnet (RFC6891) 19 | EDNS0EXPIRE = 0x9 // EDNS0 expire 20 | EDNS0SUBNETDRAFT = 0x50fa // Don't use! Use EDNS0SUBNET 21 | EDNS0LOCALSTART = 0xFDE9 // Beginning of range reserved for local/experimental use (RFC6891) 22 | EDNS0LOCALEND = 0xFFFE // End of range reserved for local/experimental use (RFC6891) 23 | _DO = 1 << 15 // dnssec ok 24 | ) 25 | 26 | // OPT is the EDNS0 RR appended to messages to convey extra (meta) information. 27 | // See RFC 6891. 28 | type OPT struct { 29 | Hdr RR_Header 30 | Option []EDNS0 `dns:"opt"` 31 | } 32 | 33 | // Header implements the RR interface. 34 | func (rr *OPT) Header() *RR_Header { 35 | return &rr.Hdr 36 | } 37 | 38 | func (rr *OPT) String() string { 39 | s := "\n;; OPT PSEUDOSECTION:\n; EDNS: version " + strconv.Itoa(int(rr.Version())) + "; " 40 | if rr.Do() { 41 | s += "flags: do; " 42 | } else { 43 | s += "flags: ; " 44 | } 45 | s += "udp: " + strconv.Itoa(int(rr.UDPSize())) 46 | 47 | for _, o := range rr.Option { 48 | switch o.(type) { 49 | case *EDNS0_NSID: 50 | s += "\n; NSID: " + o.String() 51 | h, e := o.pack() 52 | var r string 53 | if e == nil { 54 | for _, c := range h { 55 | r += "(" + string(c) + ")" 56 | } 57 | s += " " + r 58 | } 59 | case *EDNS0_SUBNET: 60 | s += "\n; SUBNET: " + o.String() 61 | if o.(*EDNS0_SUBNET).DraftOption { 62 | s += " (draft)" 63 | } 64 | case *EDNS0_UL: 65 | s += "\n; UPDATE LEASE: " + o.String() 66 | case *EDNS0_LLQ: 67 | s += "\n; LONG LIVED QUERIES: " + o.String() 68 | case *EDNS0_DAU: 69 | s += "\n; DNSSEC ALGORITHM UNDERSTOOD: " + o.String() 70 | case *EDNS0_DHU: 71 | s += "\n; DS HASH UNDERSTOOD: " + o.String() 72 | case *EDNS0_N3U: 73 | s += "\n; NSEC3 HASH UNDERSTOOD: " + o.String() 74 | case *EDNS0_LOCAL: 75 | s += "\n; LOCAL OPT: " + o.String() 76 | } 77 | } 78 | return s 79 | } 80 | 81 | func (rr *OPT) len() int { 82 | l := rr.Hdr.len() 83 | for i := 0; i < len(rr.Option); i++ { 84 | l += 4 // Account for 2-byte option code and 2-byte option length. 85 | lo, _ := rr.Option[i].pack() 86 | l += len(lo) 87 | } 88 | return l 89 | } 90 | 91 | func (rr *OPT) copy() RR { 92 | return &OPT{*rr.Hdr.copyHeader(), rr.Option} 93 | } 94 | 95 | // return the old value -> delete SetVersion? 96 | 97 | // Version returns the EDNS version used. Only zero is defined. 98 | func (rr *OPT) Version() uint8 { 99 | return uint8((rr.Hdr.Ttl & 0x00FF0000) >> 16) 100 | } 101 | 102 | // SetVersion sets the version of EDNS. This is usually zero. 103 | func (rr *OPT) SetVersion(v uint8) { 104 | rr.Hdr.Ttl = rr.Hdr.Ttl&0xFF00FFFF | (uint32(v) << 16) 105 | } 106 | 107 | // ExtendedRcode returns the EDNS extended RCODE field (the upper 8 bits of the TTL). 108 | func (rr *OPT) ExtendedRcode() uint8 { 109 | return uint8((rr.Hdr.Ttl & 0xFF000000) >> 24) 110 | } 111 | 112 | // SetExtendedRcode sets the EDNS extended RCODE field. 113 | func (rr *OPT) SetExtendedRcode(v uint8) { 114 | rr.Hdr.Ttl = rr.Hdr.Ttl&0x00FFFFFF | (uint32(v) << 24) 115 | } 116 | 117 | // UDPSize returns the UDP buffer size. 118 | func (rr *OPT) UDPSize() uint16 { 119 | return rr.Hdr.Class 120 | } 121 | 122 | // SetUDPSize sets the UDP buffer size. 123 | func (rr *OPT) SetUDPSize(size uint16) { 124 | rr.Hdr.Class = size 125 | } 126 | 127 | // Do returns the value of the DO (DNSSEC OK) bit. 128 | func (rr *OPT) Do() bool { 129 | return rr.Hdr.Ttl&_DO == _DO 130 | } 131 | 132 | // SetDo sets the DO (DNSSEC OK) bit. 133 | func (rr *OPT) SetDo() { 134 | rr.Hdr.Ttl |= _DO 135 | } 136 | 137 | // EDNS0 defines an EDNS0 Option. An OPT RR can have multiple options appended to 138 | // it. 139 | type EDNS0 interface { 140 | // Option returns the option code for the option. 141 | Option() uint16 142 | // pack returns the bytes of the option data. 143 | pack() ([]byte, error) 144 | // unpack sets the data as found in the buffer. Is also sets 145 | // the length of the slice as the length of the option data. 146 | unpack([]byte) error 147 | // String returns the string representation of the option. 148 | String() string 149 | } 150 | 151 | // The nsid EDNS0 option is used to retrieve a nameserver 152 | // identifier. When sending a request Nsid must be set to the empty string 153 | // The identifier is an opaque string encoded as hex. 154 | // Basic use pattern for creating an nsid option: 155 | // 156 | // o := new(dns.OPT) 157 | // o.Hdr.Name = "." 158 | // o.Hdr.Rrtype = dns.TypeOPT 159 | // e := new(dns.EDNS0_NSID) 160 | // e.Code = dns.EDNS0NSID 161 | // e.Nsid = "AA" 162 | // o.Option = append(o.Option, e) 163 | type EDNS0_NSID struct { 164 | Code uint16 // Always EDNS0NSID 165 | Nsid string // This string needs to be hex encoded 166 | } 167 | 168 | func (e *EDNS0_NSID) pack() ([]byte, error) { 169 | h, err := hex.DecodeString(e.Nsid) 170 | if err != nil { 171 | return nil, err 172 | } 173 | return h, nil 174 | } 175 | 176 | func (e *EDNS0_NSID) Option() uint16 { return EDNS0NSID } 177 | func (e *EDNS0_NSID) unpack(b []byte) error { e.Nsid = hex.EncodeToString(b); return nil } 178 | func (e *EDNS0_NSID) String() string { return string(e.Nsid) } 179 | 180 | // EDNS0_SUBNET is the subnet option that is used to give the remote nameserver 181 | // an idea of where the client lives. It can then give back a different 182 | // answer depending on the location or network topology. 183 | // Basic use pattern for creating an subnet option: 184 | // 185 | // o := new(dns.OPT) 186 | // o.Hdr.Name = "." 187 | // o.Hdr.Rrtype = dns.TypeOPT 188 | // e := new(dns.EDNS0_SUBNET) 189 | // e.Code = dns.EDNS0SUBNET 190 | // e.Family = 1 // 1 for IPv4 source address, 2 for IPv6 191 | // e.NetMask = 32 // 32 for IPV4, 128 for IPv6 192 | // e.SourceScope = 0 193 | // e.Address = net.ParseIP("127.0.0.1").To4() // for IPv4 194 | // // e.Address = net.ParseIP("2001:7b8:32a::2") // for IPV6 195 | // o.Option = append(o.Option, e) 196 | // 197 | // Note: the spec (draft-ietf-dnsop-edns-client-subnet-00) has some insane logic 198 | // for which netmask applies to the address. This code will parse all the 199 | // available bits when unpacking (up to optlen). When packing it will apply 200 | // SourceNetmask. If you need more advanced logic, patches welcome and good luck. 201 | type EDNS0_SUBNET struct { 202 | Code uint16 // Always EDNS0SUBNET 203 | Family uint16 // 1 for IP, 2 for IP6 204 | SourceNetmask uint8 205 | SourceScope uint8 206 | Address net.IP 207 | DraftOption bool // Set to true if using the old (0x50fa) option code 208 | } 209 | 210 | func (e *EDNS0_SUBNET) Option() uint16 { 211 | if e.DraftOption { 212 | return EDNS0SUBNETDRAFT 213 | } 214 | return EDNS0SUBNET 215 | } 216 | 217 | func (e *EDNS0_SUBNET) pack() ([]byte, error) { 218 | b := make([]byte, 4) 219 | b[0], b[1] = packUint16(e.Family) 220 | b[2] = e.SourceNetmask 221 | b[3] = e.SourceScope 222 | switch e.Family { 223 | case 1: 224 | if e.SourceNetmask > net.IPv4len*8 { 225 | return nil, errors.New("dns: bad netmask") 226 | } 227 | if len(e.Address.To4()) != net.IPv4len { 228 | return nil, errors.New("dns: bad address") 229 | } 230 | ip := e.Address.To4().Mask(net.CIDRMask(int(e.SourceNetmask), net.IPv4len*8)) 231 | needLength := (e.SourceNetmask + 8 - 1) / 8 // division rounding up 232 | b = append(b, ip[:needLength]...) 233 | case 2: 234 | if e.SourceNetmask > net.IPv6len*8 { 235 | return nil, errors.New("dns: bad netmask") 236 | } 237 | if len(e.Address) != net.IPv6len { 238 | return nil, errors.New("dns: bad address") 239 | } 240 | ip := e.Address.Mask(net.CIDRMask(int(e.SourceNetmask), net.IPv6len*8)) 241 | needLength := (e.SourceNetmask + 8 - 1) / 8 // division rounding up 242 | b = append(b, ip[:needLength]...) 243 | default: 244 | return nil, errors.New("dns: bad address family") 245 | } 246 | return b, nil 247 | } 248 | 249 | func (e *EDNS0_SUBNET) unpack(b []byte) error { 250 | if len(b) < 4 { 251 | return ErrBuf 252 | } 253 | e.Family, _ = unpackUint16(b, 0) 254 | e.SourceNetmask = b[2] 255 | e.SourceScope = b[3] 256 | switch e.Family { 257 | case 1: 258 | if e.SourceNetmask > net.IPv4len*8 || e.SourceScope > net.IPv4len*8 { 259 | return errors.New("dns: bad netmask") 260 | } 261 | addr := make([]byte, net.IPv4len) 262 | for i := 0; i < net.IPv4len && 4+i < len(b); i++ { 263 | addr[i] = b[4+i] 264 | } 265 | e.Address = net.IPv4(addr[0], addr[1], addr[2], addr[3]) 266 | case 2: 267 | if e.SourceNetmask > net.IPv6len*8 || e.SourceScope > net.IPv6len*8 { 268 | return errors.New("dns: bad netmask") 269 | } 270 | addr := make([]byte, net.IPv6len) 271 | for i := 0; i < net.IPv6len && 4+i < len(b); i++ { 272 | addr[i] = b[4+i] 273 | } 274 | e.Address = net.IP{addr[0], addr[1], addr[2], addr[3], addr[4], 275 | addr[5], addr[6], addr[7], addr[8], addr[9], addr[10], 276 | addr[11], addr[12], addr[13], addr[14], addr[15]} 277 | default: 278 | return errors.New("dns: bad address family") 279 | } 280 | return nil 281 | } 282 | 283 | func (e *EDNS0_SUBNET) String() (s string) { 284 | if e.Address == nil { 285 | s = "" 286 | } else if e.Address.To4() != nil { 287 | s = e.Address.String() 288 | } else { 289 | s = "[" + e.Address.String() + "]" 290 | } 291 | s += "/" + strconv.Itoa(int(e.SourceNetmask)) + "/" + strconv.Itoa(int(e.SourceScope)) 292 | return 293 | } 294 | 295 | // The EDNS0_UL (Update Lease) (draft RFC) option is used to tell the server to set 296 | // an expiration on an update RR. This is helpful for clients that cannot clean 297 | // up after themselves. This is a draft RFC and more information can be found at 298 | // http://files.dns-sd.org/draft-sekar-dns-ul.txt 299 | // 300 | // o := new(dns.OPT) 301 | // o.Hdr.Name = "." 302 | // o.Hdr.Rrtype = dns.TypeOPT 303 | // e := new(dns.EDNS0_UL) 304 | // e.Code = dns.EDNS0UL 305 | // e.Lease = 120 // in seconds 306 | // o.Option = append(o.Option, e) 307 | type EDNS0_UL struct { 308 | Code uint16 // Always EDNS0UL 309 | Lease uint32 310 | } 311 | 312 | func (e *EDNS0_UL) Option() uint16 { return EDNS0UL } 313 | func (e *EDNS0_UL) String() string { return strconv.FormatUint(uint64(e.Lease), 10) } 314 | 315 | // Copied: http://golang.org/src/pkg/net/dnsmsg.go 316 | func (e *EDNS0_UL) pack() ([]byte, error) { 317 | b := make([]byte, 4) 318 | b[0] = byte(e.Lease >> 24) 319 | b[1] = byte(e.Lease >> 16) 320 | b[2] = byte(e.Lease >> 8) 321 | b[3] = byte(e.Lease) 322 | return b, nil 323 | } 324 | 325 | func (e *EDNS0_UL) unpack(b []byte) error { 326 | if len(b) < 4 { 327 | return ErrBuf 328 | } 329 | e.Lease = uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3]) 330 | return nil 331 | } 332 | 333 | // EDNS0_LLQ stands for Long Lived Queries: http://tools.ietf.org/html/draft-sekar-dns-llq-01 334 | // Implemented for completeness, as the EDNS0 type code is assigned. 335 | type EDNS0_LLQ struct { 336 | Code uint16 // Always EDNS0LLQ 337 | Version uint16 338 | Opcode uint16 339 | Error uint16 340 | Id uint64 341 | LeaseLife uint32 342 | } 343 | 344 | func (e *EDNS0_LLQ) Option() uint16 { return EDNS0LLQ } 345 | 346 | func (e *EDNS0_LLQ) pack() ([]byte, error) { 347 | b := make([]byte, 18) 348 | b[0], b[1] = packUint16(e.Version) 349 | b[2], b[3] = packUint16(e.Opcode) 350 | b[4], b[5] = packUint16(e.Error) 351 | b[6] = byte(e.Id >> 56) 352 | b[7] = byte(e.Id >> 48) 353 | b[8] = byte(e.Id >> 40) 354 | b[9] = byte(e.Id >> 32) 355 | b[10] = byte(e.Id >> 24) 356 | b[11] = byte(e.Id >> 16) 357 | b[12] = byte(e.Id >> 8) 358 | b[13] = byte(e.Id) 359 | b[14] = byte(e.LeaseLife >> 24) 360 | b[15] = byte(e.LeaseLife >> 16) 361 | b[16] = byte(e.LeaseLife >> 8) 362 | b[17] = byte(e.LeaseLife) 363 | return b, nil 364 | } 365 | 366 | func (e *EDNS0_LLQ) unpack(b []byte) error { 367 | if len(b) < 18 { 368 | return ErrBuf 369 | } 370 | e.Version, _ = unpackUint16(b, 0) 371 | e.Opcode, _ = unpackUint16(b, 2) 372 | e.Error, _ = unpackUint16(b, 4) 373 | e.Id = uint64(b[6])<<56 | uint64(b[6+1])<<48 | uint64(b[6+2])<<40 | 374 | uint64(b[6+3])<<32 | uint64(b[6+4])<<24 | uint64(b[6+5])<<16 | uint64(b[6+6])<<8 | uint64(b[6+7]) 375 | e.LeaseLife = uint32(b[14])<<24 | uint32(b[14+1])<<16 | uint32(b[14+2])<<8 | uint32(b[14+3]) 376 | return nil 377 | } 378 | 379 | func (e *EDNS0_LLQ) String() string { 380 | s := strconv.FormatUint(uint64(e.Version), 10) + " " + strconv.FormatUint(uint64(e.Opcode), 10) + 381 | " " + strconv.FormatUint(uint64(e.Error), 10) + " " + strconv.FormatUint(uint64(e.Id), 10) + 382 | " " + strconv.FormatUint(uint64(e.LeaseLife), 10) 383 | return s 384 | } 385 | 386 | type EDNS0_DAU struct { 387 | Code uint16 // Always EDNS0DAU 388 | AlgCode []uint8 389 | } 390 | 391 | func (e *EDNS0_DAU) Option() uint16 { return EDNS0DAU } 392 | func (e *EDNS0_DAU) pack() ([]byte, error) { return e.AlgCode, nil } 393 | func (e *EDNS0_DAU) unpack(b []byte) error { e.AlgCode = b; return nil } 394 | 395 | func (e *EDNS0_DAU) String() string { 396 | s := "" 397 | for i := 0; i < len(e.AlgCode); i++ { 398 | if a, ok := AlgorithmToString[e.AlgCode[i]]; ok { 399 | s += " " + a 400 | } else { 401 | s += " " + strconv.Itoa(int(e.AlgCode[i])) 402 | } 403 | } 404 | return s 405 | } 406 | 407 | type EDNS0_DHU struct { 408 | Code uint16 // Always EDNS0DHU 409 | AlgCode []uint8 410 | } 411 | 412 | func (e *EDNS0_DHU) Option() uint16 { return EDNS0DHU } 413 | func (e *EDNS0_DHU) pack() ([]byte, error) { return e.AlgCode, nil } 414 | func (e *EDNS0_DHU) unpack(b []byte) error { e.AlgCode = b; return nil } 415 | 416 | func (e *EDNS0_DHU) String() string { 417 | s := "" 418 | for i := 0; i < len(e.AlgCode); i++ { 419 | if a, ok := HashToString[e.AlgCode[i]]; ok { 420 | s += " " + a 421 | } else { 422 | s += " " + strconv.Itoa(int(e.AlgCode[i])) 423 | } 424 | } 425 | return s 426 | } 427 | 428 | type EDNS0_N3U struct { 429 | Code uint16 // Always EDNS0N3U 430 | AlgCode []uint8 431 | } 432 | 433 | func (e *EDNS0_N3U) Option() uint16 { return EDNS0N3U } 434 | func (e *EDNS0_N3U) pack() ([]byte, error) { return e.AlgCode, nil } 435 | func (e *EDNS0_N3U) unpack(b []byte) error { e.AlgCode = b; return nil } 436 | 437 | func (e *EDNS0_N3U) String() string { 438 | // Re-use the hash map 439 | s := "" 440 | for i := 0; i < len(e.AlgCode); i++ { 441 | if a, ok := HashToString[e.AlgCode[i]]; ok { 442 | s += " " + a 443 | } else { 444 | s += " " + strconv.Itoa(int(e.AlgCode[i])) 445 | } 446 | } 447 | return s 448 | } 449 | 450 | type EDNS0_EXPIRE struct { 451 | Code uint16 // Always EDNS0EXPIRE 452 | Expire uint32 453 | } 454 | 455 | func (e *EDNS0_EXPIRE) Option() uint16 { return EDNS0EXPIRE } 456 | func (e *EDNS0_EXPIRE) String() string { return strconv.FormatUint(uint64(e.Expire), 10) } 457 | 458 | func (e *EDNS0_EXPIRE) pack() ([]byte, error) { 459 | b := make([]byte, 4) 460 | b[0] = byte(e.Expire >> 24) 461 | b[1] = byte(e.Expire >> 16) 462 | b[2] = byte(e.Expire >> 8) 463 | b[3] = byte(e.Expire) 464 | return b, nil 465 | } 466 | 467 | func (e *EDNS0_EXPIRE) unpack(b []byte) error { 468 | if len(b) < 4 { 469 | return ErrBuf 470 | } 471 | e.Expire = uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3]) 472 | return nil 473 | } 474 | 475 | // The EDNS0_LOCAL option is used for local/experimental purposes. The option 476 | // code is recommended to be within the range [EDNS0LOCALSTART, EDNS0LOCALEND] 477 | // (RFC6891), although any unassigned code can actually be used. The content of 478 | // the option is made available in Data, unaltered. 479 | // Basic use pattern for creating a local option: 480 | // 481 | // o := new(dns.OPT) 482 | // o.Hdr.Name = "." 483 | // o.Hdr.Rrtype = dns.TypeOPT 484 | // e := new(dns.EDNS0_LOCAL) 485 | // e.Code = dns.EDNS0LOCALSTART 486 | // e.Data = []byte{72, 82, 74} 487 | // o.Option = append(o.Option, e) 488 | type EDNS0_LOCAL struct { 489 | Code uint16 490 | Data []byte 491 | } 492 | 493 | func (e *EDNS0_LOCAL) Option() uint16 { return e.Code } 494 | func (e *EDNS0_LOCAL) String() string { 495 | return strconv.FormatInt(int64(e.Code), 10) + ":0x" + hex.EncodeToString(e.Data) 496 | } 497 | 498 | func (e *EDNS0_LOCAL) pack() ([]byte, error) { 499 | b := make([]byte, len(e.Data)) 500 | copied := copy(b, e.Data) 501 | if copied != len(e.Data) { 502 | return nil, ErrBuf 503 | } 504 | return b, nil 505 | } 506 | 507 | func (e *EDNS0_LOCAL) unpack(b []byte) error { 508 | e.Data = make([]byte, len(b)) 509 | copied := copy(e.Data, b) 510 | if copied != len(b) { 511 | return ErrBuf 512 | } 513 | return nil 514 | } 515 | -------------------------------------------------------------------------------- /edns_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import "testing" 4 | 5 | func TestOPTTtl(t *testing.T) { 6 | e := &OPT{} 7 | e.Hdr.Name = "." 8 | e.Hdr.Rrtype = TypeOPT 9 | 10 | if e.Do() { 11 | t.Fail() 12 | } 13 | 14 | e.SetDo() 15 | if !e.Do() { 16 | t.Fail() 17 | } 18 | 19 | oldTtl := e.Hdr.Ttl 20 | 21 | if e.Version() != 0 { 22 | t.Fail() 23 | } 24 | 25 | e.SetVersion(42) 26 | if e.Version() != 42 { 27 | t.Fail() 28 | } 29 | 30 | e.SetVersion(0) 31 | if e.Hdr.Ttl != oldTtl { 32 | t.Fail() 33 | } 34 | 35 | if e.ExtendedRcode() != 0 { 36 | t.Fail() 37 | } 38 | 39 | e.SetExtendedRcode(42) 40 | if e.ExtendedRcode() != 42 { 41 | t.Fail() 42 | } 43 | 44 | e.SetExtendedRcode(0) 45 | if e.Hdr.Ttl != oldTtl { 46 | t.Fail() 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | package dns_test 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "github.com/cloudflare/dns" 7 | "log" 8 | "net" 9 | ) 10 | 11 | // Retrieve the MX records for miek.nl. 12 | func ExampleMX() { 13 | config, _ := dns.ClientConfigFromFile("/etc/resolv.conf") 14 | c := new(dns.Client) 15 | m := new(dns.Msg) 16 | m.SetQuestion("miek.nl.", dns.TypeMX) 17 | m.RecursionDesired = true 18 | r, _, err := c.Exchange(m, config.Servers[0]+":"+config.Port) 19 | if err != nil { 20 | return 21 | } 22 | if r.Rcode != dns.RcodeSuccess { 23 | return 24 | } 25 | for _, a := range r.Answer { 26 | if mx, ok := a.(*dns.MX); ok { 27 | fmt.Printf("%s\n", mx.String()) 28 | } 29 | } 30 | } 31 | 32 | // Retrieve the DNSKEY records of a zone and convert them 33 | // to DS records for SHA1, SHA256 and SHA384. 34 | func ExampleDS(zone string) { 35 | config, _ := dns.ClientConfigFromFile("/etc/resolv.conf") 36 | c := new(dns.Client) 37 | m := new(dns.Msg) 38 | if zone == "" { 39 | zone = "miek.nl" 40 | } 41 | m.SetQuestion(dns.Fqdn(zone), dns.TypeDNSKEY) 42 | m.SetEdns0(4096, true) 43 | r, _, err := c.Exchange(m, config.Servers[0]+":"+config.Port) 44 | if err != nil { 45 | return 46 | } 47 | if r.Rcode != dns.RcodeSuccess { 48 | return 49 | } 50 | for _, k := range r.Answer { 51 | if key, ok := k.(*dns.DNSKEY); ok { 52 | for _, alg := range []uint8{dns.SHA1, dns.SHA256, dns.SHA384} { 53 | fmt.Printf("%s; %d\n", key.ToDS(alg).String(), key.Flags) 54 | } 55 | } 56 | } 57 | } 58 | 59 | const TypeAPAIR = 0x0F99 60 | 61 | type APAIR struct { 62 | addr [2]net.IP 63 | } 64 | 65 | func NewAPAIR() dns.PrivateRdata { return new(APAIR) } 66 | 67 | func (rd *APAIR) String() string { return rd.addr[0].String() + " " + rd.addr[1].String() } 68 | func (rd *APAIR) Parse(txt []string) error { 69 | if len(txt) != 2 { 70 | return errors.New("two addresses required for APAIR") 71 | } 72 | for i, s := range txt { 73 | ip := net.ParseIP(s) 74 | if ip == nil { 75 | return errors.New("invalid IP in APAIR text representation") 76 | } 77 | rd.addr[i] = ip 78 | } 79 | return nil 80 | } 81 | 82 | func (rd *APAIR) Pack(buf []byte) (int, error) { 83 | b := append([]byte(rd.addr[0]), []byte(rd.addr[1])...) 84 | n := copy(buf, b) 85 | if n != len(b) { 86 | return n, dns.ErrBuf 87 | } 88 | return n, nil 89 | } 90 | 91 | func (rd *APAIR) Unpack(buf []byte) (int, error) { 92 | ln := net.IPv4len * 2 93 | if len(buf) != ln { 94 | return 0, errors.New("invalid length of APAIR rdata") 95 | } 96 | cp := make([]byte, ln) 97 | copy(cp, buf) // clone bytes to use them in IPs 98 | 99 | rd.addr[0] = net.IP(cp[:3]) 100 | rd.addr[1] = net.IP(cp[4:]) 101 | 102 | return len(buf), nil 103 | } 104 | 105 | func (rd *APAIR) Copy(dest dns.PrivateRdata) error { 106 | cp := make([]byte, rd.Len()) 107 | _, err := rd.Pack(cp) 108 | if err != nil { 109 | return err 110 | } 111 | 112 | d := dest.(*APAIR) 113 | d.addr[0] = net.IP(cp[:3]) 114 | d.addr[1] = net.IP(cp[4:]) 115 | return nil 116 | } 117 | 118 | func (rd *APAIR) Len() int { 119 | return net.IPv4len * 2 120 | } 121 | 122 | func ExamplePrivateHandle() { 123 | dns.PrivateHandle("APAIR", TypeAPAIR, NewAPAIR) 124 | defer dns.PrivateHandleRemove(TypeAPAIR) 125 | 126 | rr, err := dns.NewRR("miek.nl. APAIR (1.2.3.4 1.2.3.5)") 127 | if err != nil { 128 | log.Fatal("could not parse APAIR record: ", err) 129 | } 130 | fmt.Println(rr) 131 | // Output: miek.nl. 3600 IN APAIR 1.2.3.4 1.2.3.5 132 | 133 | m := new(dns.Msg) 134 | m.Id = 12345 135 | m.SetQuestion("miek.nl.", TypeAPAIR) 136 | m.Answer = append(m.Answer, rr) 137 | 138 | fmt.Println(m) 139 | // ;; opcode: QUERY, status: NOERROR, id: 12345 140 | // ;; flags: rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 141 | // 142 | // ;; QUESTION SECTION: 143 | // ;miek.nl. IN APAIR 144 | // 145 | // ;; ANSWER SECTION: 146 | // miek.nl. 3600 IN APAIR 1.2.3.4 1.2.3.5 147 | } 148 | -------------------------------------------------------------------------------- /format.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "net" 5 | "reflect" 6 | "strconv" 7 | ) 8 | 9 | // NumField returns the number of rdata fields r has. 10 | func NumField(r RR) int { 11 | return reflect.ValueOf(r).Elem().NumField() - 1 // Remove RR_Header 12 | } 13 | 14 | // Field returns the rdata field i as a string. Fields are indexed starting from 1. 15 | // RR types that holds slice data, for instance the NSEC type bitmap will return a single 16 | // string where the types are concatenated using a space. 17 | // Accessing non existing fields will cause a panic. 18 | func Field(r RR, i int) string { 19 | if i == 0 { 20 | return "" 21 | } 22 | d := reflect.ValueOf(r).Elem().Field(i) 23 | switch k := d.Kind(); k { 24 | case reflect.String: 25 | return d.String() 26 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 27 | return strconv.FormatInt(d.Int(), 10) 28 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 29 | return strconv.FormatUint(d.Uint(), 10) 30 | case reflect.Slice: 31 | switch reflect.ValueOf(r).Elem().Type().Field(i).Tag { 32 | case `dns:"a"`: 33 | // TODO(miek): Hmm store this as 16 bytes 34 | if d.Len() < net.IPv6len { 35 | return net.IPv4(byte(d.Index(0).Uint()), 36 | byte(d.Index(1).Uint()), 37 | byte(d.Index(2).Uint()), 38 | byte(d.Index(3).Uint())).String() 39 | } 40 | return net.IPv4(byte(d.Index(12).Uint()), 41 | byte(d.Index(13).Uint()), 42 | byte(d.Index(14).Uint()), 43 | byte(d.Index(15).Uint())).String() 44 | case `dns:"aaaa"`: 45 | return net.IP{ 46 | byte(d.Index(0).Uint()), 47 | byte(d.Index(1).Uint()), 48 | byte(d.Index(2).Uint()), 49 | byte(d.Index(3).Uint()), 50 | byte(d.Index(4).Uint()), 51 | byte(d.Index(5).Uint()), 52 | byte(d.Index(6).Uint()), 53 | byte(d.Index(7).Uint()), 54 | byte(d.Index(8).Uint()), 55 | byte(d.Index(9).Uint()), 56 | byte(d.Index(10).Uint()), 57 | byte(d.Index(11).Uint()), 58 | byte(d.Index(12).Uint()), 59 | byte(d.Index(13).Uint()), 60 | byte(d.Index(14).Uint()), 61 | byte(d.Index(15).Uint()), 62 | }.String() 63 | case `dns:"nsec"`: 64 | if d.Len() == 0 { 65 | return "" 66 | } 67 | s := Type(d.Index(0).Uint()).String() 68 | for i := 1; i < d.Len(); i++ { 69 | s += " " + Type(d.Index(i).Uint()).String() 70 | } 71 | return s 72 | case `dns:"wks"`: 73 | if d.Len() == 0 { 74 | return "" 75 | } 76 | s := strconv.Itoa(int(d.Index(0).Uint())) 77 | for i := 0; i < d.Len(); i++ { 78 | s += " " + strconv.Itoa(int(d.Index(i).Uint())) 79 | } 80 | return s 81 | default: 82 | // if it does not have a tag its a string slice 83 | fallthrough 84 | case `dns:"txt"`: 85 | if d.Len() == 0 { 86 | return "" 87 | } 88 | s := d.Index(0).String() 89 | for i := 1; i < d.Len(); i++ { 90 | s += " " + d.Index(i).String() 91 | } 92 | return s 93 | } 94 | } 95 | return "" 96 | } 97 | -------------------------------------------------------------------------------- /fuzz_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import "testing" 4 | 5 | func TestFuzzString(t *testing.T) { 6 | testcases := []string{"", " MINFO ", " RP ", " NSEC 0 0", " \" NSEC 0 0\"", " \" MINFO \"", 7 | ";a ", ";a����������", 8 | " NSAP O ", " NSAP N ", 9 | " TYPE4 TYPE6a789a3bc0045c8a5fb42c7d1bd998f5444 IN 9579b47d46817afbd17273e6", 10 | " TYPE45 3 3 4147994 TYPE\\(\\)\\)\\(\\)\\(\\(\\)\\(\\)\\)\\)\\(\\)\\(\\)\\(\\(\\R 948\"\")\\(\\)\\)\\)\\(\\ ", 11 | "$GENERATE 0-3 ${441189,5039418474430,o}", 12 | "$INCLUDE 00 TYPE00000000000n ", 13 | "$INCLUDE PE4 TYPE061463623/727071511 \\(\\)\\$GENERATE 6-462/0", 14 | } 15 | for i, tc := range testcases { 16 | rr, err := NewRR(tc) 17 | if err == nil { 18 | // rr can be nil because we can (for instance) just parse a comment 19 | if rr == nil { 20 | continue 21 | } 22 | t.Fatalf("parsed mailformed RR %d: %s", i, rr.String()) 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /idn/example_test.go: -------------------------------------------------------------------------------- 1 | package idn_test 2 | 3 | import ( 4 | "fmt" 5 | "github.com/cloudflare/dns/idn" 6 | ) 7 | 8 | func ExampleToPunycode() { 9 | name := "インターネット.テスト" 10 | fmt.Printf("%s -> %s", name, idn.ToPunycode(name)) 11 | // Output: インターネット.テスト -> xn--eckucmux0ukc.xn--zckzah 12 | } 13 | 14 | func ExampleFromPunycode() { 15 | name := "xn--mgbaja8a1hpac.xn--mgbachtv" 16 | fmt.Printf("%s -> %s", name, idn.FromPunycode(name)) 17 | // Output: xn--mgbaja8a1hpac.xn--mgbachtv -> الانترنت.اختبار 18 | } 19 | -------------------------------------------------------------------------------- /idn/punycode.go: -------------------------------------------------------------------------------- 1 | // Package idn implements encoding from and to punycode as speficied by RFC 3492. 2 | package idn 3 | 4 | import ( 5 | "bytes" 6 | "strings" 7 | "unicode" 8 | "unicode/utf8" 9 | 10 | "github.com/cloudflare/dns" 11 | ) 12 | 13 | // Implementation idea from RFC itself and from from IDNA::Punycode created by 14 | // Tatsuhiko Miyagawa and released under Perl Artistic 15 | // License in 2002. 16 | 17 | const ( 18 | _MIN rune = 1 19 | _MAX rune = 26 20 | _SKEW rune = 38 21 | _BASE rune = 36 22 | _BIAS rune = 72 23 | _N rune = 128 24 | _DAMP rune = 700 25 | 26 | _DELIMITER = '-' 27 | _PREFIX = "xn--" 28 | ) 29 | 30 | // ToPunycode converts unicode domain names to DNS-appropriate punycode names. 31 | // This function will return an empty string result for domain names with 32 | // invalid unicode strings. This function expects domain names in lowercase. 33 | func ToPunycode(s string) string { 34 | // Early check to see if encoding is needed. 35 | // This will prevent making heap allocations when not needed. 36 | if !needToPunycode(s) { 37 | return s 38 | } 39 | 40 | tokens := dns.SplitDomainName(s) 41 | switch { 42 | case s == "": 43 | return "" 44 | case tokens == nil: // s == . 45 | return "." 46 | case s[len(s)-1] == '.': 47 | tokens = append(tokens, "") 48 | } 49 | 50 | for i := range tokens { 51 | t := encode([]byte(tokens[i])) 52 | if t == nil { 53 | return "" 54 | } 55 | tokens[i] = string(t) 56 | } 57 | return strings.Join(tokens, ".") 58 | } 59 | 60 | // FromPunycode returns unicode domain name from provided punycode string. 61 | // This function expects punycode strings in lowercase. 62 | func FromPunycode(s string) string { 63 | // Early check to see if decoding is needed. 64 | // This will prevent making heap allocations when not needed. 65 | if !needFromPunycode(s) { 66 | return s 67 | } 68 | 69 | tokens := dns.SplitDomainName(s) 70 | switch { 71 | case s == "": 72 | return "" 73 | case tokens == nil: // s == . 74 | return "." 75 | case s[len(s)-1] == '.': 76 | tokens = append(tokens, "") 77 | } 78 | for i := range tokens { 79 | tokens[i] = string(decode([]byte(tokens[i]))) 80 | } 81 | return strings.Join(tokens, ".") 82 | } 83 | 84 | // digitval converts single byte into meaningful value that's used to calculate decoded unicode character. 85 | const errdigit = 0xffff 86 | 87 | func digitval(code rune) rune { 88 | switch { 89 | case code >= 'A' && code <= 'Z': 90 | return code - 'A' 91 | case code >= 'a' && code <= 'z': 92 | return code - 'a' 93 | case code >= '0' && code <= '9': 94 | return code - '0' + 26 95 | } 96 | return errdigit 97 | } 98 | 99 | // lettercode finds BASE36 byte (a-z0-9) based on calculated number. 100 | func lettercode(digit rune) rune { 101 | switch { 102 | case digit >= 0 && digit <= 25: 103 | return digit + 'a' 104 | case digit >= 26 && digit <= 36: 105 | return digit - 26 + '0' 106 | } 107 | panic("dns: not reached") 108 | } 109 | 110 | // adapt calculates next bias to be used for next iteration delta. 111 | func adapt(delta rune, numpoints int, firsttime bool) rune { 112 | if firsttime { 113 | delta /= _DAMP 114 | } else { 115 | delta /= 2 116 | } 117 | 118 | var k rune 119 | for delta = delta + delta/rune(numpoints); delta > (_BASE-_MIN)*_MAX/2; k += _BASE { 120 | delta /= _BASE - _MIN 121 | } 122 | 123 | return k + ((_BASE-_MIN+1)*delta)/(delta+_SKEW) 124 | } 125 | 126 | // next finds minimal rune (one with lowest codepoint value) that should be equal or above boundary. 127 | func next(b []rune, boundary rune) rune { 128 | if len(b) == 0 { 129 | panic("dns: invalid set of runes to determine next one") 130 | } 131 | m := b[0] 132 | for _, x := range b[1:] { 133 | if x >= boundary && (m < boundary || x < m) { 134 | m = x 135 | } 136 | } 137 | return m 138 | } 139 | 140 | // preprune converts unicode rune to lower case. At this time it's not 141 | // supporting all things described in RFCs. 142 | func preprune(r rune) rune { 143 | if unicode.IsUpper(r) { 144 | r = unicode.ToLower(r) 145 | } 146 | return r 147 | } 148 | 149 | // tfunc is a function that helps calculate each character weight. 150 | func tfunc(k, bias rune) rune { 151 | switch { 152 | case k <= bias: 153 | return _MIN 154 | case k >= bias+_MAX: 155 | return _MAX 156 | } 157 | return k - bias 158 | } 159 | 160 | // needToPunycode returns true for strings that require punycode encoding 161 | // (contain unicode characters). 162 | func needToPunycode(s string) bool { 163 | // This function is very similar to bytes.Runes. We don't use bytes.Runes 164 | // because it makes a heap allocation that's not needed here. 165 | for i := 0; len(s) > 0; i++ { 166 | r, l := utf8.DecodeRuneInString(s) 167 | if r > 0x7f { 168 | return true 169 | } 170 | s = s[l:] 171 | } 172 | return false 173 | } 174 | 175 | // needFromPunycode returns true for strings that require punycode decoding. 176 | func needFromPunycode(s string) bool { 177 | if s == "." { 178 | return false 179 | } 180 | 181 | off := 0 182 | end := false 183 | pl := len(_PREFIX) 184 | sl := len(s) 185 | 186 | // If s starts with _PREFIX. 187 | if sl > pl && s[off:off+pl] == _PREFIX { 188 | return true 189 | } 190 | 191 | for { 192 | // Find the part after the next ".". 193 | off, end = dns.NextLabel(s, off) 194 | if end { 195 | return false 196 | } 197 | // If this parts starts with _PREFIX. 198 | if sl-off > pl && s[off:off+pl] == _PREFIX { 199 | return true 200 | } 201 | } 202 | panic("dns: not reached") 203 | } 204 | 205 | // encode transforms Unicode input bytes (that represent DNS label) into 206 | // punycode bytestream. This function would return nil if there's an invalid 207 | // character in the label. 208 | func encode(input []byte) []byte { 209 | n, bias := _N, _BIAS 210 | 211 | b := bytes.Runes(input) 212 | for i := range b { 213 | if !isValidRune(b[i]) { 214 | return nil 215 | } 216 | 217 | b[i] = preprune(b[i]) 218 | } 219 | 220 | basic := make([]byte, 0, len(b)) 221 | for _, ltr := range b { 222 | if ltr <= 0x7f { 223 | basic = append(basic, byte(ltr)) 224 | } 225 | } 226 | basiclen := len(basic) 227 | fulllen := len(b) 228 | if basiclen == fulllen { 229 | return basic 230 | } 231 | 232 | var out bytes.Buffer 233 | 234 | out.WriteString(_PREFIX) 235 | if basiclen > 0 { 236 | out.Write(basic) 237 | out.WriteByte(_DELIMITER) 238 | } 239 | 240 | var ( 241 | ltr, nextltr rune 242 | delta, q rune // delta calculation (see rfc) 243 | t, k, cp rune // weight and codepoint calculation 244 | ) 245 | 246 | s := &bytes.Buffer{} 247 | for h := basiclen; h < fulllen; n, delta = n+1, delta+1 { 248 | nextltr = next(b, n) 249 | s.Truncate(0) 250 | s.WriteRune(nextltr) 251 | delta, n = delta+(nextltr-n)*rune(h+1), nextltr 252 | 253 | for _, ltr = range b { 254 | if ltr < n { 255 | delta++ 256 | } 257 | if ltr == n { 258 | q = delta 259 | for k = _BASE; ; k += _BASE { 260 | t = tfunc(k, bias) 261 | if q < t { 262 | break 263 | } 264 | cp = t + ((q - t) % (_BASE - t)) 265 | out.WriteRune(lettercode(cp)) 266 | q = (q - t) / (_BASE - t) 267 | } 268 | 269 | out.WriteRune(lettercode(q)) 270 | 271 | bias = adapt(delta, h+1, h == basiclen) 272 | h, delta = h+1, 0 273 | } 274 | } 275 | } 276 | return out.Bytes() 277 | } 278 | 279 | // decode transforms punycode input bytes (that represent DNS label) into Unicode bytestream. 280 | func decode(b []byte) []byte { 281 | src := b // b would move and we need to keep it 282 | 283 | n, bias := _N, _BIAS 284 | if !bytes.HasPrefix(b, []byte(_PREFIX)) { 285 | return b 286 | } 287 | out := make([]rune, 0, len(b)) 288 | b = b[len(_PREFIX):] 289 | for pos := len(b) - 1; pos >= 0; pos-- { 290 | // only last delimiter is our interest 291 | if b[pos] == _DELIMITER { 292 | out = append(out, bytes.Runes(b[:pos])...) 293 | b = b[pos+1:] // trim source string 294 | break 295 | } 296 | } 297 | if len(b) == 0 { 298 | return src 299 | } 300 | var ( 301 | i, oldi, w rune 302 | ch byte 303 | t, digit rune 304 | ln int 305 | ) 306 | 307 | for i = 0; len(b) > 0; i++ { 308 | oldi, w = i, 1 309 | for k := _BASE; len(b) > 0; k += _BASE { 310 | ch, b = b[0], b[1:] 311 | digit = digitval(rune(ch)) 312 | if digit == errdigit { 313 | return src 314 | } 315 | i += digit * w 316 | if i < 0 { 317 | // safety check for rune overflow 318 | return src 319 | } 320 | 321 | t = tfunc(k, bias) 322 | if digit < t { 323 | break 324 | } 325 | 326 | w *= _BASE - t 327 | } 328 | ln = len(out) + 1 329 | bias = adapt(i-oldi, ln, oldi == 0) 330 | n += i / rune(ln) 331 | i = i % rune(ln) 332 | // insert 333 | out = append(out, 0) 334 | copy(out[i+1:], out[i:]) 335 | out[i] = n 336 | } 337 | 338 | var ret bytes.Buffer 339 | for _, r := range out { 340 | ret.WriteRune(r) 341 | } 342 | return ret.Bytes() 343 | } 344 | 345 | // isValidRune checks if the character is valid. We will look for the 346 | // character property in the code points list. For now we aren't checking special 347 | // rules in case of contextual property 348 | func isValidRune(r rune) bool { 349 | return findProperty(r) == propertyPVALID 350 | } 351 | 352 | // findProperty will try to check the code point property of the given 353 | // character. It will use a binary search algorithm as we have a slice of 354 | // ordered ranges (average case performance O(log n)) 355 | func findProperty(r rune) property { 356 | imin, imax := 0, len(codePoints) 357 | 358 | for imax >= imin { 359 | imid := (imin + imax) / 2 360 | 361 | codePoint := codePoints[imid] 362 | if (codePoint.start == r && codePoint.end == 0) || (codePoint.start <= r && codePoint.end >= r) { 363 | return codePoint.state 364 | } 365 | 366 | if (codePoint.end > 0 && codePoint.end < r) || (codePoint.end == 0 && codePoint.start < r) { 367 | imin = imid + 1 368 | } else { 369 | imax = imid - 1 370 | } 371 | } 372 | 373 | return propertyUnknown 374 | } 375 | -------------------------------------------------------------------------------- /idn/punycode_test.go: -------------------------------------------------------------------------------- 1 | package idn 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | ) 7 | 8 | var testcases = [][2]string{ 9 | {"", ""}, 10 | {"a", "a"}, 11 | {"a-b", "a-b"}, 12 | {"a-b-c", "a-b-c"}, 13 | {"abc", "abc"}, 14 | {"я", "xn--41a"}, 15 | {"zя", "xn--z-0ub"}, 16 | {"яZ", "xn--z-zub"}, 17 | {"а-я", "xn----7sb8g"}, 18 | {"إختبار", "xn--kgbechtv"}, 19 | {"آزمایشی", "xn--hgbk6aj7f53bba"}, 20 | {"测试", "xn--0zwm56d"}, 21 | {"測試", "xn--g6w251d"}, 22 | {"испытание", "xn--80akhbyknj4f"}, 23 | {"परीक्षा", "xn--11b5bs3a9aj6g"}, 24 | {"δοκιμή", "xn--jxalpdlp"}, 25 | {"테스트", "xn--9t4b11yi5a"}, 26 | {"טעסט", "xn--deba0ad"}, 27 | {"テスト", "xn--zckzah"}, 28 | {"பரிட்சை", "xn--hlcj6aya9esc7a"}, 29 | {"mamão-com-açúcar", "xn--mamo-com-acar-yeb1e6q"}, 30 | {"σ", "xn--4xa"}, 31 | } 32 | 33 | func TestEncodeDecodePunycode(t *testing.T) { 34 | for _, tst := range testcases { 35 | enc := encode([]byte(tst[0])) 36 | if string(enc) != tst[1] { 37 | t.Errorf("%s encodeded as %s but should be %s", tst[0], enc, tst[1]) 38 | } 39 | dec := decode([]byte(tst[1])) 40 | if string(dec) != strings.ToLower(tst[0]) { 41 | t.Errorf("%s decoded as %s but should be %s", tst[1], dec, strings.ToLower(tst[0])) 42 | } 43 | } 44 | } 45 | 46 | func TestToFromPunycode(t *testing.T) { 47 | for _, tst := range testcases { 48 | // assert unicode.com == punycode.com 49 | full := ToPunycode(tst[0] + ".com") 50 | if full != tst[1]+".com" { 51 | t.Errorf("invalid result from string conversion to punycode, %s and should be %s.com", full, tst[1]) 52 | } 53 | // assert punycode.punycode == unicode.unicode 54 | decoded := FromPunycode(tst[1] + "." + tst[1]) 55 | if decoded != strings.ToLower(tst[0]+"."+tst[0]) { 56 | t.Errorf("invalid result from string conversion to punycode, %s and should be %s.%s", decoded, tst[0], tst[0]) 57 | } 58 | } 59 | } 60 | 61 | func TestEncodeDecodeFinalPeriod(t *testing.T) { 62 | for _, tst := range testcases { 63 | // assert unicode.com. == punycode.com. 64 | full := ToPunycode(tst[0] + ".") 65 | if full != tst[1]+"." { 66 | t.Errorf("invalid result from string conversion to punycode when period added at the end, %#v and should be %#v", full, tst[1]+".") 67 | } 68 | // assert punycode.com. == unicode.com. 69 | decoded := FromPunycode(tst[1] + ".") 70 | if decoded != strings.ToLower(tst[0]+".") { 71 | t.Errorf("invalid result from string conversion to punycode when period added, %#v and should be %#v", decoded, tst[0]+".") 72 | } 73 | full = ToPunycode(tst[0]) 74 | if full != tst[1] { 75 | t.Errorf("invalid result from string conversion to punycode when no period added at the end, %#v and should be %#v", full, tst[1]+".") 76 | } 77 | // assert punycode.com. == unicode.com. 78 | decoded = FromPunycode(tst[1]) 79 | if decoded != strings.ToLower(tst[0]) { 80 | t.Errorf("invalid result from string conversion to punycode when no period added, %#v and should be %#v", decoded, tst[0]+".") 81 | } 82 | } 83 | } 84 | 85 | var invalidACEs = []string{ 86 | "xn--*", 87 | "xn--", 88 | "xn---", 89 | "xn--a000000000", 90 | } 91 | 92 | func TestInvalidPunycode(t *testing.T) { 93 | for _, d := range invalidACEs { 94 | s := FromPunycode(d) 95 | if s != d { 96 | t.Errorf("Changed invalid name %s to %#v", d, s) 97 | } 98 | } 99 | } 100 | 101 | // You can verify the labels that are valid or not comparing to the Verisign 102 | // website: http://mct.verisign-grs.com/ 103 | var invalidUnicodes = []string{ 104 | "Σ", 105 | "ЯZ", 106 | "Испытание", 107 | } 108 | 109 | func TestInvalidUnicodes(t *testing.T) { 110 | for _, d := range invalidUnicodes { 111 | s := ToPunycode(d) 112 | if s != "" { 113 | t.Errorf("Changed invalid name %s to %#v", d, s) 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /labels.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | // Holds a bunch of helper functions for dealing with labels. 4 | 5 | // SplitDomainName splits a name string into it's labels. 6 | // www.miek.nl. returns []string{"www", "miek", "nl"} 7 | // The root label (.) returns nil. Note that using 8 | // strings.Split(s) will work in most cases, but does not handle 9 | // escaped dots (\.) for instance. 10 | func SplitDomainName(s string) (labels []string) { 11 | if len(s) == 0 { 12 | return nil 13 | } 14 | fqdnEnd := 0 // offset of the final '.' or the length of the name 15 | idx := Split(s) 16 | begin := 0 17 | if s[len(s)-1] == '.' { 18 | fqdnEnd = len(s) - 1 19 | } else { 20 | fqdnEnd = len(s) 21 | } 22 | 23 | switch len(idx) { 24 | case 0: 25 | return nil 26 | case 1: 27 | // no-op 28 | default: 29 | end := 0 30 | for i := 1; i < len(idx); i++ { 31 | end = idx[i] 32 | labels = append(labels, s[begin:end-1]) 33 | begin = end 34 | } 35 | } 36 | 37 | labels = append(labels, s[begin:fqdnEnd]) 38 | return labels 39 | } 40 | 41 | // CompareDomainName compares the names s1 and s2 and 42 | // returns how many labels they have in common starting from the *right*. 43 | // The comparison stops at the first inequality. The names are not downcased 44 | // before the comparison. 45 | // 46 | // www.miek.nl. and miek.nl. have two labels in common: miek and nl 47 | // www.miek.nl. and www.bla.nl. have one label in common: nl 48 | func CompareDomainName(s1, s2 string) (n int) { 49 | s1 = Fqdn(s1) 50 | s2 = Fqdn(s2) 51 | l1 := Split(s1) 52 | l2 := Split(s2) 53 | 54 | // the first check: root label 55 | if l1 == nil || l2 == nil { 56 | return 57 | } 58 | 59 | j1 := len(l1) - 1 // end 60 | i1 := len(l1) - 2 // start 61 | j2 := len(l2) - 1 62 | i2 := len(l2) - 2 63 | // the second check can be done here: last/only label 64 | // before we fall through into the for-loop below 65 | if s1[l1[j1]:] == s2[l2[j2]:] { 66 | n++ 67 | } else { 68 | return 69 | } 70 | for { 71 | if i1 < 0 || i2 < 0 { 72 | break 73 | } 74 | if s1[l1[i1]:l1[j1]] == s2[l2[i2]:l2[j2]] { 75 | n++ 76 | } else { 77 | break 78 | } 79 | j1-- 80 | i1-- 81 | j2-- 82 | i2-- 83 | } 84 | return 85 | } 86 | 87 | // CountLabel counts the the number of labels in the string s. 88 | func CountLabel(s string) (labels int) { 89 | if s == "." { 90 | return 91 | } 92 | off := 0 93 | end := false 94 | for { 95 | off, end = NextLabel(s, off) 96 | labels++ 97 | if end { 98 | return 99 | } 100 | } 101 | } 102 | 103 | // Split splits a name s into its label indexes. 104 | // www.miek.nl. returns []int{0, 4, 9}, www.miek.nl also returns []int{0, 4, 9}. 105 | // The root name (.) returns nil. Also see SplitDomainName. 106 | func Split(s string) []int { 107 | if s == "." { 108 | return nil 109 | } 110 | idx := make([]int, 1, 3) 111 | off := 0 112 | end := false 113 | 114 | for { 115 | off, end = NextLabel(s, off) 116 | if end { 117 | return idx 118 | } 119 | idx = append(idx, off) 120 | } 121 | } 122 | 123 | // NextLabel returns the index of the start of the next label in the 124 | // string s starting at offset. 125 | // The bool end is true when the end of the string has been reached. 126 | // Also see PrevLabel. 127 | func NextLabel(s string, offset int) (i int, end bool) { 128 | quote := false 129 | for i = offset; i < len(s)-1; i++ { 130 | switch s[i] { 131 | case '\\': 132 | quote = !quote 133 | default: 134 | quote = false 135 | case '.': 136 | if quote { 137 | quote = !quote 138 | continue 139 | } 140 | return i + 1, false 141 | } 142 | } 143 | return i + 1, true 144 | } 145 | 146 | // PrevLabel returns the index of the label when starting from the right and 147 | // jumping n labels to the left. 148 | // The bool start is true when the start of the string has been overshot. 149 | // Also see NextLabel. 150 | func PrevLabel(s string, n int) (i int, start bool) { 151 | if n == 0 { 152 | return len(s), false 153 | } 154 | lab := Split(s) 155 | if lab == nil { 156 | return 0, true 157 | } 158 | if n > len(lab) { 159 | return 0, true 160 | } 161 | return lab[len(lab)-n], false 162 | } 163 | -------------------------------------------------------------------------------- /labels_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestCompareDomainName(t *testing.T) { 8 | s1 := "www.miek.nl." 9 | s2 := "miek.nl." 10 | s3 := "www.bla.nl." 11 | s4 := "nl.www.bla." 12 | s5 := "nl" 13 | s6 := "miek.nl" 14 | 15 | if CompareDomainName(s1, s2) != 2 { 16 | t.Errorf("%s with %s should be %d", s1, s2, 2) 17 | } 18 | if CompareDomainName(s1, s3) != 1 { 19 | t.Errorf("%s with %s should be %d", s1, s3, 1) 20 | } 21 | if CompareDomainName(s3, s4) != 0 { 22 | t.Errorf("%s with %s should be %d", s3, s4, 0) 23 | } 24 | // Non qualified tests 25 | if CompareDomainName(s1, s5) != 1 { 26 | t.Errorf("%s with %s should be %d", s1, s5, 1) 27 | } 28 | if CompareDomainName(s1, s6) != 2 { 29 | t.Errorf("%s with %s should be %d", s1, s5, 2) 30 | } 31 | 32 | if CompareDomainName(s1, ".") != 0 { 33 | t.Errorf("%s with %s should be %d", s1, s5, 0) 34 | } 35 | if CompareDomainName(".", ".") != 0 { 36 | t.Errorf("%s with %s should be %d", ".", ".", 0) 37 | } 38 | } 39 | 40 | func TestSplit(t *testing.T) { 41 | splitter := map[string]int{ 42 | "www.miek.nl.": 3, 43 | "www.miek.nl": 3, 44 | "www..miek.nl": 4, 45 | `www\.miek.nl.`: 2, 46 | `www\\.miek.nl.`: 3, 47 | ".": 0, 48 | "nl.": 1, 49 | "nl": 1, 50 | "com.": 1, 51 | ".com.": 2, 52 | } 53 | for s, i := range splitter { 54 | if x := len(Split(s)); x != i { 55 | t.Errorf("labels should be %d, got %d: %s %v", i, x, s, Split(s)) 56 | } else { 57 | t.Logf("%s %v", s, Split(s)) 58 | } 59 | } 60 | } 61 | 62 | func TestSplit2(t *testing.T) { 63 | splitter := map[string][]int{ 64 | "www.miek.nl.": []int{0, 4, 9}, 65 | "www.miek.nl": []int{0, 4, 9}, 66 | "nl": []int{0}, 67 | } 68 | for s, i := range splitter { 69 | x := Split(s) 70 | switch len(i) { 71 | case 1: 72 | if x[0] != i[0] { 73 | t.Errorf("labels should be %v, got %v: %s", i, x, s) 74 | } 75 | default: 76 | if x[0] != i[0] || x[1] != i[1] || x[2] != i[2] { 77 | t.Errorf("labels should be %v, got %v: %s", i, x, s) 78 | } 79 | } 80 | } 81 | } 82 | 83 | func TestPrevLabel(t *testing.T) { 84 | type prev struct { 85 | string 86 | int 87 | } 88 | prever := map[prev]int{ 89 | prev{"www.miek.nl.", 0}: 12, 90 | prev{"www.miek.nl.", 1}: 9, 91 | prev{"www.miek.nl.", 2}: 4, 92 | 93 | prev{"www.miek.nl", 0}: 11, 94 | prev{"www.miek.nl", 1}: 9, 95 | prev{"www.miek.nl", 2}: 4, 96 | 97 | prev{"www.miek.nl.", 5}: 0, 98 | prev{"www.miek.nl", 5}: 0, 99 | 100 | prev{"www.miek.nl.", 3}: 0, 101 | prev{"www.miek.nl", 3}: 0, 102 | } 103 | for s, i := range prever { 104 | x, ok := PrevLabel(s.string, s.int) 105 | if i != x { 106 | t.Errorf("label should be %d, got %d, %t: preving %d, %s", i, x, ok, s.int, s.string) 107 | } 108 | } 109 | } 110 | 111 | func TestCountLabel(t *testing.T) { 112 | splitter := map[string]int{ 113 | "www.miek.nl.": 3, 114 | "www.miek.nl": 3, 115 | "nl": 1, 116 | ".": 0, 117 | } 118 | for s, i := range splitter { 119 | x := CountLabel(s) 120 | if x != i { 121 | t.Errorf("CountLabel should have %d, got %d", i, x) 122 | } 123 | } 124 | } 125 | 126 | func TestSplitDomainName(t *testing.T) { 127 | labels := map[string][]string{ 128 | "miek.nl": []string{"miek", "nl"}, 129 | ".": nil, 130 | "www.miek.nl.": []string{"www", "miek", "nl"}, 131 | "www.miek.nl": []string{"www", "miek", "nl"}, 132 | "www..miek.nl": []string{"www", "", "miek", "nl"}, 133 | `www\.miek.nl`: []string{`www\.miek`, "nl"}, 134 | `www\\.miek.nl`: []string{`www\\`, "miek", "nl"}, 135 | } 136 | domainLoop: 137 | for domain, splits := range labels { 138 | parts := SplitDomainName(domain) 139 | if len(parts) != len(splits) { 140 | t.Errorf("SplitDomainName returned %v for %s, expected %v", parts, domain, splits) 141 | continue domainLoop 142 | } 143 | for i := range parts { 144 | if parts[i] != splits[i] { 145 | t.Errorf("SplitDomainName returned %v for %s, expected %v", parts, domain, splits) 146 | continue domainLoop 147 | } 148 | } 149 | } 150 | } 151 | 152 | func TestIsDomainName(t *testing.T) { 153 | type ret struct { 154 | ok bool 155 | lab int 156 | } 157 | names := map[string]*ret{ 158 | "..": &ret{false, 1}, 159 | "@.": &ret{true, 1}, 160 | "www.example.com": &ret{true, 3}, 161 | "www.e%ample.com": &ret{true, 3}, 162 | "www.example.com.": &ret{true, 3}, 163 | "mi\\k.nl.": &ret{true, 2}, 164 | "mi\\k.nl": &ret{true, 2}, 165 | } 166 | for d, ok := range names { 167 | l, k := IsDomainName(d) 168 | if ok.ok != k || ok.lab != l { 169 | t.Errorf(" got %v %d for %s ", k, l, d) 170 | t.Errorf("have %v %d for %s ", ok.ok, ok.lab, d) 171 | } 172 | } 173 | } 174 | 175 | func BenchmarkSplitLabels(b *testing.B) { 176 | for i := 0; i < b.N; i++ { 177 | Split("www.example.com") 178 | } 179 | } 180 | 181 | func BenchmarkLenLabels(b *testing.B) { 182 | for i := 0; i < b.N; i++ { 183 | CountLabel("www.example.com") 184 | } 185 | } 186 | 187 | func BenchmarkCompareLabels(b *testing.B) { 188 | for i := 0; i < b.N; i++ { 189 | CompareDomainName("www.example.com", "aa.example.com") 190 | } 191 | } 192 | 193 | func BenchmarkIsSubDomain(b *testing.B) { 194 | for i := 0; i < b.N; i++ { 195 | IsSubDomain("www.example.com", "aa.example.com") 196 | IsSubDomain("example.com", "aa.example.com") 197 | IsSubDomain("miek.nl", "aa.example.com") 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /nsecx.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "crypto/sha1" 5 | "hash" 6 | "io" 7 | "strings" 8 | ) 9 | 10 | type saltWireFmt struct { 11 | Salt string `dns:"size-hex"` 12 | } 13 | 14 | // HashName hashes a string (label) according to RFC 5155. It returns the hashed string in 15 | // uppercase. 16 | func HashName(label string, ha uint8, iter uint16, salt string) string { 17 | saltwire := new(saltWireFmt) 18 | saltwire.Salt = salt 19 | wire := make([]byte, DefaultMsgSize) 20 | n, err := PackStruct(saltwire, wire, 0) 21 | if err != nil { 22 | return "" 23 | } 24 | wire = wire[:n] 25 | name := make([]byte, 255) 26 | off, err := PackDomainName(strings.ToLower(label), name, 0, nil, false) 27 | if err != nil { 28 | return "" 29 | } 30 | name = name[:off] 31 | var s hash.Hash 32 | switch ha { 33 | case SHA1: 34 | s = sha1.New() 35 | default: 36 | return "" 37 | } 38 | 39 | // k = 0 40 | name = append(name, wire...) 41 | io.WriteString(s, string(name)) 42 | nsec3 := s.Sum(nil) 43 | // k > 0 44 | for k := uint16(0); k < iter; k++ { 45 | s.Reset() 46 | nsec3 = append(nsec3, wire...) 47 | io.WriteString(s, string(nsec3)) 48 | nsec3 = s.Sum(nil) 49 | } 50 | return toBase32(nsec3) 51 | } 52 | 53 | // Denialer is an interface that should be implemented by types that are used to denial 54 | // answers in DNSSEC. 55 | type Denialer interface { 56 | // Cover will check if the (unhashed) name is being covered by this NSEC or NSEC3. 57 | Cover(name string) bool 58 | // Match will check if the ownername matches the (unhashed) name for this NSEC3 or NSEC3. 59 | Match(name string) bool 60 | } 61 | 62 | // Cover implements the Denialer interface. 63 | func (rr *NSEC) Cover(name string) bool { 64 | return true 65 | } 66 | 67 | // Match implements the Denialer interface. 68 | func (rr *NSEC) Match(name string) bool { 69 | return true 70 | } 71 | 72 | // Cover implements the Denialer interface. 73 | func (rr *NSEC3) Cover(name string) bool { 74 | // FIXME(miek): check if the zones match 75 | // FIXME(miek): check if we're not dealing with parent nsec3 76 | hname := HashName(name, rr.Hash, rr.Iterations, rr.Salt) 77 | labels := Split(rr.Hdr.Name) 78 | if len(labels) < 2 { 79 | return false 80 | } 81 | hash := strings.ToUpper(rr.Hdr.Name[labels[0] : labels[1]-1]) // -1 to remove the dot 82 | if hash == rr.NextDomain { 83 | return false // empty interval 84 | } 85 | if hash > rr.NextDomain { // last name, points to apex 86 | // hname > hash 87 | // hname > rr.NextDomain 88 | // TODO(miek) 89 | } 90 | if hname <= hash { 91 | return false 92 | } 93 | if hname >= rr.NextDomain { 94 | return false 95 | } 96 | return true 97 | } 98 | 99 | // Match implements the Denialer interface. 100 | func (rr *NSEC3) Match(name string) bool { 101 | // FIXME(miek): Check if we are in the same zone 102 | hname := HashName(name, rr.Hash, rr.Iterations, rr.Salt) 103 | labels := Split(rr.Hdr.Name) 104 | if len(labels) < 2 { 105 | return false 106 | } 107 | hash := strings.ToUpper(rr.Hdr.Name[labels[0] : labels[1]-1]) // -1 to remove the . 108 | if hash == hname { 109 | return true 110 | } 111 | return false 112 | } 113 | -------------------------------------------------------------------------------- /nsecx_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestPackNsec3(t *testing.T) { 8 | nsec3 := HashName("dnsex.nl.", SHA1, 0, "DEAD") 9 | if nsec3 != "ROCCJAE8BJJU7HN6T7NG3TNM8ACRS87J" { 10 | t.Error(nsec3) 11 | } 12 | 13 | nsec3 = HashName("a.b.c.example.org.", SHA1, 2, "DEAD") 14 | if nsec3 != "6LQ07OAHBTOOEU2R9ANI2AT70K5O0RCG" { 15 | t.Error(nsec3) 16 | } 17 | } 18 | 19 | func TestNsec3(t *testing.T) { 20 | // examples taken from .nl 21 | nsec3, _ := NewRR("39p91242oslggest5e6a7cci4iaeqvnk.nl. IN NSEC3 1 1 5 F10E9F7EA83FC8F3 39P99DCGG0MDLARTCRMCF6OFLLUL7PR6 NS DS RRSIG") 22 | if !nsec3.(*NSEC3).Cover("snasajsksasasa.nl.") { // 39p94jrinub66hnpem8qdpstrec86pg3 23 | t.Error("39p94jrinub66hnpem8qdpstrec86pg3. should be covered by 39p91242oslggest5e6a7cci4iaeqvnk.nl. - 39P99DCGG0MDLARTCRMCF6OFLLUL7PR6") 24 | } 25 | nsec3, _ = NewRR("sk4e8fj94u78smusb40o1n0oltbblu2r.nl. IN NSEC3 1 1 5 F10E9F7EA83FC8F3 SK4F38CQ0ATIEI8MH3RGD0P5I4II6QAN NS SOA TXT RRSIG DNSKEY NSEC3PARAM") 26 | if !nsec3.(*NSEC3).Match("nl.") { // sk4e8fj94u78smusb40o1n0oltbblu2r.nl. 27 | t.Error("sk4e8fj94u78smusb40o1n0oltbblu2r.nl. should match sk4e8fj94u78smusb40o1n0oltbblu2r.nl.") 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /privaterr.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | // PrivateRdata is an interface used for implementing "Private Use" RR types, see 9 | // RFC 6895. This allows one to experiment with new RR types, without requesting an 10 | // official type code. Also see dns.PrivateHandle and dns.PrivateHandleRemove. 11 | type PrivateRdata interface { 12 | // String returns the text presentaton of the Rdata of the Private RR. 13 | String() string 14 | // Parse parses the Rdata of the private RR. 15 | Parse([]string) error 16 | // Pack is used when packing a private RR into a buffer. 17 | Pack([]byte) (int, error) 18 | // Unpack is used when unpacking a private RR from a buffer. 19 | // TODO(miek): diff. signature than Pack, see edns0.go for instance. 20 | Unpack([]byte) (int, error) 21 | // Copy copies the Rdata. 22 | Copy(PrivateRdata) error 23 | // Len returns the length in octets of the Rdata. 24 | Len() int 25 | } 26 | 27 | // PrivateRR represents an RR that uses a PrivateRdata user-defined type. 28 | // It mocks normal RRs and implements dns.RR interface. 29 | type PrivateRR struct { 30 | Hdr RR_Header 31 | Data PrivateRdata 32 | } 33 | 34 | func mkPrivateRR(rrtype uint16) *PrivateRR { 35 | // Panics if RR is not an instance of PrivateRR. 36 | rrfunc, ok := typeToRR[rrtype] 37 | if !ok { 38 | panic(fmt.Sprintf("dns: invalid operation with Private RR type %d", rrtype)) 39 | } 40 | 41 | anyrr := rrfunc() 42 | switch rr := anyrr.(type) { 43 | case *PrivateRR: 44 | return rr 45 | } 46 | panic(fmt.Sprintf("dns: RR is not a PrivateRR, typeToRR[%d] generator returned %T", rrtype, anyrr)) 47 | } 48 | 49 | // Header return the RR header of r. 50 | func (r *PrivateRR) Header() *RR_Header { return &r.Hdr } 51 | 52 | func (r *PrivateRR) String() string { return r.Hdr.String() + r.Data.String() } 53 | 54 | // Private len and copy parts to satisfy RR interface. 55 | func (r *PrivateRR) len() int { return r.Hdr.len() + r.Data.Len() } 56 | func (r *PrivateRR) copy() RR { 57 | // make new RR like this: 58 | rr := mkPrivateRR(r.Hdr.Rrtype) 59 | newh := r.Hdr.copyHeader() 60 | rr.Hdr = *newh 61 | 62 | err := r.Data.Copy(rr.Data) 63 | if err != nil { 64 | panic("dns: got value that could not be used to copy Private rdata") 65 | } 66 | return rr 67 | } 68 | 69 | // PrivateHandle registers a private resource record type. It requires 70 | // string and numeric representation of private RR type and generator function as argument. 71 | func PrivateHandle(rtypestr string, rtype uint16, generator func() PrivateRdata) { 72 | rtypestr = strings.ToUpper(rtypestr) 73 | 74 | typeToRR[rtype] = func() RR { return &PrivateRR{RR_Header{}, generator()} } 75 | TypeToString[rtype] = rtypestr 76 | StringToType[rtypestr] = rtype 77 | 78 | setPrivateRR := func(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) { 79 | rr := mkPrivateRR(h.Rrtype) 80 | rr.Hdr = h 81 | 82 | var l lex 83 | text := make([]string, 0, 2) // could be 0..N elements, median is probably 1 84 | FETCH: 85 | for { 86 | // TODO(miek): we could also be returning _QUOTE, this might or might not 87 | // be an issue (basically parsing TXT becomes hard) 88 | switch l = <-c; l.value { 89 | case zNewline, zEOF: 90 | break FETCH 91 | case zString: 92 | text = append(text, l.token) 93 | } 94 | } 95 | 96 | err := rr.Data.Parse(text) 97 | if err != nil { 98 | return nil, &ParseError{f, err.Error(), l}, "" 99 | } 100 | 101 | return rr, nil, "" 102 | } 103 | 104 | typeToparserFunc[rtype] = parserFunc{setPrivateRR, true} 105 | } 106 | 107 | // PrivateHandleRemove removes defenitions required to support private RR type. 108 | func PrivateHandleRemove(rtype uint16) { 109 | rtypestr, ok := TypeToString[rtype] 110 | if ok { 111 | delete(typeToRR, rtype) 112 | delete(TypeToString, rtype) 113 | delete(typeToparserFunc, rtype) 114 | delete(StringToType, rtypestr) 115 | } 116 | return 117 | } 118 | -------------------------------------------------------------------------------- /privaterr_test.go: -------------------------------------------------------------------------------- 1 | package dns_test 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | 7 | "github.com/cloudflare/dns" 8 | ) 9 | 10 | const TypeISBN uint16 = 0x0F01 11 | 12 | // A crazy new RR type :) 13 | type ISBN struct { 14 | x string // rdata with 10 or 13 numbers, dashes or spaces allowed 15 | } 16 | 17 | func NewISBN() dns.PrivateRdata { return &ISBN{""} } 18 | 19 | func (rd *ISBN) Len() int { return len([]byte(rd.x)) } 20 | func (rd *ISBN) String() string { return rd.x } 21 | 22 | func (rd *ISBN) Parse(txt []string) error { 23 | rd.x = strings.TrimSpace(strings.Join(txt, " ")) 24 | return nil 25 | } 26 | 27 | func (rd *ISBN) Pack(buf []byte) (int, error) { 28 | b := []byte(rd.x) 29 | n := copy(buf, b) 30 | if n != len(b) { 31 | return n, dns.ErrBuf 32 | } 33 | return n, nil 34 | } 35 | 36 | func (rd *ISBN) Unpack(buf []byte) (int, error) { 37 | rd.x = string(buf) 38 | return len(buf), nil 39 | } 40 | 41 | func (rd *ISBN) Copy(dest dns.PrivateRdata) error { 42 | isbn, ok := dest.(*ISBN) 43 | if !ok { 44 | return dns.ErrRdata 45 | } 46 | isbn.x = rd.x 47 | return nil 48 | } 49 | 50 | var testrecord = strings.Join([]string{"example.org.", "3600", "IN", "ISBN", "12-3 456789-0-123"}, "\t") 51 | 52 | func TestPrivateText(t *testing.T) { 53 | dns.PrivateHandle("ISBN", TypeISBN, NewISBN) 54 | defer dns.PrivateHandleRemove(TypeISBN) 55 | 56 | rr, err := dns.NewRR(testrecord) 57 | if err != nil { 58 | t.Fatal(err) 59 | } 60 | if rr.String() != testrecord { 61 | t.Errorf("record string representation did not match original %#v != %#v", rr.String(), testrecord) 62 | } else { 63 | t.Log(rr.String()) 64 | } 65 | } 66 | 67 | func TestPrivateByteSlice(t *testing.T) { 68 | dns.PrivateHandle("ISBN", TypeISBN, NewISBN) 69 | defer dns.PrivateHandleRemove(TypeISBN) 70 | 71 | rr, err := dns.NewRR(testrecord) 72 | if err != nil { 73 | t.Fatal(err) 74 | } 75 | 76 | buf := make([]byte, 100) 77 | off, err := dns.PackRR(rr, buf, 0, nil, false) 78 | if err != nil { 79 | t.Errorf("got error packing ISBN: %v", err) 80 | } 81 | 82 | custrr := rr.(*dns.PrivateRR) 83 | if ln := custrr.Data.Len() + len(custrr.Header().Name) + 11; ln != off { 84 | t.Errorf("offset is not matching to length of Private RR: %d!=%d", off, ln) 85 | } 86 | 87 | rr1, off1, err := dns.UnpackRR(buf[:off], 0) 88 | if err != nil { 89 | t.Errorf("got error unpacking ISBN: %v", err) 90 | } 91 | 92 | if off1 != off { 93 | t.Errorf("Offset after unpacking differs: %d != %d", off1, off) 94 | } 95 | 96 | if rr1.String() != testrecord { 97 | t.Errorf("Record string representation did not match original %#v != %#v", rr1.String(), testrecord) 98 | } else { 99 | t.Log(rr1.String()) 100 | } 101 | } 102 | 103 | const TypeVERSION uint16 = 0x0F02 104 | 105 | type VERSION struct { 106 | x string 107 | } 108 | 109 | func NewVersion() dns.PrivateRdata { return &VERSION{""} } 110 | 111 | func (rd *VERSION) String() string { return rd.x } 112 | func (rd *VERSION) Parse(txt []string) error { 113 | rd.x = strings.TrimSpace(strings.Join(txt, " ")) 114 | return nil 115 | } 116 | 117 | func (rd *VERSION) Pack(buf []byte) (int, error) { 118 | b := []byte(rd.x) 119 | n := copy(buf, b) 120 | if n != len(b) { 121 | return n, dns.ErrBuf 122 | } 123 | return n, nil 124 | } 125 | 126 | func (rd *VERSION) Unpack(buf []byte) (int, error) { 127 | rd.x = string(buf) 128 | return len(buf), nil 129 | } 130 | 131 | func (rd *VERSION) Copy(dest dns.PrivateRdata) error { 132 | isbn, ok := dest.(*VERSION) 133 | if !ok { 134 | return dns.ErrRdata 135 | } 136 | isbn.x = rd.x 137 | return nil 138 | } 139 | 140 | func (rd *VERSION) Len() int { 141 | return len([]byte(rd.x)) 142 | } 143 | 144 | var smallzone = `$ORIGIN example.org. 145 | @ SOA sns.dns.icann.org. noc.dns.icann.org. ( 146 | 2014091518 7200 3600 1209600 3600 147 | ) 148 | A 1.2.3.4 149 | ok ISBN 1231-92110-12 150 | go VERSION ( 151 | 1.3.1 ; comment 152 | ) 153 | www ISBN 1231-92110-16 154 | * CNAME @ 155 | ` 156 | 157 | func TestPrivateZoneParser(t *testing.T) { 158 | dns.PrivateHandle("ISBN", TypeISBN, NewISBN) 159 | dns.PrivateHandle("VERSION", TypeVERSION, NewVersion) 160 | defer dns.PrivateHandleRemove(TypeISBN) 161 | defer dns.PrivateHandleRemove(TypeVERSION) 162 | 163 | r := strings.NewReader(smallzone) 164 | for x := range dns.ParseZone(r, ".", "") { 165 | if err := x.Error; err != nil { 166 | t.Fatal(err) 167 | } 168 | t.Log(x.RR) 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /rawmsg.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | // These raw* functions do not use reflection, they directly set the values 4 | // in the buffer. There are faster than their reflection counterparts. 5 | 6 | // RawSetId sets the message id in buf. 7 | func rawSetId(msg []byte, i uint16) bool { 8 | if len(msg) < 2 { 9 | return false 10 | } 11 | msg[0], msg[1] = packUint16(i) 12 | return true 13 | } 14 | 15 | // rawSetQuestionLen sets the length of the question section. 16 | func rawSetQuestionLen(msg []byte, i uint16) bool { 17 | if len(msg) < 6 { 18 | return false 19 | } 20 | msg[4], msg[5] = packUint16(i) 21 | return true 22 | } 23 | 24 | // rawSetAnswerLen sets the lenght of the answer section. 25 | func rawSetAnswerLen(msg []byte, i uint16) bool { 26 | if len(msg) < 8 { 27 | return false 28 | } 29 | msg[6], msg[7] = packUint16(i) 30 | return true 31 | } 32 | 33 | // rawSetsNsLen sets the lenght of the authority section. 34 | func rawSetNsLen(msg []byte, i uint16) bool { 35 | if len(msg) < 10 { 36 | return false 37 | } 38 | msg[8], msg[9] = packUint16(i) 39 | return true 40 | } 41 | 42 | // rawSetExtraLen sets the lenght of the additional section. 43 | func rawSetExtraLen(msg []byte, i uint16) bool { 44 | if len(msg) < 12 { 45 | return false 46 | } 47 | msg[10], msg[11] = packUint16(i) 48 | return true 49 | } 50 | 51 | // rawSetRdlength sets the rdlength in the header of 52 | // the RR. The offset 'off' must be positioned at the 53 | // start of the header of the RR, 'end' must be the 54 | // end of the RR. 55 | func rawSetRdlength(msg []byte, off, end int) bool { 56 | l := len(msg) 57 | Loop: 58 | for { 59 | if off+1 > l { 60 | return false 61 | } 62 | c := int(msg[off]) 63 | off++ 64 | switch c & 0xC0 { 65 | case 0x00: 66 | if c == 0x00 { 67 | // End of the domainname 68 | break Loop 69 | } 70 | if off+c > l { 71 | return false 72 | } 73 | off += c 74 | 75 | case 0xC0: 76 | // pointer, next byte included, ends domainname 77 | off++ 78 | break Loop 79 | } 80 | } 81 | // The domainname has been seen, we at the start of the fixed part in the header. 82 | // Type is 2 bytes, class is 2 bytes, ttl 4 and then 2 bytes for the length. 83 | off += 2 + 2 + 4 84 | if off+2 > l { 85 | return false 86 | } 87 | //off+1 is the end of the header, 'end' is the end of the rr 88 | //so 'end' - 'off+2' is the length of the rdata 89 | rdatalen := end - (off + 2) 90 | if rdatalen > 0xFFFF { 91 | return false 92 | } 93 | msg[off], msg[off+1] = packUint16(uint16(rdatalen)) 94 | return true 95 | } 96 | -------------------------------------------------------------------------------- /remote_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import "testing" 4 | 5 | const LinodeAddr = "176.58.119.54:53" 6 | 7 | func TestClientRemote(t *testing.T) { 8 | m := new(Msg) 9 | m.SetQuestion("go.dns.miek.nl.", TypeTXT) 10 | 11 | c := new(Client) 12 | r, _, err := c.Exchange(m, LinodeAddr) 13 | if err != nil { 14 | t.Errorf("failed to exchange: %v", err) 15 | } 16 | if r != nil && r.Rcode != RcodeSuccess { 17 | t.Errorf("failed to get an valid answer\n%v", r) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /sanitize.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | // Dedup removes identical RRs from rrs. It preserves the original ordering. 4 | // The lowest TTL of any duplicates is used in the remaining one. Dedup modifies 5 | // rrs. 6 | // m is used to store the RRs temporay. If it is nil a new map will be allocated. 7 | func Dedup(rrs []RR, m map[string]RR) []RR { 8 | if m == nil { 9 | m = make(map[string]RR) 10 | } 11 | // Save the keys, so we don't have to call normalizedString twice. 12 | keys := make([]*string, 0, len(rrs)) 13 | 14 | for _, r := range rrs { 15 | key := normalizedString(r) 16 | keys = append(keys, &key) 17 | if _, ok := m[key]; ok { 18 | // Shortest TTL wins. 19 | if m[key].Header().Ttl > r.Header().Ttl { 20 | m[key].Header().Ttl = r.Header().Ttl 21 | } 22 | continue 23 | } 24 | 25 | m[key] = r 26 | } 27 | // If the length of the result map equals the amount of RRs we got, 28 | // it means they were all different. We can then just return the original rrset. 29 | if len(m) == len(rrs) { 30 | return rrs 31 | } 32 | 33 | j := 0 34 | for i, r := range rrs { 35 | // If keys[i] lives in the map, we should copy and remove it. 36 | if _, ok := m[*keys[i]]; ok { 37 | delete(m, *keys[i]) 38 | rrs[j] = r 39 | j++ 40 | } 41 | 42 | if len(m) == 0 { 43 | break 44 | } 45 | } 46 | 47 | return rrs[:j] 48 | } 49 | 50 | // normalizedString returns a normalized string from r. The TTL 51 | // is removed and the domain name is lowercased. We go from this: 52 | // DomainNameTTLCLASSTYPERDATA to: 53 | // lowercasenameCLASSTYPE... 54 | func normalizedString(r RR) string { 55 | // A string Go DNS makes has: domainnameTTL... 56 | b := []byte(r.String()) 57 | 58 | // find the first non-escaped tab, then another, so we capture where the TTL lives. 59 | esc := false 60 | ttlStart, ttlEnd := 0, 0 61 | for i := 0; i < len(b) && ttlEnd == 0; i++ { 62 | switch { 63 | case b[i] == '\\': 64 | esc = !esc 65 | case b[i] == '\t' && !esc: 66 | if ttlStart == 0 { 67 | ttlStart = i 68 | continue 69 | } 70 | if ttlEnd == 0 { 71 | ttlEnd = i 72 | } 73 | case b[i] >= 'A' && b[i] <= 'Z' && !esc: 74 | b[i] += 32 75 | default: 76 | esc = false 77 | } 78 | } 79 | 80 | // remove TTL. 81 | copy(b[ttlStart:], b[ttlEnd:]) 82 | cut := ttlEnd - ttlStart 83 | return string(b[:len(b)-cut]) 84 | } 85 | -------------------------------------------------------------------------------- /sanitize_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import "testing" 4 | 5 | func TestDedup(t *testing.T) { 6 | // make it []string 7 | testcases := map[[3]RR][]string{ 8 | [...]RR{ 9 | newRR(t, "mIek.nl. IN A 127.0.0.1"), 10 | newRR(t, "mieK.nl. IN A 127.0.0.1"), 11 | newRR(t, "miek.Nl. IN A 127.0.0.1"), 12 | }: []string{"mIek.nl.\t3600\tIN\tA\t127.0.0.1"}, 13 | [...]RR{ 14 | newRR(t, "miEk.nl. 2000 IN A 127.0.0.1"), 15 | newRR(t, "mieK.Nl. 1000 IN A 127.0.0.1"), 16 | newRR(t, "Miek.nL. 500 IN A 127.0.0.1"), 17 | }: []string{"miEk.nl.\t500\tIN\tA\t127.0.0.1"}, 18 | [...]RR{ 19 | newRR(t, "miek.nl. IN A 127.0.0.1"), 20 | newRR(t, "miek.nl. CH A 127.0.0.1"), 21 | newRR(t, "miek.nl. IN A 127.0.0.1"), 22 | }: []string{"miek.nl.\t3600\tIN\tA\t127.0.0.1", 23 | "miek.nl.\t3600\tCH\tA\t127.0.0.1", 24 | }, 25 | [...]RR{ 26 | newRR(t, "miek.nl. CH A 127.0.0.1"), 27 | newRR(t, "miek.nl. IN A 127.0.0.1"), 28 | newRR(t, "miek.de. IN A 127.0.0.1"), 29 | }: []string{"miek.nl.\t3600\tCH\tA\t127.0.0.1", 30 | "miek.nl.\t3600\tIN\tA\t127.0.0.1", 31 | "miek.de.\t3600\tIN\tA\t127.0.0.1", 32 | }, 33 | [...]RR{ 34 | newRR(t, "miek.de. IN A 127.0.0.1"), 35 | newRR(t, "miek.nl. 200 IN A 127.0.0.1"), 36 | newRR(t, "miek.nl. 300 IN A 127.0.0.1"), 37 | }: []string{"miek.de.\t3600\tIN\tA\t127.0.0.1", 38 | "miek.nl.\t200\tIN\tA\t127.0.0.1", 39 | }, 40 | } 41 | 42 | for rr, expected := range testcases { 43 | out := Dedup([]RR{rr[0], rr[1], rr[2]}, nil) 44 | for i, o := range out { 45 | if o.String() != expected[i] { 46 | t.Fatalf("expected %v, got %v", expected[i], o.String()) 47 | } 48 | } 49 | } 50 | } 51 | 52 | func BenchmarkDedup(b *testing.B) { 53 | rrs := []RR{ 54 | newRR(nil, "miEk.nl. 2000 IN A 127.0.0.1"), 55 | newRR(nil, "mieK.Nl. 1000 IN A 127.0.0.1"), 56 | newRR(nil, "Miek.nL. 500 IN A 127.0.0.1"), 57 | } 58 | m := make(map[string]RR) 59 | for i := 0; i < b.N; i++ { 60 | Dedup(rrs,m ) 61 | } 62 | } 63 | 64 | func TestNormalizedString(t *testing.T) { 65 | tests := map[RR]string{ 66 | newRR(t, "mIEk.Nl. 3600 IN A 127.0.0.1"): "miek.nl.\tIN\tA\t127.0.0.1", 67 | newRR(t, "m\\ iek.nL. 3600 IN A 127.0.0.1"): "m\\ iek.nl.\tIN\tA\t127.0.0.1", 68 | newRR(t, "m\\\tIeK.nl. 3600 in A 127.0.0.1"): "m\\tiek.nl.\tIN\tA\t127.0.0.1", 69 | } 70 | for tc, expected := range tests { 71 | n := normalizedString(tc) 72 | if n != expected { 73 | t.Logf("expected %s, got %s", expected, n) 74 | t.Fail() 75 | } 76 | } 77 | } 78 | 79 | func newRR(t *testing.T, s string) RR { 80 | r, e := NewRR(s) 81 | if e != nil { 82 | t.Logf("newRR: %s", e) 83 | } 84 | return r 85 | } 86 | -------------------------------------------------------------------------------- /scanner.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | // Implement a simple scanner, return a byte stream from an io reader. 4 | 5 | import ( 6 | "bufio" 7 | "io" 8 | "text/scanner" 9 | ) 10 | 11 | type scan struct { 12 | src *bufio.Reader 13 | position scanner.Position 14 | eof bool // Have we just seen a eof 15 | } 16 | 17 | func scanInit(r io.Reader) *scan { 18 | s := new(scan) 19 | s.src = bufio.NewReader(r) 20 | s.position.Line = 1 21 | return s 22 | } 23 | 24 | // tokenText returns the next byte from the input 25 | func (s *scan) tokenText() (byte, error) { 26 | c, err := s.src.ReadByte() 27 | if err != nil { 28 | return c, err 29 | } 30 | // delay the newline handling until the next token is delivered, 31 | // fixes off-by-one errors when reporting a parse error. 32 | if s.eof == true { 33 | s.position.Line++ 34 | s.position.Column = 0 35 | s.eof = false 36 | } 37 | if c == '\n' { 38 | s.eof = true 39 | return c, nil 40 | } 41 | s.position.Column++ 42 | return c, nil 43 | } 44 | -------------------------------------------------------------------------------- /server_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "runtime" 7 | "sync" 8 | "testing" 9 | "time" 10 | ) 11 | 12 | func HelloServer(w ResponseWriter, req *Msg) { 13 | m := new(Msg) 14 | m.SetReply(req) 15 | 16 | m.Extra = make([]RR, 1) 17 | m.Extra[0] = &TXT{Hdr: RR_Header{Name: m.Question[0].Name, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}, Txt: []string{"Hello world"}} 18 | w.WriteMsg(m) 19 | } 20 | 21 | func HelloServerBadId(w ResponseWriter, req *Msg) { 22 | m := new(Msg) 23 | m.SetReply(req) 24 | m.Id++ 25 | 26 | m.Extra = make([]RR, 1) 27 | m.Extra[0] = &TXT{Hdr: RR_Header{Name: m.Question[0].Name, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}, Txt: []string{"Hello world"}} 28 | w.WriteMsg(m) 29 | } 30 | 31 | func AnotherHelloServer(w ResponseWriter, req *Msg) { 32 | m := new(Msg) 33 | m.SetReply(req) 34 | 35 | m.Extra = make([]RR, 1) 36 | m.Extra[0] = &TXT{Hdr: RR_Header{Name: m.Question[0].Name, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}, Txt: []string{"Hello example"}} 37 | w.WriteMsg(m) 38 | } 39 | 40 | func RunLocalUDPServer(laddr string) (*Server, string, error) { 41 | pc, err := net.ListenPacket("udp", laddr) 42 | if err != nil { 43 | return nil, "", err 44 | } 45 | server := &Server{PacketConn: pc, ReadTimeout: time.Hour, WriteTimeout: time.Hour} 46 | 47 | waitLock := sync.Mutex{} 48 | waitLock.Lock() 49 | server.NotifyStartedFunc = waitLock.Unlock 50 | 51 | go func() { 52 | server.ActivateAndServe() 53 | pc.Close() 54 | }() 55 | 56 | waitLock.Lock() 57 | return server, pc.LocalAddr().String(), nil 58 | } 59 | 60 | func RunLocalUDPServerUnsafe(laddr string) (*Server, string, error) { 61 | pc, err := net.ListenPacket("udp", laddr) 62 | if err != nil { 63 | return nil, "", err 64 | } 65 | server := &Server{PacketConn: pc, Unsafe: true, 66 | ReadTimeout: time.Hour, WriteTimeout: time.Hour} 67 | 68 | waitLock := sync.Mutex{} 69 | waitLock.Lock() 70 | server.NotifyStartedFunc = waitLock.Unlock 71 | 72 | go func() { 73 | server.ActivateAndServe() 74 | pc.Close() 75 | }() 76 | 77 | waitLock.Lock() 78 | return server, pc.LocalAddr().String(), nil 79 | } 80 | 81 | func RunLocalTCPServer(laddr string) (*Server, string, error) { 82 | l, err := net.Listen("tcp", laddr) 83 | if err != nil { 84 | return nil, "", err 85 | } 86 | 87 | server := &Server{Listener: l, ReadTimeout: time.Hour, WriteTimeout: time.Hour} 88 | 89 | waitLock := sync.Mutex{} 90 | waitLock.Lock() 91 | server.NotifyStartedFunc = waitLock.Unlock 92 | 93 | go func() { 94 | server.ActivateAndServe() 95 | l.Close() 96 | }() 97 | 98 | waitLock.Lock() 99 | return server, l.Addr().String(), nil 100 | } 101 | 102 | func TestServing(t *testing.T) { 103 | HandleFunc("miek.nl.", HelloServer) 104 | HandleFunc("example.com.", AnotherHelloServer) 105 | defer HandleRemove("miek.nl.") 106 | defer HandleRemove("example.com.") 107 | 108 | s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") 109 | if err != nil { 110 | t.Fatalf("Unable to run test server: %v", err) 111 | } 112 | defer s.Shutdown() 113 | 114 | c := new(Client) 115 | m := new(Msg) 116 | m.SetQuestion("miek.nl.", TypeTXT) 117 | r, _, err := c.Exchange(m, addrstr) 118 | if err != nil || len(r.Extra) == 0 { 119 | t.Fatal("failed to exchange miek.nl", err) 120 | } 121 | txt := r.Extra[0].(*TXT).Txt[0] 122 | if txt != "Hello world" { 123 | t.Error("Unexpected result for miek.nl", txt, "!= Hello world") 124 | } 125 | 126 | m.SetQuestion("example.com.", TypeTXT) 127 | r, _, err = c.Exchange(m, addrstr) 128 | if err != nil { 129 | t.Fatal("failed to exchange example.com", err) 130 | } 131 | txt = r.Extra[0].(*TXT).Txt[0] 132 | if txt != "Hello example" { 133 | t.Error("Unexpected result for example.com", txt, "!= Hello example") 134 | } 135 | 136 | // Test Mixes cased as noticed by Ask. 137 | m.SetQuestion("eXaMplE.cOm.", TypeTXT) 138 | r, _, err = c.Exchange(m, addrstr) 139 | if err != nil { 140 | t.Error("failed to exchange eXaMplE.cOm", err) 141 | } 142 | txt = r.Extra[0].(*TXT).Txt[0] 143 | if txt != "Hello example" { 144 | t.Error("Unexpected result for example.com", txt, "!= Hello example") 145 | } 146 | } 147 | 148 | func BenchmarkServe(b *testing.B) { 149 | b.StopTimer() 150 | HandleFunc("miek.nl.", HelloServer) 151 | defer HandleRemove("miek.nl.") 152 | a := runtime.GOMAXPROCS(4) 153 | 154 | s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") 155 | if err != nil { 156 | b.Fatalf("Unable to run test server: %v", err) 157 | } 158 | defer s.Shutdown() 159 | 160 | c := new(Client) 161 | m := new(Msg) 162 | m.SetQuestion("miek.nl", TypeSOA) 163 | 164 | b.StartTimer() 165 | for i := 0; i < b.N; i++ { 166 | c.Exchange(m, addrstr) 167 | } 168 | runtime.GOMAXPROCS(a) 169 | } 170 | 171 | func benchmarkServe6(b *testing.B) { 172 | b.StopTimer() 173 | HandleFunc("miek.nl.", HelloServer) 174 | defer HandleRemove("miek.nl.") 175 | a := runtime.GOMAXPROCS(4) 176 | s, addrstr, err := RunLocalUDPServer("[::1]:0") 177 | if err != nil { 178 | b.Fatalf("Unable to run test server: %v", err) 179 | } 180 | defer s.Shutdown() 181 | 182 | c := new(Client) 183 | m := new(Msg) 184 | m.SetQuestion("miek.nl", TypeSOA) 185 | 186 | b.StartTimer() 187 | for i := 0; i < b.N; i++ { 188 | c.Exchange(m, addrstr) 189 | } 190 | runtime.GOMAXPROCS(a) 191 | } 192 | 193 | func HelloServerCompress(w ResponseWriter, req *Msg) { 194 | m := new(Msg) 195 | m.SetReply(req) 196 | m.Extra = make([]RR, 1) 197 | m.Extra[0] = &TXT{Hdr: RR_Header{Name: m.Question[0].Name, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}, Txt: []string{"Hello world"}} 198 | m.Compress = true 199 | w.WriteMsg(m) 200 | } 201 | 202 | func BenchmarkServeCompress(b *testing.B) { 203 | b.StopTimer() 204 | HandleFunc("miek.nl.", HelloServerCompress) 205 | defer HandleRemove("miek.nl.") 206 | a := runtime.GOMAXPROCS(4) 207 | s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") 208 | if err != nil { 209 | b.Fatalf("Unable to run test server: %v", err) 210 | } 211 | defer s.Shutdown() 212 | 213 | c := new(Client) 214 | m := new(Msg) 215 | m.SetQuestion("miek.nl", TypeSOA) 216 | b.StartTimer() 217 | for i := 0; i < b.N; i++ { 218 | c.Exchange(m, addrstr) 219 | } 220 | runtime.GOMAXPROCS(a) 221 | } 222 | 223 | func TestDotAsCatchAllWildcard(t *testing.T) { 224 | mux := NewServeMux() 225 | mux.Handle(".", HandlerFunc(HelloServer)) 226 | mux.Handle("example.com.", HandlerFunc(AnotherHelloServer)) 227 | 228 | handler := mux.match("www.miek.nl.", TypeTXT) 229 | if handler == nil { 230 | t.Error("wildcard match failed") 231 | } 232 | 233 | handler = mux.match("www.example.com.", TypeTXT) 234 | if handler == nil { 235 | t.Error("example.com match failed") 236 | } 237 | 238 | handler = mux.match("a.www.example.com.", TypeTXT) 239 | if handler == nil { 240 | t.Error("a.www.example.com match failed") 241 | } 242 | 243 | handler = mux.match("boe.", TypeTXT) 244 | if handler == nil { 245 | t.Error("boe. match failed") 246 | } 247 | } 248 | 249 | func TestCaseFolding(t *testing.T) { 250 | mux := NewServeMux() 251 | mux.Handle("_udp.example.com.", HandlerFunc(HelloServer)) 252 | 253 | handler := mux.match("_dns._udp.example.com.", TypeSRV) 254 | if handler == nil { 255 | t.Error("case sensitive characters folded") 256 | } 257 | 258 | handler = mux.match("_DNS._UDP.EXAMPLE.COM.", TypeSRV) 259 | if handler == nil { 260 | t.Error("case insensitive characters not folded") 261 | } 262 | } 263 | 264 | func TestRootServer(t *testing.T) { 265 | mux := NewServeMux() 266 | mux.Handle(".", HandlerFunc(HelloServer)) 267 | 268 | handler := mux.match(".", TypeNS) 269 | if handler == nil { 270 | t.Error("root match failed") 271 | } 272 | } 273 | 274 | type maxRec struct { 275 | max int 276 | sync.RWMutex 277 | } 278 | 279 | var M = new(maxRec) 280 | 281 | func HelloServerLargeResponse(resp ResponseWriter, req *Msg) { 282 | m := new(Msg) 283 | m.SetReply(req) 284 | m.Authoritative = true 285 | m1 := 0 286 | M.RLock() 287 | m1 = M.max 288 | M.RUnlock() 289 | for i := 0; i < m1; i++ { 290 | aRec := &A{ 291 | Hdr: RR_Header{ 292 | Name: req.Question[0].Name, 293 | Rrtype: TypeA, 294 | Class: ClassINET, 295 | Ttl: 0, 296 | }, 297 | A: net.ParseIP(fmt.Sprintf("127.0.0.%d", i+1)).To4(), 298 | } 299 | m.Answer = append(m.Answer, aRec) 300 | } 301 | resp.WriteMsg(m) 302 | } 303 | 304 | func TestServingLargeResponses(t *testing.T) { 305 | HandleFunc("example.", HelloServerLargeResponse) 306 | defer HandleRemove("example.") 307 | 308 | s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") 309 | if err != nil { 310 | t.Fatalf("Unable to run test server: %v", err) 311 | } 312 | defer s.Shutdown() 313 | 314 | // Create request 315 | m := new(Msg) 316 | m.SetQuestion("web.service.example.", TypeANY) 317 | 318 | c := new(Client) 319 | c.Net = "udp" 320 | M.Lock() 321 | M.max = 2 322 | M.Unlock() 323 | _, _, err = c.Exchange(m, addrstr) 324 | if err != nil { 325 | t.Errorf("failed to exchange: %v", err) 326 | } 327 | // This must fail 328 | M.Lock() 329 | M.max = 20 330 | M.Unlock() 331 | _, _, err = c.Exchange(m, addrstr) 332 | if err == nil { 333 | t.Error("failed to fail exchange, this should generate packet error") 334 | } 335 | // But this must work again 336 | c.UDPSize = 7000 337 | _, _, err = c.Exchange(m, addrstr) 338 | if err != nil { 339 | t.Errorf("failed to exchange: %v", err) 340 | } 341 | } 342 | 343 | func TestServingResponse(t *testing.T) { 344 | if testing.Short() { 345 | t.Skip("skipping test in short mode.") 346 | } 347 | HandleFunc("miek.nl.", HelloServer) 348 | s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") 349 | if err != nil { 350 | t.Fatalf("Unable to run test server: %v", err) 351 | } 352 | 353 | c := new(Client) 354 | m := new(Msg) 355 | m.SetQuestion("miek.nl.", TypeTXT) 356 | m.Response = false 357 | _, _, err = c.Exchange(m, addrstr) 358 | if err != nil { 359 | t.Fatal("failed to exchange", err) 360 | } 361 | m.Response = true 362 | _, _, err = c.Exchange(m, addrstr) 363 | if err == nil { 364 | t.Fatal("exchanged response message") 365 | } 366 | 367 | s.Shutdown() 368 | s, addrstr, err = RunLocalUDPServerUnsafe("127.0.0.1:0") 369 | if err != nil { 370 | t.Fatalf("Unable to run test server: %v", err) 371 | } 372 | defer s.Shutdown() 373 | 374 | m.Response = true 375 | _, _, err = c.Exchange(m, addrstr) 376 | if err != nil { 377 | t.Fatal("could exchanged response message in Unsafe mode") 378 | } 379 | } 380 | 381 | func TestShutdownTCP(t *testing.T) { 382 | s, _, err := RunLocalTCPServer("127.0.0.1:0") 383 | if err != nil { 384 | t.Fatalf("Unable to run test server: %v", err) 385 | } 386 | err = s.Shutdown() 387 | if err != nil { 388 | t.Errorf("Could not shutdown test TCP server, %v", err) 389 | } 390 | } 391 | 392 | func TestShutdownUDP(t *testing.T) { 393 | s, _, err := RunLocalUDPServer("127.0.0.1:0") 394 | if err != nil { 395 | t.Fatalf("Unable to run test server: %v", err) 396 | } 397 | err = s.Shutdown() 398 | if err != nil { 399 | t.Errorf("Could not shutdown test UDP server, %v", err) 400 | } 401 | } 402 | 403 | type ExampleFrameLengthWriter struct { 404 | Writer 405 | } 406 | 407 | func (e *ExampleFrameLengthWriter) Write(m []byte) (int, error) { 408 | fmt.Println("writing raw DNS message of length", len(m)) 409 | return e.Writer.Write(m) 410 | } 411 | 412 | func ExampleDecorateWriter() { 413 | // instrument raw DNS message writing 414 | wf := DecorateWriter(func(w Writer) Writer { 415 | return &ExampleFrameLengthWriter{w} 416 | }) 417 | 418 | // simple UDP server 419 | pc, err := net.ListenPacket("udp", "127.0.0.1:0") 420 | if err != nil { 421 | fmt.Println(err.Error()) 422 | return 423 | } 424 | server := &Server{ 425 | PacketConn: pc, 426 | DecorateWriter: wf, 427 | ReadTimeout: time.Hour, WriteTimeout: time.Hour, 428 | } 429 | 430 | waitLock := sync.Mutex{} 431 | waitLock.Lock() 432 | server.NotifyStartedFunc = waitLock.Unlock 433 | defer server.Shutdown() 434 | 435 | go func() { 436 | server.ActivateAndServe() 437 | pc.Close() 438 | }() 439 | 440 | waitLock.Lock() 441 | 442 | HandleFunc("miek.nl.", HelloServer) 443 | 444 | c := new(Client) 445 | m := new(Msg) 446 | m.SetQuestion("miek.nl.", TypeTXT) 447 | _, _, err = c.Exchange(m, pc.LocalAddr().String()) 448 | if err != nil { 449 | fmt.Println("failed to exchange", err.Error()) 450 | return 451 | } 452 | // Output: writing raw DNS message of length 56 453 | } 454 | -------------------------------------------------------------------------------- /sig0.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "crypto" 5 | "crypto/dsa" 6 | "crypto/ecdsa" 7 | "crypto/rsa" 8 | "math/big" 9 | "strings" 10 | "time" 11 | ) 12 | 13 | // Sign signs a dns.Msg. It fills the signature with the appropriate data. 14 | // The SIG record should have the SignerName, KeyTag, Algorithm, Inception 15 | // and Expiration set. 16 | func (rr *SIG) Sign(k crypto.Signer, m *Msg) ([]byte, error) { 17 | if k == nil { 18 | return nil, ErrPrivKey 19 | } 20 | if rr.KeyTag == 0 || len(rr.SignerName) == 0 || rr.Algorithm == 0 { 21 | return nil, ErrKey 22 | } 23 | rr.Header().Rrtype = TypeSIG 24 | rr.Header().Class = ClassANY 25 | rr.Header().Ttl = 0 26 | rr.Header().Name = "." 27 | rr.OrigTtl = 0 28 | rr.TypeCovered = 0 29 | rr.Labels = 0 30 | 31 | buf := make([]byte, m.Len()+rr.len()) 32 | mbuf, err := m.PackBuffer(buf) 33 | if err != nil { 34 | return nil, err 35 | } 36 | if &buf[0] != &mbuf[0] { 37 | return nil, ErrBuf 38 | } 39 | off, err := PackRR(rr, buf, len(mbuf), nil, false) 40 | if err != nil { 41 | return nil, err 42 | } 43 | buf = buf[:off:cap(buf)] 44 | 45 | hash, ok := AlgorithmToHash[rr.Algorithm] 46 | if !ok { 47 | return nil, ErrAlg 48 | } 49 | 50 | hasher := hash.New() 51 | // Write SIG rdata 52 | hasher.Write(buf[len(mbuf)+1+2+2+4+2:]) 53 | // Write message 54 | hasher.Write(buf[:len(mbuf)]) 55 | 56 | signature, err := sign(k, hasher.Sum(nil), hash, rr.Algorithm) 57 | if err != nil { 58 | return nil, err 59 | } 60 | 61 | rr.Signature = toBase64(signature) 62 | sig := string(signature) 63 | 64 | buf = append(buf, sig...) 65 | if len(buf) > int(^uint16(0)) { 66 | return nil, ErrBuf 67 | } 68 | // Adjust sig data length 69 | rdoff := len(mbuf) + 1 + 2 + 2 + 4 70 | rdlen, _ := unpackUint16(buf, rdoff) 71 | rdlen += uint16(len(sig)) 72 | buf[rdoff], buf[rdoff+1] = packUint16(rdlen) 73 | // Adjust additional count 74 | adc, _ := unpackUint16(buf, 10) 75 | adc++ 76 | buf[10], buf[11] = packUint16(adc) 77 | return buf, nil 78 | } 79 | 80 | // Verify validates the message buf using the key k. 81 | // It's assumed that buf is a valid message from which rr was unpacked. 82 | func (rr *SIG) Verify(k *KEY, buf []byte) error { 83 | if k == nil { 84 | return ErrKey 85 | } 86 | if rr.KeyTag == 0 || len(rr.SignerName) == 0 || rr.Algorithm == 0 { 87 | return ErrKey 88 | } 89 | 90 | var hash crypto.Hash 91 | switch rr.Algorithm { 92 | case DSA, RSASHA1: 93 | hash = crypto.SHA1 94 | case RSASHA256, ECDSAP256SHA256: 95 | hash = crypto.SHA256 96 | case ECDSAP384SHA384: 97 | hash = crypto.SHA384 98 | case RSASHA512: 99 | hash = crypto.SHA512 100 | default: 101 | return ErrAlg 102 | } 103 | hasher := hash.New() 104 | 105 | buflen := len(buf) 106 | qdc, _ := unpackUint16(buf, 4) 107 | anc, _ := unpackUint16(buf, 6) 108 | auc, _ := unpackUint16(buf, 8) 109 | adc, offset := unpackUint16(buf, 10) 110 | var err error 111 | for i := uint16(0); i < qdc && offset < buflen; i++ { 112 | _, offset, err = UnpackDomainName(buf, offset) 113 | if err != nil { 114 | return err 115 | } 116 | // Skip past Type and Class 117 | offset += 2 + 2 118 | } 119 | for i := uint16(1); i < anc+auc+adc && offset < buflen; i++ { 120 | _, offset, err = UnpackDomainName(buf, offset) 121 | if err != nil { 122 | return err 123 | } 124 | // Skip past Type, Class and TTL 125 | offset += 2 + 2 + 4 126 | if offset+1 >= buflen { 127 | continue 128 | } 129 | var rdlen uint16 130 | rdlen, offset = unpackUint16(buf, offset) 131 | offset += int(rdlen) 132 | } 133 | if offset >= buflen { 134 | return &Error{err: "overflowing unpacking signed message"} 135 | } 136 | 137 | // offset should be just prior to SIG 138 | bodyend := offset 139 | // owner name SHOULD be root 140 | _, offset, err = UnpackDomainName(buf, offset) 141 | if err != nil { 142 | return err 143 | } 144 | // Skip Type, Class, TTL, RDLen 145 | offset += 2 + 2 + 4 + 2 146 | sigstart := offset 147 | // Skip Type Covered, Algorithm, Labels, Original TTL 148 | offset += 2 + 1 + 1 + 4 149 | if offset+4+4 >= buflen { 150 | return &Error{err: "overflow unpacking signed message"} 151 | } 152 | expire := uint32(buf[offset])<<24 | uint32(buf[offset+1])<<16 | uint32(buf[offset+2])<<8 | uint32(buf[offset+3]) 153 | offset += 4 154 | incept := uint32(buf[offset])<<24 | uint32(buf[offset+1])<<16 | uint32(buf[offset+2])<<8 | uint32(buf[offset+3]) 155 | offset += 4 156 | now := uint32(time.Now().Unix()) 157 | if now < incept || now > expire { 158 | return ErrTime 159 | } 160 | // Skip key tag 161 | offset += 2 162 | var signername string 163 | signername, offset, err = UnpackDomainName(buf, offset) 164 | if err != nil { 165 | return err 166 | } 167 | // If key has come from the DNS name compression might 168 | // have mangled the case of the name 169 | if strings.ToLower(signername) != strings.ToLower(k.Header().Name) { 170 | return &Error{err: "signer name doesn't match key name"} 171 | } 172 | sigend := offset 173 | hasher.Write(buf[sigstart:sigend]) 174 | hasher.Write(buf[:10]) 175 | hasher.Write([]byte{ 176 | byte((adc - 1) << 8), 177 | byte(adc - 1), 178 | }) 179 | hasher.Write(buf[12:bodyend]) 180 | 181 | hashed := hasher.Sum(nil) 182 | sig := buf[sigend:] 183 | switch k.Algorithm { 184 | case DSA: 185 | pk := k.publicKeyDSA() 186 | sig = sig[1:] 187 | r := big.NewInt(0) 188 | r.SetBytes(sig[:len(sig)/2]) 189 | s := big.NewInt(0) 190 | s.SetBytes(sig[len(sig)/2:]) 191 | if pk != nil { 192 | if dsa.Verify(pk, hashed, r, s) { 193 | return nil 194 | } 195 | return ErrSig 196 | } 197 | case RSASHA1, RSASHA256, RSASHA512: 198 | pk := k.publicKeyRSA() 199 | if pk != nil { 200 | return rsa.VerifyPKCS1v15(pk, hash, hashed, sig) 201 | } 202 | case ECDSAP256SHA256, ECDSAP384SHA384: 203 | pk := k.publicKeyECDSA() 204 | r := big.NewInt(0) 205 | r.SetBytes(sig[:len(sig)/2]) 206 | s := big.NewInt(0) 207 | s.SetBytes(sig[len(sig)/2:]) 208 | if pk != nil { 209 | if ecdsa.Verify(pk, hashed, r, s) { 210 | return nil 211 | } 212 | return ErrSig 213 | } 214 | } 215 | return ErrKeyAlg 216 | } 217 | -------------------------------------------------------------------------------- /sig0_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "crypto" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestSIG0(t *testing.T) { 10 | if testing.Short() { 11 | t.Skip("skipping test in short mode.") 12 | } 13 | m := new(Msg) 14 | m.SetQuestion("example.org.", TypeSOA) 15 | for _, alg := range []uint8{ECDSAP256SHA256, ECDSAP384SHA384, RSASHA1, RSASHA256, RSASHA512} { 16 | algstr := AlgorithmToString[alg] 17 | keyrr := new(KEY) 18 | keyrr.Hdr.Name = algstr + "." 19 | keyrr.Hdr.Rrtype = TypeKEY 20 | keyrr.Hdr.Class = ClassINET 21 | keyrr.Algorithm = alg 22 | keysize := 1024 23 | switch alg { 24 | case ECDSAP256SHA256: 25 | keysize = 256 26 | case ECDSAP384SHA384: 27 | keysize = 384 28 | } 29 | pk, err := keyrr.Generate(keysize) 30 | if err != nil { 31 | t.Errorf("Failed to generate key for “%s”: %v", algstr, err) 32 | continue 33 | } 34 | now := uint32(time.Now().Unix()) 35 | sigrr := new(SIG) 36 | sigrr.Hdr.Name = "." 37 | sigrr.Hdr.Rrtype = TypeSIG 38 | sigrr.Hdr.Class = ClassANY 39 | sigrr.Algorithm = alg 40 | sigrr.Expiration = now + 300 41 | sigrr.Inception = now - 300 42 | sigrr.KeyTag = keyrr.KeyTag() 43 | sigrr.SignerName = keyrr.Hdr.Name 44 | mb, err := sigrr.Sign(pk.(crypto.Signer), m) 45 | if err != nil { 46 | t.Errorf("Failed to sign message using “%s”: %v", algstr, err) 47 | continue 48 | } 49 | m := new(Msg) 50 | if err := m.Unpack(mb); err != nil { 51 | t.Errorf("Failed to unpack message signed using “%s”: %v", algstr, err) 52 | continue 53 | } 54 | if len(m.Extra) != 1 { 55 | t.Errorf("Missing SIG for message signed using “%s”", algstr) 56 | continue 57 | } 58 | var sigrrwire *SIG 59 | switch rr := m.Extra[0].(type) { 60 | case *SIG: 61 | sigrrwire = rr 62 | default: 63 | t.Errorf("Expected SIG RR, instead: %v", rr) 64 | continue 65 | } 66 | for _, rr := range []*SIG{sigrr, sigrrwire} { 67 | id := "sigrr" 68 | if rr == sigrrwire { 69 | id = "sigrrwire" 70 | } 71 | if err := rr.Verify(keyrr, mb); err != nil { 72 | t.Errorf("Failed to verify “%s” signed SIG(%s): %v", algstr, id, err) 73 | continue 74 | } 75 | } 76 | mb[13]++ 77 | if err := sigrr.Verify(keyrr, mb); err == nil { 78 | t.Errorf("Verify succeeded on an altered message using “%s”", algstr) 79 | continue 80 | } 81 | sigrr.Expiration = 2 82 | sigrr.Inception = 1 83 | mb, _ = sigrr.Sign(pk.(crypto.Signer), m) 84 | if err := sigrr.Verify(keyrr, mb); err == nil { 85 | t.Errorf("Verify succeeded on an expired message using “%s”", algstr) 86 | continue 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /singleinflight.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Adapted for dns package usage by Miek Gieben. 6 | 7 | package dns 8 | 9 | import "sync" 10 | import "time" 11 | 12 | // call is an in-flight or completed singleflight.Do call 13 | type call struct { 14 | wg sync.WaitGroup 15 | val *Msg 16 | rtt time.Duration 17 | err error 18 | dups int 19 | } 20 | 21 | // singleflight represents a class of work and forms a namespace in 22 | // which units of work can be executed with duplicate suppression. 23 | type singleflight struct { 24 | sync.Mutex // protects m 25 | m map[string]*call // lazily initialized 26 | } 27 | 28 | // Do executes and returns the results of the given function, making 29 | // sure that only one execution is in-flight for a given key at a 30 | // time. If a duplicate comes in, the duplicate caller waits for the 31 | // original to complete and receives the same results. 32 | // The return value shared indicates whether v was given to multiple callers. 33 | func (g *singleflight) Do(key string, fn func() (*Msg, time.Duration, error)) (v *Msg, rtt time.Duration, err error, shared bool) { 34 | g.Lock() 35 | if g.m == nil { 36 | g.m = make(map[string]*call) 37 | } 38 | if c, ok := g.m[key]; ok { 39 | c.dups++ 40 | g.Unlock() 41 | c.wg.Wait() 42 | return c.val, c.rtt, c.err, true 43 | } 44 | c := new(call) 45 | c.wg.Add(1) 46 | g.m[key] = c 47 | g.Unlock() 48 | 49 | c.val, c.rtt, c.err = fn() 50 | c.wg.Done() 51 | 52 | g.Lock() 53 | delete(g.m, key) 54 | g.Unlock() 55 | 56 | return c.val, c.rtt, c.err, c.dups > 0 57 | } 58 | -------------------------------------------------------------------------------- /tlsa.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "crypto/sha256" 5 | "crypto/sha512" 6 | "crypto/x509" 7 | "encoding/hex" 8 | "errors" 9 | "io" 10 | "net" 11 | "strconv" 12 | ) 13 | 14 | // CertificateToDANE converts a certificate to a hex string as used in the TLSA record. 15 | func CertificateToDANE(selector, matchingType uint8, cert *x509.Certificate) (string, error) { 16 | switch matchingType { 17 | case 0: 18 | switch selector { 19 | case 0: 20 | return hex.EncodeToString(cert.Raw), nil 21 | case 1: 22 | return hex.EncodeToString(cert.RawSubjectPublicKeyInfo), nil 23 | } 24 | case 1: 25 | h := sha256.New() 26 | switch selector { 27 | case 0: 28 | io.WriteString(h, string(cert.Raw)) 29 | return hex.EncodeToString(h.Sum(nil)), nil 30 | case 1: 31 | io.WriteString(h, string(cert.RawSubjectPublicKeyInfo)) 32 | return hex.EncodeToString(h.Sum(nil)), nil 33 | } 34 | case 2: 35 | h := sha512.New() 36 | switch selector { 37 | case 0: 38 | io.WriteString(h, string(cert.Raw)) 39 | return hex.EncodeToString(h.Sum(nil)), nil 40 | case 1: 41 | io.WriteString(h, string(cert.RawSubjectPublicKeyInfo)) 42 | return hex.EncodeToString(h.Sum(nil)), nil 43 | } 44 | } 45 | return "", errors.New("dns: bad TLSA MatchingType or TLSA Selector") 46 | } 47 | 48 | // Sign creates a TLSA record from an SSL certificate. 49 | func (r *TLSA) Sign(usage, selector, matchingType int, cert *x509.Certificate) (err error) { 50 | r.Hdr.Rrtype = TypeTLSA 51 | r.Usage = uint8(usage) 52 | r.Selector = uint8(selector) 53 | r.MatchingType = uint8(matchingType) 54 | 55 | r.Certificate, err = CertificateToDANE(r.Selector, r.MatchingType, cert) 56 | if err != nil { 57 | return err 58 | } 59 | return nil 60 | } 61 | 62 | // Verify verifies a TLSA record against an SSL certificate. If it is OK 63 | // a nil error is returned. 64 | func (r *TLSA) Verify(cert *x509.Certificate) error { 65 | c, err := CertificateToDANE(r.Selector, r.MatchingType, cert) 66 | if err != nil { 67 | return err // Not also ErrSig? 68 | } 69 | if r.Certificate == c { 70 | return nil 71 | } 72 | return ErrSig // ErrSig, really? 73 | } 74 | 75 | // TLSAName returns the ownername of a TLSA resource record as per the 76 | // rules specified in RFC 6698, Section 3. 77 | func TLSAName(name, service, network string) (string, error) { 78 | if !IsFqdn(name) { 79 | return "", ErrFqdn 80 | } 81 | p, e := net.LookupPort(network, service) 82 | if e != nil { 83 | return "", e 84 | } 85 | return "_" + strconv.Itoa(p) + "_" + network + "." + name, nil 86 | } 87 | -------------------------------------------------------------------------------- /tsig.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/md5" 6 | "crypto/sha1" 7 | "crypto/sha256" 8 | "crypto/sha512" 9 | "encoding/hex" 10 | "hash" 11 | "io" 12 | "strconv" 13 | "strings" 14 | "time" 15 | ) 16 | 17 | // HMAC hashing codes. These are transmitted as domain names. 18 | const ( 19 | HmacMD5 = "hmac-md5.sig-alg.reg.int." 20 | HmacSHA1 = "hmac-sha1." 21 | HmacSHA256 = "hmac-sha256." 22 | HmacSHA512 = "hmac-sha512." 23 | ) 24 | 25 | // TSIG is the RR the holds the transaction signature of a message. 26 | // See RFC 2845 and RFC 4635. 27 | type TSIG struct { 28 | Hdr RR_Header 29 | Algorithm string `dns:"domain-name"` 30 | TimeSigned uint64 `dns:"uint48"` 31 | Fudge uint16 32 | MACSize uint16 33 | MAC string `dns:"size-hex"` 34 | OrigId uint16 35 | Error uint16 36 | OtherLen uint16 37 | OtherData string `dns:"size-hex"` 38 | } 39 | 40 | func (rr *TSIG) Header() *RR_Header { 41 | return &rr.Hdr 42 | } 43 | 44 | // TSIG has no official presentation format, but this will suffice. 45 | 46 | func (rr *TSIG) String() string { 47 | s := "\n;; TSIG PSEUDOSECTION:\n" 48 | s += rr.Hdr.String() + 49 | " " + rr.Algorithm + 50 | " " + tsigTimeToString(rr.TimeSigned) + 51 | " " + strconv.Itoa(int(rr.Fudge)) + 52 | " " + strconv.Itoa(int(rr.MACSize)) + 53 | " " + strings.ToUpper(rr.MAC) + 54 | " " + strconv.Itoa(int(rr.OrigId)) + 55 | " " + strconv.Itoa(int(rr.Error)) + // BIND prints NOERROR 56 | " " + strconv.Itoa(int(rr.OtherLen)) + 57 | " " + rr.OtherData 58 | return s 59 | } 60 | 61 | func (rr *TSIG) len() int { 62 | return rr.Hdr.len() + len(rr.Algorithm) + 1 + 6 + 63 | 4 + len(rr.MAC)/2 + 1 + 6 + len(rr.OtherData)/2 + 1 64 | } 65 | 66 | func (rr *TSIG) copy() RR { 67 | return &TSIG{*rr.Hdr.copyHeader(), rr.Algorithm, rr.TimeSigned, rr.Fudge, rr.MACSize, rr.MAC, rr.OrigId, rr.Error, rr.OtherLen, rr.OtherData} 68 | } 69 | 70 | // The following values must be put in wireformat, so that the MAC can be calculated. 71 | // RFC 2845, section 3.4.2. TSIG Variables. 72 | type tsigWireFmt struct { 73 | // From RR_Header 74 | Name string `dns:"domain-name"` 75 | Class uint16 76 | Ttl uint32 77 | // Rdata of the TSIG 78 | Algorithm string `dns:"domain-name"` 79 | TimeSigned uint64 `dns:"uint48"` 80 | Fudge uint16 81 | // MACSize, MAC and OrigId excluded 82 | Error uint16 83 | OtherLen uint16 84 | OtherData string `dns:"size-hex"` 85 | } 86 | 87 | // If we have the MAC use this type to convert it to wiredata. 88 | // Section 3.4.3. Request MAC 89 | type macWireFmt struct { 90 | MACSize uint16 91 | MAC string `dns:"size-hex"` 92 | } 93 | 94 | // 3.3. Time values used in TSIG calculations 95 | type timerWireFmt struct { 96 | TimeSigned uint64 `dns:"uint48"` 97 | Fudge uint16 98 | } 99 | 100 | // TsigGenerate fills out the TSIG record attached to the message. 101 | // The message should contain 102 | // a "stub" TSIG RR with the algorithm, key name (owner name of the RR), 103 | // time fudge (defaults to 300 seconds) and the current time 104 | // The TSIG MAC is saved in that Tsig RR. 105 | // When TsigGenerate is called for the first time requestMAC is set to the empty string and 106 | // timersOnly is false. 107 | // If something goes wrong an error is returned, otherwise it is nil. 108 | func TsigGenerate(m *Msg, secret, requestMAC string, timersOnly bool) ([]byte, string, error) { 109 | if m.IsTsig() == nil { 110 | panic("dns: TSIG not last RR in additional") 111 | } 112 | // If we barf here, the caller is to blame 113 | rawsecret, err := fromBase64([]byte(secret)) 114 | if err != nil { 115 | return nil, "", err 116 | } 117 | 118 | rr := m.Extra[len(m.Extra)-1].(*TSIG) 119 | m.Extra = m.Extra[0 : len(m.Extra)-1] // kill the TSIG from the msg 120 | mbuf, err := m.Pack() 121 | if err != nil { 122 | return nil, "", err 123 | } 124 | buf := tsigBuffer(mbuf, rr, requestMAC, timersOnly) 125 | 126 | t := new(TSIG) 127 | var h hash.Hash 128 | switch rr.Algorithm { 129 | case HmacMD5: 130 | h = hmac.New(md5.New, []byte(rawsecret)) 131 | case HmacSHA1: 132 | h = hmac.New(sha1.New, []byte(rawsecret)) 133 | case HmacSHA256: 134 | h = hmac.New(sha256.New, []byte(rawsecret)) 135 | case HmacSHA512: 136 | h = hmac.New(sha512.New, []byte(rawsecret)) 137 | default: 138 | return nil, "", ErrKeyAlg 139 | } 140 | io.WriteString(h, string(buf)) 141 | t.MAC = hex.EncodeToString(h.Sum(nil)) 142 | t.MACSize = uint16(len(t.MAC) / 2) // Size is half! 143 | 144 | t.Hdr = RR_Header{Name: rr.Hdr.Name, Rrtype: TypeTSIG, Class: ClassANY, Ttl: 0} 145 | t.Fudge = rr.Fudge 146 | t.TimeSigned = rr.TimeSigned 147 | t.Algorithm = rr.Algorithm 148 | t.OrigId = m.Id 149 | 150 | tbuf := make([]byte, t.len()) 151 | if off, err := PackRR(t, tbuf, 0, nil, false); err == nil { 152 | tbuf = tbuf[:off] // reset to actual size used 153 | } else { 154 | return nil, "", err 155 | } 156 | mbuf = append(mbuf, tbuf...) 157 | rawSetExtraLen(mbuf, uint16(len(m.Extra)+1)) 158 | return mbuf, t.MAC, nil 159 | } 160 | 161 | // TsigVerify verifies the TSIG on a message. 162 | // If the signature does not validate err contains the 163 | // error, otherwise it is nil. 164 | func TsigVerify(msg []byte, secret, requestMAC string, timersOnly bool) error { 165 | rawsecret, err := fromBase64([]byte(secret)) 166 | if err != nil { 167 | return err 168 | } 169 | // Strip the TSIG from the incoming msg 170 | stripped, tsig, err := stripTsig(msg) 171 | if err != nil { 172 | return err 173 | } 174 | 175 | msgMAC, err := hex.DecodeString(tsig.MAC) 176 | if err != nil { 177 | return err 178 | } 179 | 180 | buf := tsigBuffer(stripped, tsig, requestMAC, timersOnly) 181 | 182 | // Fudge factor works both ways. A message can arrive before it was signed because 183 | // of clock skew. 184 | now := uint64(time.Now().Unix()) 185 | ti := now - tsig.TimeSigned 186 | if now < tsig.TimeSigned { 187 | ti = tsig.TimeSigned - now 188 | } 189 | if uint64(tsig.Fudge) < ti { 190 | return ErrTime 191 | } 192 | 193 | var h hash.Hash 194 | switch tsig.Algorithm { 195 | case HmacMD5: 196 | h = hmac.New(md5.New, rawsecret) 197 | case HmacSHA1: 198 | h = hmac.New(sha1.New, rawsecret) 199 | case HmacSHA256: 200 | h = hmac.New(sha256.New, rawsecret) 201 | case HmacSHA512: 202 | h = hmac.New(sha512.New, rawsecret) 203 | default: 204 | return ErrKeyAlg 205 | } 206 | h.Write(buf) 207 | if !hmac.Equal(h.Sum(nil), msgMAC) { 208 | return ErrSig 209 | } 210 | return nil 211 | } 212 | 213 | // Create a wiredata buffer for the MAC calculation. 214 | func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) []byte { 215 | var buf []byte 216 | if rr.TimeSigned == 0 { 217 | rr.TimeSigned = uint64(time.Now().Unix()) 218 | } 219 | if rr.Fudge == 0 { 220 | rr.Fudge = 300 // Standard (RFC) default. 221 | } 222 | 223 | if requestMAC != "" { 224 | m := new(macWireFmt) 225 | m.MACSize = uint16(len(requestMAC) / 2) 226 | m.MAC = requestMAC 227 | buf = make([]byte, len(requestMAC)) // long enough 228 | n, _ := PackStruct(m, buf, 0) 229 | buf = buf[:n] 230 | } 231 | 232 | tsigvar := make([]byte, DefaultMsgSize) 233 | if timersOnly { 234 | tsig := new(timerWireFmt) 235 | tsig.TimeSigned = rr.TimeSigned 236 | tsig.Fudge = rr.Fudge 237 | n, _ := PackStruct(tsig, tsigvar, 0) 238 | tsigvar = tsigvar[:n] 239 | } else { 240 | tsig := new(tsigWireFmt) 241 | tsig.Name = strings.ToLower(rr.Hdr.Name) 242 | tsig.Class = ClassANY 243 | tsig.Ttl = rr.Hdr.Ttl 244 | tsig.Algorithm = strings.ToLower(rr.Algorithm) 245 | tsig.TimeSigned = rr.TimeSigned 246 | tsig.Fudge = rr.Fudge 247 | tsig.Error = rr.Error 248 | tsig.OtherLen = rr.OtherLen 249 | tsig.OtherData = rr.OtherData 250 | n, _ := PackStruct(tsig, tsigvar, 0) 251 | tsigvar = tsigvar[:n] 252 | } 253 | 254 | if requestMAC != "" { 255 | x := append(buf, msgbuf...) 256 | buf = append(x, tsigvar...) 257 | } else { 258 | buf = append(msgbuf, tsigvar...) 259 | } 260 | return buf 261 | } 262 | 263 | // Strip the TSIG from the raw message. 264 | func stripTsig(msg []byte) ([]byte, *TSIG, error) { 265 | // Copied from msg.go's Unpack() 266 | // Header. 267 | var dh Header 268 | var err error 269 | dns := new(Msg) 270 | rr := new(TSIG) 271 | off := 0 272 | tsigoff := 0 273 | if off, err = UnpackStruct(&dh, msg, off); err != nil { 274 | return nil, nil, err 275 | } 276 | if dh.Arcount == 0 { 277 | return nil, nil, ErrNoSig 278 | } 279 | // Rcode, see msg.go Unpack() 280 | if int(dh.Bits&0xF) == RcodeNotAuth { 281 | return nil, nil, ErrAuth 282 | } 283 | 284 | // Arrays. 285 | dns.Question = make([]Question, dh.Qdcount) 286 | dns.Answer = make([]RR, dh.Ancount) 287 | dns.Ns = make([]RR, dh.Nscount) 288 | dns.Extra = make([]RR, dh.Arcount) 289 | 290 | for i := 0; i < len(dns.Question); i++ { 291 | off, err = UnpackStruct(&dns.Question[i], msg, off) 292 | if err != nil { 293 | return nil, nil, err 294 | } 295 | } 296 | for i := 0; i < len(dns.Answer); i++ { 297 | dns.Answer[i], off, err = UnpackRR(msg, off) 298 | if err != nil { 299 | return nil, nil, err 300 | } 301 | } 302 | for i := 0; i < len(dns.Ns); i++ { 303 | dns.Ns[i], off, err = UnpackRR(msg, off) 304 | if err != nil { 305 | return nil, nil, err 306 | } 307 | } 308 | for i := 0; i < len(dns.Extra); i++ { 309 | tsigoff = off 310 | dns.Extra[i], off, err = UnpackRR(msg, off) 311 | if err != nil { 312 | return nil, nil, err 313 | } 314 | if dns.Extra[i].Header().Rrtype == TypeTSIG { 315 | rr = dns.Extra[i].(*TSIG) 316 | // Adjust Arcount. 317 | arcount, _ := unpackUint16(msg, 10) 318 | msg[10], msg[11] = packUint16(arcount - 1) 319 | break 320 | } 321 | } 322 | if rr == nil { 323 | return nil, nil, ErrNoSig 324 | } 325 | return msg[:tsigoff], rr, nil 326 | } 327 | 328 | // Translate the TSIG time signed into a date. There is no 329 | // need for RFC1982 calculations as this date is 48 bits. 330 | func tsigTimeToString(t uint64) string { 331 | ti := time.Unix(int64(t), 0).UTC() 332 | return ti.Format("20060102150405") 333 | } 334 | -------------------------------------------------------------------------------- /types_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestCmToM(t *testing.T) { 8 | s := cmToM(0, 0) 9 | if s != "0.00" { 10 | t.Error("0, 0") 11 | } 12 | 13 | s = cmToM(1, 0) 14 | if s != "0.01" { 15 | t.Error("1, 0") 16 | } 17 | 18 | s = cmToM(3, 1) 19 | if s != "0.30" { 20 | t.Error("3, 1") 21 | } 22 | 23 | s = cmToM(4, 2) 24 | if s != "4" { 25 | t.Error("4, 2") 26 | } 27 | 28 | s = cmToM(5, 3) 29 | if s != "50" { 30 | t.Error("5, 3") 31 | } 32 | 33 | s = cmToM(7, 5) 34 | if s != "7000" { 35 | t.Error("7, 5") 36 | } 37 | 38 | s = cmToM(9, 9) 39 | if s != "90000000" { 40 | t.Error("9, 9") 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /udp.go: -------------------------------------------------------------------------------- 1 | // +build !windows 2 | 3 | package dns 4 | 5 | import ( 6 | "net" 7 | "syscall" 8 | ) 9 | 10 | // SessionUDP holds the remote address and the associated 11 | // out-of-band data. 12 | type SessionUDP struct { 13 | raddr *net.UDPAddr 14 | context []byte 15 | } 16 | 17 | // RemoteAddr returns the remote network address. 18 | func (s *SessionUDP) RemoteAddr() net.Addr { return s.raddr } 19 | 20 | // setUDPSocketOptions sets the UDP socket options. 21 | // This function is implemented on a per platform basis. See udp_*.go for more details 22 | func setUDPSocketOptions(conn *net.UDPConn) error { 23 | sa, err := getUDPSocketName(conn) 24 | if err != nil { 25 | return err 26 | } 27 | switch sa.(type) { 28 | case *syscall.SockaddrInet6: 29 | v6only, err := getUDPSocketOptions6Only(conn) 30 | if err != nil { 31 | return err 32 | } 33 | setUDPSocketOptions6(conn) 34 | if !v6only { 35 | setUDPSocketOptions4(conn) 36 | } 37 | case *syscall.SockaddrInet4: 38 | setUDPSocketOptions4(conn) 39 | } 40 | return nil 41 | } 42 | 43 | // ReadFromSessionUDP acts just like net.UDPConn.ReadFrom(), but returns a session object instead of a 44 | // net.UDPAddr. 45 | func ReadFromSessionUDP(conn *net.UDPConn, b []byte) (int, *SessionUDP, error) { 46 | oob := make([]byte, 40) 47 | n, oobn, _, raddr, err := conn.ReadMsgUDP(b, oob) 48 | if err != nil { 49 | return n, nil, err 50 | } 51 | return n, &SessionUDP{raddr, oob[:oobn]}, err 52 | } 53 | 54 | // WriteToSessionUDP acts just like net.UDPConn.WritetTo(), but uses a *SessionUDP instead of a net.Addr. 55 | func WriteToSessionUDP(conn *net.UDPConn, b []byte, session *SessionUDP) (int, error) { 56 | n, _, err := conn.WriteMsgUDP(b, session.context, session.raddr) 57 | return n, err 58 | } 59 | -------------------------------------------------------------------------------- /udp_linux.go: -------------------------------------------------------------------------------- 1 | // +build linux 2 | 3 | package dns 4 | 5 | // See: 6 | // * http://stackoverflow.com/questions/3062205/setting-the-source-ip-for-a-udp-socket and 7 | // * http://blog.powerdns.com/2012/10/08/on-binding-datagram-udp-sockets-to-the-any-addresses/ 8 | // 9 | // Why do we need this: When listening on 0.0.0.0 with UDP so kernel decides what is the outgoing 10 | // interface, this might not always be the correct one. This code will make sure the egress 11 | // packet's interface matched the ingress' one. 12 | 13 | import ( 14 | "net" 15 | "syscall" 16 | ) 17 | 18 | // setUDPSocketOptions4 prepares the v4 socket for sessions. 19 | func setUDPSocketOptions4(conn *net.UDPConn) error { 20 | file, err := conn.File() 21 | if err != nil { 22 | return err 23 | } 24 | if err := syscall.SetsockoptInt(int(file.Fd()), syscall.IPPROTO_IP, syscall.IP_PKTINFO, 1); err != nil { 25 | return err 26 | } 27 | return nil 28 | } 29 | 30 | // setUDPSocketOptions6 prepares the v6 socket for sessions. 31 | func setUDPSocketOptions6(conn *net.UDPConn) error { 32 | file, err := conn.File() 33 | if err != nil { 34 | return err 35 | } 36 | if err := syscall.SetsockoptInt(int(file.Fd()), syscall.IPPROTO_IPV6, syscall.IPV6_RECVPKTINFO, 1); err != nil { 37 | return err 38 | } 39 | return nil 40 | } 41 | 42 | // getUDPSocketOption6Only return true if the socket is v6 only and false when it is v4/v6 combined 43 | // (dualstack). 44 | func getUDPSocketOptions6Only(conn *net.UDPConn) (bool, error) { 45 | file, err := conn.File() 46 | if err != nil { 47 | return false, err 48 | } 49 | // dual stack. See http://stackoverflow.com/questions/1618240/how-to-support-both-ipv4-and-ipv6-connections 50 | v6only, err := syscall.GetsockoptInt(int(file.Fd()), syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY) 51 | if err != nil { 52 | return false, err 53 | } 54 | return v6only == 1, nil 55 | } 56 | 57 | func getUDPSocketName(conn *net.UDPConn) (syscall.Sockaddr, error) { 58 | file, err := conn.File() 59 | if err != nil { 60 | return nil, err 61 | } 62 | return syscall.Getsockname(int(file.Fd())) 63 | } 64 | -------------------------------------------------------------------------------- /udp_other.go: -------------------------------------------------------------------------------- 1 | // +build !linux 2 | 3 | package dns 4 | 5 | import ( 6 | "net" 7 | "syscall" 8 | ) 9 | 10 | // These do nothing. See udp_linux.go for an example of how to implement this. 11 | 12 | // We tried to adhire to some kind of naming scheme. 13 | 14 | func setUDPSocketOptions4(conn *net.UDPConn) error { return nil } 15 | func setUDPSocketOptions6(conn *net.UDPConn) error { return nil } 16 | func getUDPSocketOptions6Only(conn *net.UDPConn) (bool, error) { return false, nil } 17 | func getUDPSocketName(conn *net.UDPConn) (syscall.Sockaddr, error) { return nil, nil } 18 | -------------------------------------------------------------------------------- /udp_windows.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package dns 4 | 5 | import "net" 6 | 7 | type SessionUDP struct { 8 | raddr *net.UDPAddr 9 | } 10 | 11 | // ReadFromSessionUDP acts just like net.UDPConn.ReadFrom(), but returns a session object instead of a 12 | // net.UDPAddr. 13 | func ReadFromSessionUDP(conn *net.UDPConn, b []byte) (int, *SessionUDP, error) { 14 | n, raddr, err := conn.ReadFrom(b) 15 | if err != nil { 16 | return n, nil, err 17 | } 18 | session := &SessionUDP{raddr.(*net.UDPAddr)} 19 | return n, session, err 20 | } 21 | 22 | // WriteToSessionUDP acts just like net.UDPConn.WritetTo(), but uses a *SessionUDP instead of a net.Addr. 23 | func WriteToSessionUDP(conn *net.UDPConn, b []byte, session *SessionUDP) (int, error) { 24 | n, err := conn.WriteTo(b, session.raddr) 25 | return n, err 26 | } 27 | 28 | func (s *SessionUDP) RemoteAddr() net.Addr { return s.raddr } 29 | 30 | // setUDPSocketOptions sets the UDP socket options. 31 | // This function is implemented on a per platform basis. See udp_*.go for more details 32 | func setUDPSocketOptions(conn *net.UDPConn) error { 33 | return nil 34 | } 35 | -------------------------------------------------------------------------------- /update.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | // NameUsed sets the RRs in the prereq section to 4 | // "Name is in use" RRs. RFC 2136 section 2.4.4. 5 | func (u *Msg) NameUsed(rr []RR) { 6 | u.Answer = make([]RR, len(rr)) 7 | for i, r := range rr { 8 | u.Answer[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassANY}} 9 | } 10 | } 11 | 12 | // NameNotUsed sets the RRs in the prereq section to 13 | // "Name is in not use" RRs. RFC 2136 section 2.4.5. 14 | func (u *Msg) NameNotUsed(rr []RR) { 15 | u.Answer = make([]RR, len(rr)) 16 | for i, r := range rr { 17 | u.Answer[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassNONE}} 18 | } 19 | } 20 | 21 | // Used sets the RRs in the prereq section to 22 | // "RRset exists (value dependent -- with rdata)" RRs. RFC 2136 section 2.4.2. 23 | func (u *Msg) Used(rr []RR) { 24 | if len(u.Question) == 0 { 25 | panic("dns: empty question section") 26 | } 27 | u.Answer = make([]RR, len(rr)) 28 | for i, r := range rr { 29 | u.Answer[i] = r 30 | u.Answer[i].Header().Class = u.Question[0].Qclass 31 | } 32 | } 33 | 34 | // RRsetUsed sets the RRs in the prereq section to 35 | // "RRset exists (value independent -- no rdata)" RRs. RFC 2136 section 2.4.1. 36 | func (u *Msg) RRsetUsed(rr []RR) { 37 | u.Answer = make([]RR, len(rr)) 38 | for i, r := range rr { 39 | u.Answer[i] = r 40 | u.Answer[i].Header().Class = ClassANY 41 | u.Answer[i].Header().Ttl = 0 42 | u.Answer[i].Header().Rdlength = 0 43 | } 44 | } 45 | 46 | // RRsetNotUsed sets the RRs in the prereq section to 47 | // "RRset does not exist" RRs. RFC 2136 section 2.4.3. 48 | func (u *Msg) RRsetNotUsed(rr []RR) { 49 | u.Answer = make([]RR, len(rr)) 50 | for i, r := range rr { 51 | u.Answer[i] = r 52 | u.Answer[i].Header().Class = ClassNONE 53 | u.Answer[i].Header().Rdlength = 0 54 | u.Answer[i].Header().Ttl = 0 55 | } 56 | } 57 | 58 | // Insert creates a dynamic update packet that adds an complete RRset, see RFC 2136 section 2.5.1. 59 | func (u *Msg) Insert(rr []RR) { 60 | if len(u.Question) == 0 { 61 | panic("dns: empty question section") 62 | } 63 | u.Ns = make([]RR, len(rr)) 64 | for i, r := range rr { 65 | u.Ns[i] = r 66 | u.Ns[i].Header().Class = u.Question[0].Qclass 67 | } 68 | } 69 | 70 | // RemoveRRset creates a dynamic update packet that deletes an RRset, see RFC 2136 section 2.5.2. 71 | func (u *Msg) RemoveRRset(rr []RR) { 72 | u.Ns = make([]RR, len(rr)) 73 | for i, r := range rr { 74 | u.Ns[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: r.Header().Rrtype, Class: ClassANY}} 75 | } 76 | } 77 | 78 | // RemoveName creates a dynamic update packet that deletes all RRsets of a name, see RFC 2136 section 2.5.3 79 | func (u *Msg) RemoveName(rr []RR) { 80 | u.Ns = make([]RR, len(rr)) 81 | for i, r := range rr { 82 | u.Ns[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassANY}} 83 | } 84 | } 85 | 86 | // Remove creates a dynamic update packet deletes RR from the RRSset, see RFC 2136 section 2.5.4 87 | func (u *Msg) Remove(rr []RR) { 88 | u.Ns = make([]RR, len(rr)) 89 | for i, r := range rr { 90 | u.Ns[i] = r 91 | u.Ns[i].Header().Class = ClassNONE 92 | u.Ns[i].Header().Ttl = 0 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /update_test.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | ) 7 | 8 | func TestDynamicUpdateParsing(t *testing.T) { 9 | prefix := "example.com. IN " 10 | for _, typ := range TypeToString { 11 | if typ == "OPT" || typ == "AXFR" || typ == "IXFR" || typ == "ANY" || typ == "TKEY" || 12 | typ == "TSIG" || typ == "ISDN" || typ == "UNSPEC" || typ == "NULL" || typ == "ATMA" { 13 | continue 14 | } 15 | r, err := NewRR(prefix + typ) 16 | if err != nil { 17 | t.Errorf("failure to parse: %s %s: %v", prefix, typ, err) 18 | } else { 19 | t.Logf("parsed: %s", r.String()) 20 | } 21 | } 22 | } 23 | 24 | func TestDynamicUpdateUnpack(t *testing.T) { 25 | // From https://github.com/miekg/dns/issues/150#issuecomment-62296803 26 | // It should be an update message for the zone "example.", 27 | // deleting the A RRset "example." and then adding an A record at "example.". 28 | // class ANY, TYPE A 29 | buf := []byte{171, 68, 40, 0, 0, 1, 0, 0, 0, 2, 0, 0, 7, 101, 120, 97, 109, 112, 108, 101, 0, 0, 6, 0, 1, 192, 12, 0, 1, 0, 255, 0, 0, 0, 0, 0, 0, 192, 12, 0, 1, 0, 1, 0, 0, 0, 0, 0, 4, 127, 0, 0, 1} 30 | msg := new(Msg) 31 | err := msg.Unpack(buf) 32 | if err != nil { 33 | t.Errorf("failed to unpack: %v\n%s", err, msg.String()) 34 | } 35 | } 36 | 37 | func TestDynamicUpdateZeroRdataUnpack(t *testing.T) { 38 | m := new(Msg) 39 | rr := &RR_Header{Name: ".", Rrtype: 0, Class: 1, Ttl: ^uint32(0), Rdlength: 0} 40 | m.Answer = []RR{rr, rr, rr, rr, rr} 41 | m.Ns = m.Answer 42 | for n, s := range TypeToString { 43 | rr.Rrtype = n 44 | bytes, err := m.Pack() 45 | if err != nil { 46 | t.Errorf("failed to pack %s: %v", s, err) 47 | continue 48 | } 49 | if err := new(Msg).Unpack(bytes); err != nil { 50 | t.Errorf("failed to unpack %s: %v", s, err) 51 | } 52 | } 53 | } 54 | 55 | func TestRemoveRRset(t *testing.T) { 56 | // Should add a zero data RR in Class ANY with a TTL of 0 57 | // for each set mentioned in the RRs provided to it. 58 | rr, err := NewRR(". 100 IN A 127.0.0.1") 59 | if err != nil { 60 | t.Fatalf("Error constructing RR: %v", err) 61 | } 62 | m := new(Msg) 63 | m.Ns = []RR{&RR_Header{Name: ".", Rrtype: TypeA, Class: ClassANY, Ttl: 0, Rdlength: 0}} 64 | expectstr := m.String() 65 | expect, err := m.Pack() 66 | if err != nil { 67 | t.Fatalf("Error packing expected msg: %v", err) 68 | } 69 | 70 | m.Ns = nil 71 | m.RemoveRRset([]RR{rr}) 72 | actual, err := m.Pack() 73 | if err != nil { 74 | t.Fatalf("Error packing actual msg: %v", err) 75 | } 76 | if !bytes.Equal(actual, expect) { 77 | tmp := new(Msg) 78 | if err := tmp.Unpack(actual); err != nil { 79 | t.Fatalf("Error unpacking actual msg: %v", err) 80 | } 81 | t.Errorf("Expected msg:\n%s", expectstr) 82 | t.Errorf("Actual msg:\n%v", tmp) 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /xfr.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "time" 5 | ) 6 | 7 | // Envelope is used when doing a zone transfer with a remote server. 8 | type Envelope struct { 9 | RR []RR // The set of RRs in the answer section of the xfr reply message. 10 | Error error // If something went wrong, this contains the error. 11 | } 12 | 13 | // A Transfer defines parameters that are used during a zone transfer. 14 | type Transfer struct { 15 | *Conn 16 | DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds 17 | ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds 18 | WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds 19 | TsigSecret map[string]string // Secret(s) for Tsig map[], zonename must be fully qualified 20 | tsigTimersOnly bool 21 | } 22 | 23 | // Think we need to away to stop the transfer 24 | 25 | // In performs an incoming transfer with the server in a. 26 | // If you would like to set the source IP, or some other attribute 27 | // of a Dialer for a Transfer, you can do so by specifying the attributes 28 | // in the Transfer.Conn: 29 | // 30 | // d := net.Dialer{LocalAddr: transfer_source} 31 | // con, err := d.Dial("tcp", master) 32 | // dnscon := &dns.Conn{Conn:con} 33 | // transfer = &dns.Transfer{Conn: dnscon} 34 | // channel, err := transfer.In(message, master) 35 | // 36 | func (t *Transfer) In(q *Msg, a string) (env chan *Envelope, err error) { 37 | timeout := dnsTimeout 38 | if t.DialTimeout != 0 { 39 | timeout = t.DialTimeout 40 | } 41 | if t.Conn == nil { 42 | t.Conn, err = DialTimeout("tcp", a, timeout) 43 | if err != nil { 44 | return nil, err 45 | } 46 | } 47 | if err := t.WriteMsg(q); err != nil { 48 | return nil, err 49 | } 50 | env = make(chan *Envelope) 51 | go func() { 52 | if q.Question[0].Qtype == TypeAXFR { 53 | go t.inAxfr(q.Id, env) 54 | return 55 | } 56 | if q.Question[0].Qtype == TypeIXFR { 57 | go t.inIxfr(q.Id, env) 58 | return 59 | } 60 | }() 61 | return env, nil 62 | } 63 | 64 | func (t *Transfer) inAxfr(id uint16, c chan *Envelope) { 65 | first := true 66 | defer t.Close() 67 | defer close(c) 68 | timeout := dnsTimeout 69 | if t.ReadTimeout != 0 { 70 | timeout = t.ReadTimeout 71 | } 72 | for { 73 | t.Conn.SetReadDeadline(time.Now().Add(timeout)) 74 | in, err := t.ReadMsg() 75 | if err != nil { 76 | c <- &Envelope{nil, err} 77 | return 78 | } 79 | if id != in.Id { 80 | c <- &Envelope{in.Answer, ErrId} 81 | return 82 | } 83 | if first { 84 | if !isSOAFirst(in) { 85 | c <- &Envelope{in.Answer, ErrSoa} 86 | return 87 | } 88 | first = !first 89 | // only one answer that is SOA, receive more 90 | if len(in.Answer) == 1 { 91 | t.tsigTimersOnly = true 92 | c <- &Envelope{in.Answer, nil} 93 | continue 94 | } 95 | } 96 | 97 | if !first { 98 | t.tsigTimersOnly = true // Subsequent envelopes use this. 99 | if isSOALast(in) { 100 | c <- &Envelope{in.Answer, nil} 101 | return 102 | } 103 | c <- &Envelope{in.Answer, nil} 104 | } 105 | } 106 | } 107 | 108 | func (t *Transfer) inIxfr(id uint16, c chan *Envelope) { 109 | serial := uint32(0) // The first serial seen is the current server serial 110 | first := true 111 | defer t.Close() 112 | defer close(c) 113 | timeout := dnsTimeout 114 | if t.ReadTimeout != 0 { 115 | timeout = t.ReadTimeout 116 | } 117 | for { 118 | t.SetReadDeadline(time.Now().Add(timeout)) 119 | in, err := t.ReadMsg() 120 | if err != nil { 121 | c <- &Envelope{nil, err} 122 | return 123 | } 124 | if id != in.Id { 125 | c <- &Envelope{in.Answer, ErrId} 126 | return 127 | } 128 | if first { 129 | // A single SOA RR signals "no changes" 130 | if len(in.Answer) == 1 && isSOAFirst(in) { 131 | c <- &Envelope{in.Answer, nil} 132 | return 133 | } 134 | 135 | // Check if the returned answer is ok 136 | if !isSOAFirst(in) { 137 | c <- &Envelope{in.Answer, ErrSoa} 138 | return 139 | } 140 | // This serial is important 141 | serial = in.Answer[0].(*SOA).Serial 142 | first = !first 143 | } 144 | 145 | // Now we need to check each message for SOA records, to see what we need to do 146 | if !first { 147 | t.tsigTimersOnly = true 148 | // If the last record in the IXFR contains the servers' SOA, we should quit 149 | if v, ok := in.Answer[len(in.Answer)-1].(*SOA); ok { 150 | if v.Serial == serial { 151 | c <- &Envelope{in.Answer, nil} 152 | return 153 | } 154 | } 155 | c <- &Envelope{in.Answer, nil} 156 | } 157 | } 158 | } 159 | 160 | // Out performs an outgoing transfer with the client connecting in w. 161 | // Basic use pattern: 162 | // 163 | // ch := make(chan *dns.Envelope) 164 | // tr := new(dns.Transfer) 165 | // tr.Out(w, r, ch) 166 | // c <- &dns.Envelope{RR: []dns.RR{soa, rr1, rr2, rr3, soa}} 167 | // close(ch) 168 | // w.Hijack() 169 | // // w.Close() // Client closes connection 170 | // 171 | // The server is responsible for sending the correct sequence of RRs through the 172 | // channel ch. 173 | func (t *Transfer) Out(w ResponseWriter, q *Msg, ch chan *Envelope) error { 174 | for x := range ch { 175 | r := new(Msg) 176 | // Compress? 177 | r.SetReply(q) 178 | r.Authoritative = true 179 | // assume it fits TODO(miek): fix 180 | r.Answer = append(r.Answer, x.RR...) 181 | if err := w.WriteMsg(r); err != nil { 182 | return err 183 | } 184 | } 185 | w.TsigTimersOnly(true) 186 | return nil 187 | } 188 | 189 | // ReadMsg reads a message from the transfer connection t. 190 | func (t *Transfer) ReadMsg() (*Msg, error) { 191 | m := new(Msg) 192 | p := make([]byte, MaxMsgSize) 193 | n, err := t.Read(p) 194 | if err != nil && n == 0 { 195 | return nil, err 196 | } 197 | p = p[:n] 198 | if err := m.Unpack(p); err != nil { 199 | return nil, err 200 | } 201 | if ts := m.IsTsig(); ts != nil && t.TsigSecret != nil { 202 | if _, ok := t.TsigSecret[ts.Hdr.Name]; !ok { 203 | return m, ErrSecret 204 | } 205 | // Need to work on the original message p, as that was used to calculate the tsig. 206 | err = TsigVerify(p, t.TsigSecret[ts.Hdr.Name], t.tsigRequestMAC, t.tsigTimersOnly) 207 | t.tsigRequestMAC = ts.MAC 208 | } 209 | return m, err 210 | } 211 | 212 | // WriteMsg writes a message through the transfer connection t. 213 | func (t *Transfer) WriteMsg(m *Msg) (err error) { 214 | var out []byte 215 | if ts := m.IsTsig(); ts != nil && t.TsigSecret != nil { 216 | if _, ok := t.TsigSecret[ts.Hdr.Name]; !ok { 217 | return ErrSecret 218 | } 219 | out, t.tsigRequestMAC, err = TsigGenerate(m, t.TsigSecret[ts.Hdr.Name], t.tsigRequestMAC, t.tsigTimersOnly) 220 | } else { 221 | out, err = m.Pack() 222 | } 223 | if err != nil { 224 | return err 225 | } 226 | if _, err = t.Write(out); err != nil { 227 | return err 228 | } 229 | return nil 230 | } 231 | 232 | func isSOAFirst(in *Msg) bool { 233 | if len(in.Answer) > 0 { 234 | return in.Answer[0].Header().Rrtype == TypeSOA 235 | } 236 | return false 237 | } 238 | 239 | func isSOALast(in *Msg) bool { 240 | if len(in.Answer) > 0 { 241 | return in.Answer[len(in.Answer)-1].Header().Rrtype == TypeSOA 242 | } 243 | return false 244 | } 245 | -------------------------------------------------------------------------------- /xfr_test.go: -------------------------------------------------------------------------------- 1 | // +build net 2 | 3 | package dns 4 | 5 | import ( 6 | "net" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | func getIP(s string) string { 12 | a, err := net.LookupAddr(s) 13 | if err != nil { 14 | return "" 15 | } 16 | return a[0] 17 | } 18 | 19 | // flaky, need to setup local server and test from 20 | // that. 21 | func TestAXFR_Miek(t *testing.T) { 22 | // This test runs against a server maintained by Miek 23 | if testing.Short() { 24 | return 25 | } 26 | m := new(Msg) 27 | m.SetAxfr("miek.nl.") 28 | 29 | server := getIP("linode.atoom.net") 30 | 31 | tr := new(Transfer) 32 | 33 | if a, err := tr.In(m, net.JoinHostPort(server, "53")); err != nil { 34 | t.Fatal("failed to setup axfr: ", err) 35 | } else { 36 | for ex := range a { 37 | if ex.Error != nil { 38 | t.Errorf("error %v", ex.Error) 39 | break 40 | } 41 | for _, rr := range ex.RR { 42 | t.Log(rr.String()) 43 | } 44 | } 45 | } 46 | } 47 | 48 | // fails. 49 | func TestAXFR_NLNL_MultipleEnvelopes(t *testing.T) { 50 | // This test runs against a server maintained by NLnet Labs 51 | if testing.Short() { 52 | return 53 | } 54 | m := new(Msg) 55 | m.SetAxfr("nlnetlabs.nl.") 56 | 57 | server := getIP("open.nlnetlabs.nl.") 58 | 59 | tr := new(Transfer) 60 | if a, err := tr.In(m, net.JoinHostPort(server, "53")); err != nil { 61 | t.Fatalf("Failed to setup axfr %v for server: %v", err, server) 62 | } else { 63 | for ex := range a { 64 | if ex.Error != nil { 65 | t.Errorf("Error %v", ex.Error) 66 | break 67 | } 68 | } 69 | } 70 | } 71 | 72 | func TestAXFR_Miek_Tsig(t *testing.T) { 73 | // This test runs against a server maintained by Miek 74 | if testing.Short() { 75 | return 76 | } 77 | m := new(Msg) 78 | m.SetAxfr("example.nl.") 79 | m.SetTsig("axfr.", HmacMD5, 300, time.Now().Unix()) 80 | 81 | tr := new(Transfer) 82 | tr.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="} 83 | 84 | if a, err := tr.In(m, "176.58.119.54:53"); err != nil { 85 | t.Fatal("failed to setup axfr: ", err) 86 | } else { 87 | for ex := range a { 88 | if ex.Error != nil { 89 | t.Errorf("error %v", ex.Error) 90 | break 91 | } 92 | for _, rr := range ex.RR { 93 | t.Log(rr.String()) 94 | } 95 | } 96 | } 97 | } 98 | 99 | func TestAXFR_SIDN_NSD3_NONE(t *testing.T) { testAXFRSIDN(t, "nsd", "") } 100 | func TestAXFR_SIDN_NSD3_MD5(t *testing.T) { testAXFRSIDN(t, "nsd", HmacMD5) } 101 | func TestAXFR_SIDN_NSD3_SHA1(t *testing.T) { testAXFRSIDN(t, "nsd", HmacSHA1) } 102 | func TestAXFR_SIDN_NSD3_SHA256(t *testing.T) { testAXFRSIDN(t, "nsd", HmacSHA256) } 103 | 104 | func TestAXFR_SIDN_NSD4_NONE(t *testing.T) { testAXFRSIDN(t, "nsd4", "") } 105 | func TestAXFR_SIDN_NSD4_MD5(t *testing.T) { testAXFRSIDN(t, "nsd4", HmacMD5) } 106 | func TestAXFR_SIDN_NSD4_SHA1(t *testing.T) { testAXFRSIDN(t, "nsd4", HmacSHA1) } 107 | func TestAXFR_SIDN_NSD4_SHA256(t *testing.T) { testAXFRSIDN(t, "nsd4", HmacSHA256) } 108 | 109 | func TestAXFR_SIDN_BIND9_NONE(t *testing.T) { testAXFRSIDN(t, "bind9", "") } 110 | func TestAXFR_SIDN_BIND9_MD5(t *testing.T) { testAXFRSIDN(t, "bind9", HmacMD5) } 111 | func TestAXFR_SIDN_BIND9_SHA1(t *testing.T) { testAXFRSIDN(t, "bind9", HmacSHA1) } 112 | func TestAXFR_SIDN_BIND9_SHA256(t *testing.T) { testAXFRSIDN(t, "bind9", HmacSHA256) } 113 | 114 | func TestAXFR_SIDN_KNOT_NONE(t *testing.T) { testAXFRSIDN(t, "knot", "") } 115 | func TestAXFR_SIDN_KNOT_MD5(t *testing.T) { testAXFRSIDN(t, "knot", HmacMD5) } 116 | func TestAXFR_SIDN_KNOT_SHA1(t *testing.T) { testAXFRSIDN(t, "knot", HmacSHA1) } 117 | func TestAXFR_SIDN_KNOT_SHA256(t *testing.T) { testAXFRSIDN(t, "knot", HmacSHA256) } 118 | 119 | func TestAXFR_SIDN_POWERDNS_NONE(t *testing.T) { testAXFRSIDN(t, "powerdns", "") } 120 | func TestAXFR_SIDN_POWERDNS_MD5(t *testing.T) { testAXFRSIDN(t, "powerdns", HmacMD5) } 121 | func TestAXFR_SIDN_POWERDNS_SHA1(t *testing.T) { testAXFRSIDN(t, "powerdns", HmacSHA1) } 122 | func TestAXFR_SIDN_POWERDNS_SHA256(t *testing.T) { testAXFRSIDN(t, "powerdns", HmacSHA256) } 123 | 124 | func TestAXFR_SIDN_YADIFA_NONE(t *testing.T) { testAXFRSIDN(t, "yadifa", "") } 125 | func TestAXFR_SIDN_YADIFA_MD5(t *testing.T) { testAXFRSIDN(t, "yadifa", HmacMD5) } 126 | func TestAXFR_SIDN_YADIFA_SHA1(t *testing.T) { testAXFRSIDN(t, "yadifa", HmacSHA1) } 127 | func TestAXFR_SIDN_YADIFA_SHA256(t *testing.T) { testAXFRSIDN(t, "yadifa", HmacSHA256) } 128 | 129 | func testAXFRSIDN(t *testing.T, host, alg string) { 130 | // This tests run against a server maintained by SIDN labs, see: 131 | // https://workbench.sidnlabs.nl/ 132 | if testing.Short() { 133 | return 134 | } 135 | x := new(Transfer) 136 | x.TsigSecret = map[string]string{ 137 | "wb_md5.": "Wu/utSasZUkoeCNku152Zw==", 138 | "wb_sha1_longkey.": "uhMpEhPq/RAD9Bt4mqhfmi+7ZdKmjLQb/lcrqYPXR4s/nnbsqw==", 139 | "wb_sha256.": "npfrIJjt/MJOjGJoBNZtsjftKMhkSpIYMv2RzRZt1f8=", 140 | } 141 | keyname := map[string]string{ 142 | HmacMD5: "wb_md5.", 143 | HmacSHA1: "wb_sha1_longkey.", 144 | HmacSHA256: "wb_sha256.", 145 | }[alg] 146 | 147 | m := new(Msg) 148 | m.SetAxfr("types.wb.sidnlabs.nl.") 149 | if keyname != "" { 150 | m.SetTsig(keyname, alg, 300, time.Now().Unix()) 151 | } 152 | c, err := x.In(m, host+".sidnlabs.nl:53") 153 | if err != nil { 154 | t.Fatal(err) 155 | } 156 | for e := range c { 157 | if e.Error != nil { 158 | t.Fatal(e.Error) 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /zgenerate.go: -------------------------------------------------------------------------------- 1 | package dns 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | // Parse the $GENERATE statement as used in BIND9 zones. 11 | // See http://www.zytrax.com/books/dns/ch8/generate.html for instance. 12 | // We are called after '$GENERATE '. After which we expect: 13 | // * the range (12-24/2) 14 | // * lhs (ownername) 15 | // * [[ttl][class]] 16 | // * type 17 | // * rhs (rdata) 18 | // But we are lazy here, only the range is parsed *all* occurences 19 | // of $ after that are interpreted. 20 | // Any error are returned as a string value, the empty string signals 21 | // "no error". 22 | func generate(l lex, c chan lex, t chan *Token, o string) string { 23 | step := 1 24 | if i := strings.IndexAny(l.token, "/"); i != -1 { 25 | if i+1 == len(l.token) { 26 | return "bad step in $GENERATE range" 27 | } 28 | if s, e := strconv.Atoi(l.token[i+1:]); e == nil { 29 | if s < 0 { 30 | return "bad step in $GENERATE range" 31 | } 32 | step = s 33 | } else { 34 | return "bad step in $GENERATE range" 35 | } 36 | l.token = l.token[:i] 37 | } 38 | sx := strings.SplitN(l.token, "-", 2) 39 | if len(sx) != 2 { 40 | return "bad start-stop in $GENERATE range" 41 | } 42 | start, err := strconv.Atoi(sx[0]) 43 | if err != nil { 44 | return "bad start in $GENERATE range" 45 | } 46 | end, err := strconv.Atoi(sx[1]) 47 | if err != nil { 48 | return "bad stop in $GENERATE range" 49 | } 50 | if end < 0 || start < 0 || end < start { 51 | return "bad range in $GENERATE range" 52 | } 53 | 54 | <-c // _BLANK 55 | // Create a complete new string, which we then parse again. 56 | s := "" 57 | BuildRR: 58 | l = <-c 59 | if l.value != zNewline && l.value != zEOF { 60 | s += l.token 61 | goto BuildRR 62 | } 63 | for i := start; i <= end; i += step { 64 | var ( 65 | escape bool 66 | dom bytes.Buffer 67 | mod string 68 | err string 69 | offset int 70 | ) 71 | 72 | for j := 0; j < len(s); j++ { // No 'range' because we need to jump around 73 | switch s[j] { 74 | case '\\': 75 | if escape { 76 | dom.WriteByte('\\') 77 | escape = false 78 | continue 79 | } 80 | escape = true 81 | case '$': 82 | mod = "%d" 83 | offset = 0 84 | if escape { 85 | dom.WriteByte('$') 86 | escape = false 87 | continue 88 | } 89 | escape = false 90 | if j+1 >= len(s) { // End of the string 91 | dom.WriteString(fmt.Sprintf(mod, i+offset)) 92 | continue 93 | } else { 94 | if s[j+1] == '$' { 95 | dom.WriteByte('$') 96 | j++ 97 | continue 98 | } 99 | } 100 | // Search for { and } 101 | if s[j+1] == '{' { // Modifier block 102 | sep := strings.Index(s[j+2:], "}") 103 | if sep == -1 { 104 | return "bad modifier in $GENERATE" 105 | } 106 | mod, offset, err = modToPrintf(s[j+2 : j+2+sep]) 107 | if err != "" { 108 | return err 109 | } 110 | j += 2 + sep // Jump to it 111 | } 112 | dom.WriteString(fmt.Sprintf(mod, i+offset)) 113 | default: 114 | if escape { // Pretty useless here 115 | escape = false 116 | continue 117 | } 118 | dom.WriteByte(s[j]) 119 | } 120 | } 121 | // Re-parse the RR and send it on the current channel t 122 | rx, e := NewRR("$ORIGIN " + o + "\n" + dom.String()) 123 | if e != nil { 124 | return e.(*ParseError).err 125 | } 126 | t <- &Token{RR: rx} 127 | // Its more efficient to first built the rrlist and then parse it in 128 | // one go! But is this a problem? 129 | } 130 | return "" 131 | } 132 | 133 | // Convert a $GENERATE modifier 0,0,d to something Printf can deal with. 134 | func modToPrintf(s string) (string, int, string) { 135 | xs := strings.SplitN(s, ",", 3) 136 | if len(xs) != 3 { 137 | return "", 0, "bad modifier in $GENERATE" 138 | } 139 | // xs[0] is offset, xs[1] is width, xs[2] is base 140 | if xs[2] != "o" && xs[2] != "d" && xs[2] != "x" && xs[2] != "X" { 141 | return "", 0, "bad base in $GENERATE" 142 | } 143 | offset, err := strconv.Atoi(xs[0]) 144 | if err != nil || offset > 255 { 145 | return "", 0, "bad offset in $GENERATE" 146 | } 147 | width, err := strconv.Atoi(xs[1]) 148 | if err != nil || width > 255 { 149 | return "", offset, "bad width in $GENERATE" 150 | } 151 | switch { 152 | case width < 0: 153 | return "", offset, "bad width in $GENERATE" 154 | case width == 0: 155 | return "%" + xs[1] + xs[2], offset, "" 156 | } 157 | return "%0" + xs[1] + xs[2], offset, "" 158 | } 159 | --------------------------------------------------------------------------------