mirror of
https://github.com/m13253/dns-over-https.git
synced 2026-03-30 16:25:39 +00:00
Implement IETF protocol
This commit is contained in:
@@ -1,63 +1,64 @@
|
||||
/*
|
||||
DNS-over-HTTPS
|
||||
Copyright (C) 2017 Star Brilliant <m13253@hotmail.com>
|
||||
DNS-over-HTTPS
|
||||
Copyright (C) 2017-2018 Star Brilliant <m13253@hotmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
type config struct {
|
||||
Listen string `toml:"listen"`
|
||||
Cert string `toml:"cert"`
|
||||
Key string `toml:"key"`
|
||||
Path string `toml:"path"`
|
||||
Upstream []string `toml:"upstream"`
|
||||
Timeout uint `toml:"timeout"`
|
||||
Tries uint `toml:"tries"`
|
||||
TCPOnly bool `toml:"tcp_only"`
|
||||
Verbose bool `toml:"verbose"`
|
||||
Listen string `toml:"listen"`
|
||||
Cert string `toml:"cert"`
|
||||
Key string `toml:"key"`
|
||||
Path string `toml:"path"`
|
||||
Upstream []string `toml:"upstream"`
|
||||
Timeout uint `toml:"timeout"`
|
||||
Tries uint `toml:"tries"`
|
||||
TCPOnly bool `toml:"tcp_only"`
|
||||
Verbose bool `toml:"verbose"`
|
||||
}
|
||||
|
||||
func loadConfig(path string) (*config, error) {
|
||||
conf := &config {}
|
||||
conf := &config{}
|
||||
metaData, err := toml.DecodeFile(path, conf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, key := range metaData.Undecoded() {
|
||||
return nil, &configError { fmt.Sprintf("unknown option %q", key.String()) }
|
||||
return nil, &configError{fmt.Sprintf("unknown option %q", key.String())}
|
||||
}
|
||||
|
||||
if conf.Listen == "" {
|
||||
conf.Listen = "127.0.0.1:8053"
|
||||
}
|
||||
if conf.Path == "" {
|
||||
conf.Path = "/resolve"
|
||||
conf.Path = "/dns-query"
|
||||
}
|
||||
if len(conf.Upstream) == 0 {
|
||||
conf.Upstream = []string { "8.8.8.8:53", "8.8.4.4:53" }
|
||||
conf.Upstream = []string{"8.8.8.8:53", "8.8.4.4:53"}
|
||||
}
|
||||
if conf.Timeout == 0 {
|
||||
conf.Timeout = 10
|
||||
@@ -67,14 +68,14 @@ func loadConfig(path string) (*config, error) {
|
||||
}
|
||||
|
||||
if (conf.Cert != "") != (conf.Key != "") {
|
||||
return nil, &configError { "You must specify both -cert and -key to enable TLS" }
|
||||
return nil, &configError{"You must specify both -cert and -key to enable TLS"}
|
||||
}
|
||||
|
||||
return conf, nil
|
||||
}
|
||||
|
||||
type configError struct {
|
||||
err string
|
||||
err string
|
||||
}
|
||||
|
||||
func (e *configError) Error() string {
|
||||
|
||||
@@ -8,7 +8,7 @@ cert = ""
|
||||
key = ""
|
||||
|
||||
# HTTP path for resolve application
|
||||
path = "/resolve"
|
||||
path = "/dns-query"
|
||||
|
||||
# Upstream DNS resolver
|
||||
# If multiple servers are specified, a random one will be chosen each time.
|
||||
|
||||
193
doh-server/google.go
Normal file
193
doh-server/google.go
Normal file
@@ -0,0 +1,193 @@
|
||||
/*
|
||||
DNS-over-HTTPS
|
||||
Copyright (C) 2017-2018 Star Brilliant <m13253@hotmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"../json-dns"
|
||||
"github.com/miekg/dns"
|
||||
"golang.org/x/net/idna"
|
||||
)
|
||||
|
||||
func (s *Server) parseRequestGoogle(w http.ResponseWriter, r *http.Request) *DNSRequest {
|
||||
name := r.FormValue("name")
|
||||
if name == "" {
|
||||
return &DNSRequest{
|
||||
errcode: 400,
|
||||
errtext: "Invalid argument value: \"name\"",
|
||||
}
|
||||
}
|
||||
name = strings.ToLower(name)
|
||||
if punycode, err := idna.ToASCII(name); err == nil {
|
||||
name = punycode
|
||||
} else {
|
||||
return &DNSRequest{
|
||||
errcode: 400,
|
||||
errtext: fmt.Sprintf("Invalid argument value: \"name\" = %q (%s)", name, err.Error()),
|
||||
}
|
||||
}
|
||||
|
||||
rrTypeStr := r.FormValue("type")
|
||||
rrType := uint16(1)
|
||||
if rrTypeStr == "" {
|
||||
} else if v, err := strconv.ParseUint(rrTypeStr, 10, 16); err == nil {
|
||||
rrType = uint16(v)
|
||||
} else if v, ok := dns.StringToType[strings.ToUpper(rrTypeStr)]; ok {
|
||||
rrType = v
|
||||
} else {
|
||||
return &DNSRequest{
|
||||
errcode: 400,
|
||||
errtext: fmt.Sprintf("Invalid argument value: \"type\" = %q", rrTypeStr),
|
||||
}
|
||||
}
|
||||
|
||||
cdStr := r.FormValue("cd")
|
||||
cd := false
|
||||
if cdStr == "1" || cdStr == "true" {
|
||||
cd = true
|
||||
} else if cdStr == "0" || cdStr == "false" || cdStr == "" {
|
||||
} else {
|
||||
return &DNSRequest{
|
||||
errcode: 400,
|
||||
errtext: fmt.Sprintf("Invalid argument value: \"cd\" = %q", cdStr),
|
||||
}
|
||||
}
|
||||
|
||||
ednsClientSubnet := r.FormValue("edns_client_subnet")
|
||||
ednsClientFamily := uint16(0)
|
||||
ednsClientAddress := net.IP(nil)
|
||||
ednsClientNetmask := uint8(255)
|
||||
if ednsClientSubnet != "" {
|
||||
if ednsClientSubnet == "0/0" {
|
||||
ednsClientSubnet = "0.0.0.0/0"
|
||||
}
|
||||
slash := strings.IndexByte(ednsClientSubnet, '/')
|
||||
if slash < 0 {
|
||||
ednsClientAddress = net.ParseIP(ednsClientSubnet)
|
||||
if ednsClientAddress == nil {
|
||||
return &DNSRequest{
|
||||
errcode: 400,
|
||||
errtext: fmt.Sprintf("Invalid argument value: \"edns_client_subnet\" = %q", ednsClientSubnet),
|
||||
}
|
||||
}
|
||||
if ipv4 := ednsClientAddress.To4(); ipv4 != nil {
|
||||
ednsClientFamily = 1
|
||||
ednsClientAddress = ipv4
|
||||
ednsClientNetmask = 24
|
||||
} else {
|
||||
ednsClientFamily = 2
|
||||
ednsClientNetmask = 48
|
||||
}
|
||||
} else {
|
||||
ednsClientAddress = net.ParseIP(ednsClientSubnet[:slash])
|
||||
if ednsClientAddress == nil {
|
||||
return &DNSRequest{
|
||||
errcode: 400,
|
||||
errtext: fmt.Sprintf("Invalid argument value: \"edns_client_subnet\" = %q", ednsClientSubnet),
|
||||
}
|
||||
}
|
||||
if ipv4 := ednsClientAddress.To4(); ipv4 != nil {
|
||||
ednsClientFamily = 1
|
||||
ednsClientAddress = ipv4
|
||||
} else {
|
||||
ednsClientFamily = 2
|
||||
}
|
||||
netmask, err := strconv.ParseUint(ednsClientSubnet[slash+1:], 10, 8)
|
||||
if err != nil {
|
||||
return &DNSRequest{
|
||||
errcode: 400,
|
||||
errtext: fmt.Sprintf("Invalid argument value: \"edns_client_subnet\" = %q", ednsClientSubnet),
|
||||
}
|
||||
}
|
||||
ednsClientNetmask = uint8(netmask)
|
||||
}
|
||||
} else {
|
||||
ednsClientAddress = s.findClientIP(r)
|
||||
if ednsClientAddress == nil {
|
||||
ednsClientNetmask = 0
|
||||
} else if ipv4 := ednsClientAddress.To4(); ipv4 != nil {
|
||||
ednsClientFamily = 1
|
||||
ednsClientAddress = ipv4
|
||||
ednsClientNetmask = 24
|
||||
} else {
|
||||
ednsClientFamily = 2
|
||||
ednsClientNetmask = 48
|
||||
}
|
||||
}
|
||||
|
||||
msg := new(dns.Msg)
|
||||
msg.SetQuestion(dns.Fqdn(name), rrType)
|
||||
msg.CheckingDisabled = cd
|
||||
opt := new(dns.OPT)
|
||||
opt.Hdr.Name = "."
|
||||
opt.Hdr.Rrtype = dns.TypeOPT
|
||||
opt.SetUDPSize(4096)
|
||||
opt.SetDo(true)
|
||||
if ednsClientAddress != nil {
|
||||
edns0Subnet := new(dns.EDNS0_SUBNET)
|
||||
edns0Subnet.Code = dns.EDNS0SUBNET
|
||||
edns0Subnet.Family = ednsClientFamily
|
||||
edns0Subnet.SourceNetmask = ednsClientNetmask
|
||||
edns0Subnet.SourceScope = 0
|
||||
edns0Subnet.Address = ednsClientAddress
|
||||
opt.Option = append(opt.Option, edns0Subnet)
|
||||
}
|
||||
msg.Extra = append(msg.Extra, opt)
|
||||
|
||||
return &DNSRequest{
|
||||
request: msg,
|
||||
isTailored: ednsClientSubnet == "",
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) generateResponseGoogle(w http.ResponseWriter, r *http.Request, req *DNSRequest) {
|
||||
respJSON := jsonDNS.Marshal(req.response)
|
||||
respStr, err := json.Marshal(respJSON)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
jsonDNS.FormatError(w, fmt.Sprintf("DNS packet parse failure (%s)", err.Error()), 500)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
|
||||
if respJSON.HaveTTL {
|
||||
if req.isTailored {
|
||||
w.Header().Set("Cache-Control", "public, max-age="+strconv.Itoa(int(respJSON.LeastTTL)))
|
||||
} else {
|
||||
w.Header().Set("Cache-Control", "private, max-age="+strconv.Itoa(int(respJSON.LeastTTL)))
|
||||
}
|
||||
w.Header().Set("Expires", respJSON.EarliestExpires.Format(http.TimeFormat))
|
||||
}
|
||||
if respJSON.Status == dns.RcodeServerFailure {
|
||||
w.WriteHeader(503)
|
||||
}
|
||||
w.Write(respStr)
|
||||
}
|
||||
144
doh-server/ietf.go
Normal file
144
doh-server/ietf.go
Normal file
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
DNS-over-HTTPS
|
||||
Copyright (C) 2017-2018 Star Brilliant <m13253@hotmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"../json-dns"
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
func (s *Server) parseRequestIETF(w http.ResponseWriter, r *http.Request) *DNSRequest {
|
||||
requestBase64 := r.FormValue("dns")
|
||||
requestBinary, err := base64.StdEncoding.DecodeString(requestBase64)
|
||||
if err != nil {
|
||||
return &DNSRequest{
|
||||
errcode: 400,
|
||||
errtext: fmt.Sprintf("Invalid argument value: \"dns\" = %q", requestBase64),
|
||||
}
|
||||
}
|
||||
if len(requestBinary) == 0 && r.Header.Get("Content-Type") == "application/dns-udpwireformat" {
|
||||
requestBinary, err = ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return &DNSRequest{
|
||||
errcode: 400,
|
||||
errtext: fmt.Sprintf("Failed to read request body (%s)", err.Error()),
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(requestBinary) == 0 {
|
||||
return &DNSRequest{
|
||||
errcode: 400,
|
||||
errtext: fmt.Sprintf("Invalid argument value: \"dns\""),
|
||||
}
|
||||
}
|
||||
msg := new(dns.Msg)
|
||||
err = msg.Unpack(requestBinary)
|
||||
if err != nil {
|
||||
return &DNSRequest{
|
||||
errcode: 400,
|
||||
errtext: fmt.Sprintf("DNS packet parse failure (%s)", err.Error()),
|
||||
}
|
||||
}
|
||||
msg.Id = dns.Id()
|
||||
opt := msg.IsEdns0()
|
||||
if opt == nil {
|
||||
opt = new(dns.OPT)
|
||||
opt.Hdr.Name = "."
|
||||
opt.Hdr.Rrtype = dns.TypeOPT
|
||||
opt.SetUDPSize(4096)
|
||||
opt.SetDo(false)
|
||||
msg.Extra = append(msg.Extra, opt)
|
||||
}
|
||||
var edns0Subnet *dns.EDNS0_SUBNET
|
||||
for _, option := range opt.Option {
|
||||
if option.Option() == dns.EDNS0SUBNET {
|
||||
edns0Subnet = option.(*dns.EDNS0_SUBNET)
|
||||
break
|
||||
}
|
||||
}
|
||||
isTailored := edns0Subnet == nil
|
||||
if edns0Subnet == nil {
|
||||
ednsClientFamily := uint16(0)
|
||||
ednsClientAddress := s.findClientIP(r)
|
||||
ednsClientNetmask := uint8(255)
|
||||
if ednsClientAddress == nil {
|
||||
ednsClientNetmask = 0
|
||||
} else if ipv4 := ednsClientAddress.To4(); ipv4 != nil {
|
||||
ednsClientFamily = 1
|
||||
ednsClientAddress = ipv4
|
||||
ednsClientNetmask = 24
|
||||
} else {
|
||||
ednsClientFamily = 2
|
||||
ednsClientNetmask = 48
|
||||
}
|
||||
edns0Subnet = new(dns.EDNS0_SUBNET)
|
||||
edns0Subnet.Code = dns.EDNS0SUBNET
|
||||
edns0Subnet.Family = ednsClientFamily
|
||||
edns0Subnet.SourceNetmask = ednsClientNetmask
|
||||
edns0Subnet.SourceScope = 0
|
||||
edns0Subnet.Address = ednsClientAddress
|
||||
opt.Option = append(opt.Option, edns0Subnet)
|
||||
}
|
||||
|
||||
return &DNSRequest{
|
||||
request: msg,
|
||||
isTailored: isTailored,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) generateResponseIETF(w http.ResponseWriter, r *http.Request, req *DNSRequest) {
|
||||
respJSON := jsonDNS.Marshal(req.response)
|
||||
req.response.Id = 0
|
||||
respBytes, err := req.response.Pack()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
jsonDNS.FormatError(w, fmt.Sprintf("DNS packet construct failure (%s)", err.Error()), 500)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/dns-udpwireformat")
|
||||
now := time.Now().Format(http.TimeFormat)
|
||||
w.Header().Set("Date", now)
|
||||
w.Header().Set("Last-Modified", now)
|
||||
if respJSON.HaveTTL {
|
||||
if req.isTailored {
|
||||
w.Header().Set("Cache-Control", "public, max-age="+strconv.Itoa(int(respJSON.LeastTTL)))
|
||||
} else {
|
||||
w.Header().Set("Cache-Control", "private, max-age="+strconv.Itoa(int(respJSON.LeastTTL)))
|
||||
}
|
||||
w.Header().Set("Expires", respJSON.EarliestExpires.Format(http.TimeFormat))
|
||||
}
|
||||
if respJSON.Status == dns.RcodeServerFailure {
|
||||
w.WriteHeader(503)
|
||||
}
|
||||
w.Write(respBytes)
|
||||
}
|
||||
@@ -1,24 +1,24 @@
|
||||
/*
|
||||
DNS-over-HTTPS
|
||||
Copyright (C) 2017 Star Brilliant <m13253@hotmail.com>
|
||||
DNS-over-HTTPS
|
||||
Copyright (C) 2017-2018 Star Brilliant <m13253@hotmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
@@ -1,61 +1,67 @@
|
||||
/*
|
||||
DNS-over-HTTPS
|
||||
Copyright (C) 2017 Star Brilliant <m13253@hotmail.com>
|
||||
DNS-over-HTTPS
|
||||
Copyright (C) 2017-2018 Star Brilliant <m13253@hotmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"golang.org/x/net/idna"
|
||||
|
||||
"../json-dns"
|
||||
"github.com/gorilla/handlers"
|
||||
"github.com/miekg/dns"
|
||||
"../json-dns"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
conf *config
|
||||
udpClient *dns.Client
|
||||
tcpClient *dns.Client
|
||||
servemux *http.ServeMux
|
||||
conf *config
|
||||
udpClient *dns.Client
|
||||
tcpClient *dns.Client
|
||||
servemux *http.ServeMux
|
||||
}
|
||||
|
||||
type DNSRequest struct {
|
||||
request *dns.Msg
|
||||
response *dns.Msg
|
||||
isTailored bool
|
||||
errcode int
|
||||
errtext string
|
||||
}
|
||||
|
||||
func NewServer(conf *config) (s *Server) {
|
||||
s = &Server {
|
||||
s = &Server{
|
||||
conf: conf,
|
||||
udpClient: &dns.Client {
|
||||
Net: "udp",
|
||||
udpClient: &dns.Client{
|
||||
Net: "udp",
|
||||
Timeout: time.Duration(conf.Timeout) * time.Second,
|
||||
},
|
||||
tcpClient: &dns.Client {
|
||||
Net: "tcp",
|
||||
tcpClient: &dns.Client{
|
||||
Net: "tcp",
|
||||
Timeout: time.Duration(conf.Timeout) * time.Second,
|
||||
},
|
||||
servemux: http.NewServeMux(),
|
||||
@@ -71,151 +77,76 @@ func (s *Server) Start() error {
|
||||
}
|
||||
if s.conf.Cert != "" || s.conf.Key != "" {
|
||||
return http.ListenAndServeTLS(s.conf.Listen, s.conf.Cert, s.conf.Key, servemux)
|
||||
} else {
|
||||
return http.ListenAndServe(s.conf.Listen, servemux)
|
||||
}
|
||||
return http.ListenAndServe(s.conf.Listen, servemux)
|
||||
}
|
||||
|
||||
func (s *Server) handlerFunc(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
|
||||
w.Header().Set("Server", "DNS-over-HTTPS/1.0 (+https://github.com/m13253/dns-over-https)")
|
||||
w.Header().Set("X-Powered-By", "DNS-over-HTTPS/1.0 (+https://github.com/m13253/dns-over-https)")
|
||||
|
||||
name := r.FormValue("name")
|
||||
if name == "" {
|
||||
jsonDNS.FormatError(w, "Invalid argument value: \"name\"", 400)
|
||||
return
|
||||
if r.Form == nil {
|
||||
const maxMemory = 32 << 20 // 32 MB
|
||||
r.ParseMultipartForm(maxMemory)
|
||||
}
|
||||
name = strings.ToLower(name)
|
||||
if punycode, err := idna.ToASCII(name); err == nil {
|
||||
name = punycode
|
||||
} else {
|
||||
jsonDNS.FormatError(w, fmt.Sprintf("Invalid argument value: \"name\" = %q (%s)", name, err.Error()), 400)
|
||||
return
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
if ct := r.FormValue("ct"); ct != "" {
|
||||
contentType = ct
|
||||
}
|
||||
|
||||
rrTypeStr := r.FormValue("type")
|
||||
rrType := uint16(1)
|
||||
if rrTypeStr == "" {
|
||||
} else if v, err := strconv.ParseUint(rrTypeStr, 10, 16); err == nil {
|
||||
rrType = uint16(v)
|
||||
} else if v, ok := dns.StringToType[strings.ToUpper(rrTypeStr)]; ok {
|
||||
rrType = v
|
||||
} else {
|
||||
jsonDNS.FormatError(w, fmt.Sprintf("Invalid argument value: \"type\" = %q", rrTypeStr), 400)
|
||||
return
|
||||
}
|
||||
|
||||
cdStr := r.FormValue("cd")
|
||||
cd := false
|
||||
if cdStr == "1" || cdStr == "true" {
|
||||
cd = true
|
||||
} else if cdStr == "0" || cdStr == "false" || cdStr == "" {
|
||||
} else {
|
||||
jsonDNS.FormatError(w, fmt.Sprintf("Invalid argument value: \"cd\" = %q", cdStr), 400)
|
||||
return
|
||||
}
|
||||
|
||||
ednsClientSubnet := r.FormValue("edns_client_subnet")
|
||||
ednsClientFamily := uint16(0)
|
||||
ednsClientAddress := net.IP(nil)
|
||||
ednsClientNetmask := uint8(255)
|
||||
if ednsClientSubnet != "" {
|
||||
if ednsClientSubnet == "0/0" {
|
||||
ednsClientSubnet = "0.0.0.0/0"
|
||||
if contentType == "" {
|
||||
// Guess request Content-Type based on other parameters
|
||||
if r.FormValue("name") != "" {
|
||||
contentType = "application/x-www-form-urlencoded"
|
||||
} else if r.FormValue("dns") != "" {
|
||||
contentType = "application/dns-udpwireformat"
|
||||
}
|
||||
slash := strings.IndexByte(ednsClientSubnet, '/')
|
||||
if slash < 0 {
|
||||
ednsClientAddress = net.ParseIP(ednsClientSubnet)
|
||||
if ednsClientAddress == nil {
|
||||
jsonDNS.FormatError(w, fmt.Sprintf("Invalid argument value: \"edns_client_subnet\" = %q", ednsClientSubnet), 400)
|
||||
return
|
||||
}
|
||||
if ipv4 := ednsClientAddress.To4(); ipv4 != nil {
|
||||
ednsClientFamily = 1
|
||||
ednsClientAddress = ipv4
|
||||
ednsClientNetmask = 24
|
||||
} else {
|
||||
ednsClientFamily = 2
|
||||
ednsClientNetmask = 48
|
||||
}
|
||||
} else {
|
||||
ednsClientAddress = net.ParseIP(ednsClientSubnet[:slash])
|
||||
if ednsClientAddress == nil {
|
||||
jsonDNS.FormatError(w, fmt.Sprintf("Invalid argument value: \"edns_client_subnet\" = %q", ednsClientSubnet), 400)
|
||||
return
|
||||
}
|
||||
if ipv4 := ednsClientAddress.To4(); ipv4 != nil {
|
||||
ednsClientFamily = 1
|
||||
ednsClientAddress = ipv4
|
||||
} else {
|
||||
ednsClientFamily = 2
|
||||
}
|
||||
netmask, err := strconv.ParseUint(ednsClientSubnet[slash + 1:], 10, 8)
|
||||
if err != nil {
|
||||
jsonDNS.FormatError(w, fmt.Sprintf("Invalid argument value: \"edns_client_subnet\" = %q (%s)", ednsClientSubnet, err.Error()), 400)
|
||||
return
|
||||
}
|
||||
ednsClientNetmask = uint8(netmask)
|
||||
}
|
||||
var responseType string
|
||||
for _, responseCandidate := range strings.Split(r.Header.Get("Accept"), ",") {
|
||||
responseCandidate = strings.ToLower(strings.SplitN(responseCandidate, ";", 2)[0])
|
||||
if responseCandidate == "application/json" {
|
||||
responseType = "application/json"
|
||||
break
|
||||
} else if responseCandidate == "application/dns-udpwireformat" {
|
||||
responseType = "application/dns-udpwireformat"
|
||||
break
|
||||
}
|
||||
} else {
|
||||
ednsClientAddress = s.findClientIP(r)
|
||||
if ednsClientAddress == nil {
|
||||
ednsClientNetmask = 0
|
||||
} else if ipv4 := ednsClientAddress.To4(); ipv4 != nil {
|
||||
ednsClientFamily = 1
|
||||
ednsClientAddress = ipv4
|
||||
ednsClientNetmask = 24
|
||||
} else {
|
||||
ednsClientFamily = 2
|
||||
ednsClientNetmask = 48
|
||||
}
|
||||
if responseType == "" {
|
||||
// Guess response Content-Type based on request Content-Type
|
||||
if contentType == "application/x-www-form-urlencoded" {
|
||||
responseType = "application/json"
|
||||
} else if contentType == "application/dns-udpwireformat" {
|
||||
responseType = "application/dns-udpwireformat"
|
||||
}
|
||||
}
|
||||
|
||||
msg := new(dns.Msg)
|
||||
msg.SetQuestion(dns.Fqdn(name), rrType)
|
||||
msg.CheckingDisabled = cd
|
||||
opt := new(dns.OPT)
|
||||
opt.Hdr.Name = "."
|
||||
opt.Hdr.Rrtype = dns.TypeOPT
|
||||
opt.SetUDPSize(4096)
|
||||
opt.SetDo(true)
|
||||
if ednsClientAddress != nil {
|
||||
edns0Subnet := new(dns.EDNS0_SUBNET)
|
||||
edns0Subnet.Code = dns.EDNS0SUBNET
|
||||
edns0Subnet.Family = ednsClientFamily
|
||||
edns0Subnet.SourceNetmask = ednsClientNetmask
|
||||
edns0Subnet.SourceScope = 0
|
||||
edns0Subnet.Address = ednsClientAddress
|
||||
opt.Option = append(opt.Option, edns0Subnet)
|
||||
var req *DNSRequest
|
||||
if contentType == "application/x-www-form-urlencoded" {
|
||||
req = s.parseRequestGoogle(w, r)
|
||||
} else if contentType == "application/dns-udpwireformat" {
|
||||
req = s.parseRequestIETF(w, r)
|
||||
} else {
|
||||
jsonDNS.FormatError(w, fmt.Sprintf("Invalid argument value: \"ct\" = %q", contentType), 400)
|
||||
return
|
||||
}
|
||||
if req.errcode != 0 {
|
||||
jsonDNS.FormatError(w, req.errtext, req.errcode)
|
||||
return
|
||||
}
|
||||
msg.Extra = append(msg.Extra, opt)
|
||||
|
||||
resp, err := s.doDNSQuery(msg)
|
||||
var err error
|
||||
req.response, err = s.doDNSQuery(req.request)
|
||||
if err != nil {
|
||||
jsonDNS.FormatError(w, fmt.Sprintf("DNS query failure (%s)", err.Error()), 503)
|
||||
return
|
||||
}
|
||||
respJson := jsonDNS.Marshal(resp)
|
||||
respStr, err := json.Marshal(respJson)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
jsonDNS.FormatError(w, fmt.Sprintf("DNS packet parse failure (%s)", err.Error()), 500)
|
||||
return
|
||||
}
|
||||
|
||||
if respJson.HaveTTL {
|
||||
if ednsClientSubnet != "" {
|
||||
w.Header().Set("Cache-Control", "public, max-age=" + strconv.Itoa(int(respJson.LeastTTL)))
|
||||
} else {
|
||||
w.Header().Set("Cache-Control", "private, max-age=" + strconv.Itoa(int(respJson.LeastTTL)))
|
||||
}
|
||||
w.Header().Set("Expires", respJson.EarliestExpires.Format(http.TimeFormat))
|
||||
if contentType == "application/x-www-form-urlencoded" {
|
||||
s.generateResponseGoogle(w, r, req)
|
||||
} else if contentType == "application/dns-udpwireformat" {
|
||||
s.generateResponseIETF(w, r, req)
|
||||
}
|
||||
if respJson.Status == dns.RcodeServerFailure {
|
||||
w.WriteHeader(503)
|
||||
}
|
||||
w.Write(respStr)
|
||||
}
|
||||
|
||||
func (s *Server) findClientIP(r *http.Request) net.IP {
|
||||
@@ -248,9 +179,9 @@ func (s *Server) findClientIP(r *http.Request) net.IP {
|
||||
}
|
||||
|
||||
func (s *Server) doDNSQuery(msg *dns.Msg) (resp *dns.Msg, err error) {
|
||||
num_servers := len(s.conf.Upstream)
|
||||
numServers := len(s.conf.Upstream)
|
||||
for i := uint(0); i < s.conf.Tries; i++ {
|
||||
server := s.conf.Upstream[rand.Intn(num_servers)]
|
||||
server := s.conf.Upstream[rand.Intn(numServers)]
|
||||
if !s.conf.TCPOnly {
|
||||
resp, _, err = s.udpClient.Exchange(msg, server)
|
||||
if err == dns.ErrTruncated {
|
||||
|
||||
Reference in New Issue
Block a user