diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..62c8935
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+.idea/
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..4e21f3c
--- /dev/null
+++ b/README.md
@@ -0,0 +1,76 @@
+# Go DANE
+
+**Note: Go DANE is still under development, use at your own risk.**
+
+
+Go DANE enables the use of DANE/TLSA in browsers using a simple proxy. It currently supports [DANE](https://tools.ietf.org/html/rfc6698) EE(3), and works with self-signed certificates.
+
+
+
+
+
+
+
+
+## How it works
+
+Go DANE mitms HTTPS for sites that support DANE. It requires one root CA to be installed locally. Go DANE will use the root CA to create certificates on the fly if it was able to verify DANE/TLSA.
+It won't mitm sites that don't use DANE/TLSA and will serve their original certificate instead.
+
+
+## Usage
+
+Download the latest pre-built binary for your OS from [releases](https://github.com.) and run
+
+
+ ./godane -dns tls://1.1.1.1
+
+* Add Go DANE proxy to your web browser `127.0.0.1:8080` (see [Firefox instructions](doc/firefox.md)). Make sure to add it for HTTPS as well.
+
+* Visit `http://godane.test` and click install certificate.
+
+
+
+Note: When you run Go DANE for the first time, it will generate a root CA and store it in `~/.godane`.
+The easiest way to try it out is to use Firefox because it supports adding a proxy natively and has a built in CA store so that you don't have to add the root CA or proxy to your whole OS (it's still experimental).
+
+#### Some sites that currently use DANE-EE(3):
+* FreeBSD: https://freebsd.org
+
+* Tor Project: https://torproject.org
+
+* Kumari https://www.kumari.net/
+
+and more?
+
+### Go DANE with handshake.org
+
+If you're running a local hsd node listening for dns queries:
+
+ ./godane -dns udp://:53
+
+You can also use [easyhandshake](https://easyhandshake.com) resolver.
+
+ ./godane -dns https://easyhandshake.com:8053
+
+
+Note: You can configure hsd to use a different port if 53 is in use.
+
+## Use of resolvers
+
+Go DANE doesn't perform DNSSEC verficiation by itself. The resolver you specify must be DNSSEC capable. If you have a local resolver that is DNSSEC capable, you can use udp or tcp. If not, please use a trusted resolver that supports DNSSEC and uses DOT or DOH.
+
+Note: Go DANE will ignore TLSA responses that don't come with the [Authenticaed Data (AD)](https://tools.ietf.org/html/rfc3655) flag.
+
+## Why?
+
+I wanted to use DANE/TLSA, but no browser currently supports it. Also, it appears that it's [not possible](https://www.dnssec-validator.cz/) to support it via an extension. So this seemed like a fun idea to try, and with [martian](https://github.com/google/martian), it was pretty easy.
+
+
+
+## Contributing
+
+Contributions are welcome!
+
+
+
diff --git a/cache.go b/cache.go
new file mode 100644
index 0000000..9314dd8
--- /dev/null
+++ b/cache.go
@@ -0,0 +1,59 @@
+package godane
+
+import (
+ "github.com/miekg/dns"
+ "sync"
+ "time"
+)
+
+type entry struct {
+ msg []dns.RR
+ ttl time.Time
+}
+
+type cache struct {
+ m map[string]*entry
+ maxN int
+
+ sync.RWMutex
+}
+
+func newCache(maxN int) (m *cache) {
+ return &cache{m: make(map[string]*entry), maxN: maxN}
+}
+
+func (c *cache) set(key string, item *entry) {
+ c.Lock()
+ defer c.Unlock()
+
+ if c.maxN == len(c.m) {
+ for k := range c.m {
+ delete(c.m, k)
+ break
+ }
+ }
+
+ c.m[key] = item
+}
+
+func (c *cache) get(key string) (*entry, bool) {
+ c.RLock()
+ defer c.RUnlock()
+
+ i, ok := c.m[key]
+ return i, ok
+}
+
+func (c *cache) remove(key string) {
+ c.Lock()
+ defer c.Unlock()
+
+ delete(c.m, key)
+}
+
+func (c *cache) len() int {
+ c.RLock()
+ defer c.RUnlock()
+
+ return len(c.m)
+}
diff --git a/cache_test.go b/cache_test.go
new file mode 100644
index 0000000..8dbbf5a
--- /dev/null
+++ b/cache_test.go
@@ -0,0 +1,25 @@
+package godane
+
+import (
+ "fmt"
+ "testing"
+)
+
+func TestCache(t *testing.T) {
+ maxCache := 10
+ c := newCache(maxCache)
+
+ for i := 0; i < 30; i++ {
+ c.set(fmt.Sprintf("test%d", i), &entry{})
+ }
+
+ _, ok := c.get("test29")
+
+ if !ok {
+ t.Fatal("want key `test29`")
+ }
+
+ if c.len() > maxCache {
+ t.Fatalf("want cache len = %d, got %d", maxCache, c.len())
+ }
+}
diff --git a/cmd/godane/main.go b/cmd/godane/main.go
new file mode 100644
index 0000000..8b85909
--- /dev/null
+++ b/cmd/godane/main.go
@@ -0,0 +1,326 @@
+package main
+
+import (
+ "bytes"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/pem"
+ "flag"
+ "github.com/google/martian/v3"
+ mapi "github.com/google/martian/v3/api"
+ "github.com/google/martian/v3/fifo"
+ "github.com/google/martian/v3/httpspec"
+ "github.com/google/martian/v3/martianhttp"
+ "github.com/google/martian/v3/mitm"
+ "github.com/google/martian/v3/servemux"
+ "godane"
+ "html/template"
+ "io/ioutil"
+ "log"
+ "net"
+ "net/http"
+ "os"
+ "path"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var (
+ resolver = flag.String("dns", "tls://1.1.1.1", "dns resolver udp://, tcp://, tls:// or https://")
+ conf = flag.String("dir", "", "dir path to store configuration (default: ~/.godane)")
+ addr = flag.String("addr", ":8080", "host:port of the proxy")
+ apiAddr = flag.String("api-addr", ":8181", "host:port of the configuration api")
+ cert = flag.String("cert", "", "filepath to the CA (leave empty to auto generate)")
+ key = flag.String("key", "", "filepath to the private key of the CA")
+ validity = flag.Duration("validity", time.Hour, "window of time generated DANE certificates are valid")
+)
+
+var badGatewayTmpl = `
+
+
+
+
+
+
+
+
HTTP 502 - Bad Gateway
An error occurred while making this request:
+
`
+
+var daneSetupTmpl = `
+
+
+
+
+
+
+
+
Go DANE Setup
+
Install Certificate
+
The root CA has been generated and stored at {{.CertPath}}
.
+
+
Add this certificate to your browser's trusted root certificates. It will be used to generate certificates for websites that use DANE.
+
+
Install Certificate
+
+
+
+
+`
+
+const certEndpoint = "/authority.cer"
+const godaneHost = "godane.test"
+
+var indexTmpl *template.Template
+
+type indexTmplData struct {
+ CertPath string
+ CertURL string
+}
+
+func getConfPath() string {
+ if *conf != "" {
+ return *conf
+ }
+
+ home, err := os.UserHomeDir()
+ if err != nil {
+ log.Fatalf("failed to get home dir: %v", err)
+ }
+
+ p := path.Join(home, ".godane")
+
+ if _, err := os.Stat(p); err != nil {
+ if err := os.Mkdir(p, 0700); err != nil {
+ log.Fatalf("failed to create conf dir: %v", err)
+ }
+ }
+
+ return p
+}
+
+func generateCA() (string, string) {
+ if *cert != "" && *key != "" {
+ return *cert, *key
+ }
+
+ p := getConfPath()
+ ca, priv, err := mitm.NewAuthority("DNSSEC", "DNSSEC", 365*24*time.Hour)
+ if err != nil {
+ log.Fatalf("couldn't generate CA: %v", err)
+ }
+
+ certPath := path.Join(p, "cert.crt")
+ keyPath := path.Join(p, "cert.key")
+
+ if _, err := os.Stat(certPath); err != nil {
+
+ cOut, err := os.Create(certPath)
+ if err != nil {
+ log.Fatalf("couldn't create CA file: %v", err)
+ }
+
+ // pem encode
+ pem.Encode(cOut, &pem.Block{
+ Type: "CERTIFICATE",
+ Bytes: ca.Raw,
+ })
+
+ if err := cOut.Close(); err != nil {
+ log.Fatalf("couldn't close CA file: %v", err)
+ }
+
+ kOut, err := os.Create(keyPath)
+ if err != nil {
+ log.Fatalf("couldn't create CA key file: %v", err)
+ }
+
+ pem.Encode(kOut, &pem.Block{
+ Type: "RSA PRIVATE KEY",
+ Bytes: x509.MarshalPKCS1PrivateKey(priv),
+ })
+
+ if err := kOut.Close(); err != nil {
+ log.Fatalf("couldn't close CA key file: %v", err)
+ }
+ }
+
+ return certPath, keyPath
+}
+
+func setupMITM(p *martian.Proxy, mux *http.ServeMux, rs godane.Resolver) {
+ var x509c *x509.Certificate
+ var priv interface{}
+
+ *cert, *key = generateCA()
+ if *cert != "" && *key != "" {
+ tlsc, err := tls.LoadX509KeyPair(*cert, *key)
+ if err != nil {
+ log.Fatal(err)
+ }
+ priv = tlsc.PrivateKey
+
+ x509c, err = x509.ParseCertificate(tlsc.Certificate[0])
+ if err != nil {
+ log.Fatal(err)
+ }
+ }
+
+ if x509c != nil && priv != nil {
+ mc, err := mitm.NewConfig(x509c, priv)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ mc.SetValidity(*validity)
+ mc.SetOrganization("DNSSEC")
+ p.SetMITM(mc)
+ p.SkipMITM(func(req *http.Request) bool {
+ prefix := godane.GetTLSAPrefix(req.Host)
+ if ans, err := rs.LookupTLSA(prefix); err == nil && godane.TLSASupported(ans) {
+ return false
+ }
+ return true
+ })
+
+ // Expose certificate authority.
+ ah := martianhttp.NewAuthorityHandler(x509c)
+ configure(certEndpoint, ah, mux)
+ configure("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ indexTmpl.Execute(w, indexTmplData{
+ CertPath: *cert,
+ CertURL: "http://" + path.Join(godaneHost, certEndpoint),
+ })
+ }), mux)
+ }
+}
+
+func main() {
+ p := martian.NewProxy()
+ defer p.Close()
+
+ rs, err := godane.NewResolver(*resolver)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ tr := godane.RoundTripper(rs)
+ p.SetRoundTripper(tr)
+ p.SetDial(godane.GetDialFunc(rs))
+
+ mux := http.NewServeMux()
+ setupMITM(p, mux, rs)
+
+ // Note: this part uses the same forwarding logic in the original martian proxy[0]
+ // to handle requests for http://godane.test
+ // [0]: https://github.com/google/martian/blob/master/cmd/proxy/main.go
+
+ stack, fg := httpspec.NewStack("martian")
+
+ // wrap stack in a group so that we can forward API requests to the API port
+ // before the httpspec modifiers which include the via modifier which will
+ // trip loop detection
+ topg := fifo.NewGroup()
+
+ // Redirect API traffic to API server.
+ if *apiAddr != "" {
+ apip := strings.Replace(*apiAddr, ":", "", 1)
+ port, err := strconv.Atoi(apip)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ // Forward traffic that pattern matches in http.DefaultServeMux
+ apif := servemux.NewFilter(mux)
+ apif.SetRequestModifier(mapi.NewForwarder("", port))
+ topg.AddRequestModifier(apif)
+ }
+ topg.AddRequestModifier(stack)
+ topg.AddResponseModifier(stack)
+ topg.AddResponseModifier(martian.ResponseModifierFunc(func(res *http.Response) error {
+ if res.StatusCode == 502 {
+ // format:199 "martian" "error message" "date"
+ w := strings.TrimSpace(res.Header.Get("Warning"))
+ p := strings.Split(w, `"`)
+ if len(p) != 7 {
+ return nil
+ }
+
+ msg := p[3]
+ raw := []byte(badGatewayTmpl + msg)
+ res.ContentLength = int64(len(raw))
+ res.Header.Set("Content-Length", strconv.Itoa(len(raw)))
+ res.Body = ioutil.NopCloser(bytes.NewReader(raw))
+ }
+
+ return nil
+ }))
+
+ p.SetRequestModifier(topg)
+ p.SetResponseModifier(topg)
+
+ m := martianhttp.NewModifier()
+ fg.AddRequestModifier(m)
+ fg.AddResponseModifier(m)
+
+ l, err := net.Listen("tcp", *addr)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ lAPI, err := net.Listen("tcp", *apiAddr)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ log.Printf("godane: starting proxy on %s and api on %s", l.Addr().String(), lAPI.Addr().String())
+
+ go p.Serve(l)
+ http.Serve(lAPI, mux)
+}
+
+func init() {
+ var err error
+ indexTmpl, err = template.New("index").Parse(daneSetupTmpl)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ martian.Init()
+}
+
+// configure installs a configuration handler at path.
+func configure(pattern string, handler http.Handler, mux *http.ServeMux) {
+ // register handler for godane.test
+ mux.Handle(godaneHost+pattern, handler)
+
+ // register handler for local server
+ p := path.Join("localhost"+*apiAddr, pattern)
+ mux.Handle(p, handler)
+}
diff --git a/doc/firefox.md b/doc/firefox.md
new file mode 100644
index 0000000..53b5f88
--- /dev/null
+++ b/doc/firefox.md
@@ -0,0 +1,16 @@
+# Use Go DANE with Firefox
+
+Go to Preferences -> Network Settings
+
+Add the proxy for http and https. Click ok.
+
+![Firefox Proxy Settings](network-settings.png)
+
+
+Visit `http://godane.test` and click install certificate.
+
+![godane.test install certificate](godane.test.png)
+
+
+
+That's it. You can now visit sites that use DANE.
\ No newline at end of file
diff --git a/doc/godane.test.png b/doc/godane.test.png
new file mode 100644
index 0000000..00dadd2
Binary files /dev/null and b/doc/godane.test.png differ
diff --git a/doc/network-settings.png b/doc/network-settings.png
new file mode 100644
index 0000000..6647470
Binary files /dev/null and b/doc/network-settings.png differ
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..914a521
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,10 @@
+module godane
+
+go 1.13
+
+replace github.com/google/martian/v3 => github.com/buffrr/martian/v3 v3.0.1-0.20200408012421-ffcd9db35185
+
+require (
+ github.com/google/martian/v3 v3.0.0
+ github.com/miekg/dns v1.1.29
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..51993d5
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,21 @@
+github.com/buffrr/martian/v3 v3.0.1-0.20200408012421-ffcd9db35185 h1:sFbj1GreDVRAFz0NYPG5UkPVdffmqFvsDa+INlkJ5Mo=
+github.com/buffrr/martian/v3 v3.0.1-0.20200408012421-ffcd9db35185/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
+github.com/miekg/dns v1.1.29 h1:xHBEhR+t5RzcFJjBLJlax2daXOrTYtr9z4WdKEfWFzg=
+github.com/miekg/dns v1.1.29/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8=
+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
+golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20190923162816-aa69164e4478 h1:l5EDrHhldLYb3ZRHDUhXF7Om7MvYXnkV9/iQNo1lX6g=
+golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe h1:6fAMxZRR6sl1Uq8U61gxU+kPTs2tR8uOySCbBP7BN/M=
+golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
+golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
diff --git a/resolver.go b/resolver.go
new file mode 100644
index 0000000..a815556
--- /dev/null
+++ b/resolver.go
@@ -0,0 +1,324 @@
+package godane
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "github.com/miekg/dns"
+ "io/ioutil"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Resolver looks up names
+type Resolver interface {
+ LookupIP(string) ([]net.IP, error)
+ LookupTLSA(string) ([]dns.TLSA, error)
+}
+
+// ClientResolver implements Resolver and caches queries.
+type ClientResolver struct {
+ rrCache map[uint16]*cache
+ client *dns.Client
+ protocol string
+ address string
+}
+
+const (
+ minTTL = 10 * time.Second
+ maxTTL = 3 * time.Hour
+ // max cache len for each rr type
+ maxCache = 10000
+)
+
+// NewResolver creates a new resolver
+// the server can be specified using udp://, tcp://, tls:// or https://
+func NewResolver(server string) (*ClientResolver, error) {
+ address, protocol, err := parseAddress(server)
+ if err != nil {
+ return nil, err
+ }
+
+ client := new(dns.Client)
+ client.Net = protocol
+ rrCache := make(map[uint16]*cache)
+ rrCache[dns.TypeA] = newCache(maxCache)
+ rrCache[dns.TypeAAAA] = newCache(maxCache)
+ rrCache[dns.TypeTLSA] = newCache(maxCache)
+
+ return &ClientResolver{
+ rrCache: rrCache,
+ client: client,
+ protocol: protocol,
+ address: address,
+ }, nil
+}
+
+func parseAddress(server string) (string, string, error) {
+ u, err := url.Parse(server)
+ if err != nil {
+ return "", "", fmt.Errorf("dns: couldn't parse server address: %v", err)
+ }
+
+ var p, defaultPort string
+ host := u.Host
+
+ switch u.Scheme {
+ case "udp":
+ defaultPort = "53"
+ p = ""
+ case "tcp":
+ p = u.Scheme
+ defaultPort = "53"
+ case "tls":
+ p = "tcp-tls"
+ defaultPort = "853"
+ case "https":
+ p = u.Scheme
+ host = u.Scheme + "://" + u.Host
+ default:
+ return "", "", fmt.Errorf("dns: unsupported scheme %s", u.Scheme)
+ }
+
+ _, _, err = net.SplitHostPort(u.Host)
+ if err != nil && u.Scheme != "https" {
+ return net.JoinHostPort(host, defaultPort), p, nil
+ }
+
+ return host, p, nil
+
+}
+
+func (rs *ClientResolver) exchange(m *dns.Msg) (r *dns.Msg, rtt time.Duration, err error) {
+ if rs.protocol == "https" {
+ return rs.exchangeDOH(m)
+ }
+ return rs.client.Exchange(m, rs.address)
+}
+
+func (rs *ClientResolver) exchangeDOH(m *dns.Msg) (r *dns.Msg, rtt time.Duration, err error) {
+ buf, err := m.Pack()
+ if err != nil {
+ return nil, 0, err
+ }
+
+ req, err := http.NewRequest(http.MethodPost, rs.address+"/dns-query", bytes.NewReader(buf))
+ if err != nil {
+ return nil, 0, err
+ }
+
+ req.Header.Set("content-type", "application/dns-message")
+ req.Header.Set("accept", "application/dns-message")
+
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, 0, fmt.Errorf("dns: %s", resp.Status)
+ }
+
+ defer resp.Body.Close()
+ b, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ ans := new(dns.Msg)
+ err = ans.Unpack(b)
+
+ return ans, 0, err
+}
+
+func (rs *ClientResolver) checkCache(key string, qtype uint16) (*entry, bool) {
+ if ans, ok := rs.rrCache[qtype].get(key); ok {
+ if time.Now().Before(ans.ttl) {
+ return ans, true
+ }
+
+ rs.rrCache[qtype].remove(key)
+ }
+
+ return nil, false
+}
+
+// LookupIP looks up host using the specified resolver.
+// It returns a slice of that host's IPv4 and IPv6 addresses.
+func (rs *ClientResolver) LookupIP(hostname string) ([]net.IP, error) {
+ ip := net.ParseIP(hostname)
+ if ip != nil {
+ return []net.IP{ip}, nil
+ }
+
+ if !shouldResolve(hostname) {
+ return net.LookupIP(hostname)
+ }
+
+ var wg sync.WaitGroup
+ var ipv4, ipv6 []net.IP
+ var err1, err2 error
+
+ wg.Add(2)
+ go func() {
+ ipv4, err1 = rs.lookupIPv4(hostname)
+ wg.Done()
+ }()
+
+ go func() {
+ ipv6, err2 = rs.lookupIPv4(hostname)
+ wg.Done()
+ }()
+
+ wg.Wait()
+
+ if err1 != nil {
+ return nil, err1
+ }
+
+ if err2 != nil {
+ return nil, err2
+ }
+
+ return append(ipv4, ipv6...), nil
+}
+
+func (rs *ClientResolver) lookupIPv4(hostname string) ([]net.IP, error) {
+ rr, err := rs.lookup(hostname, dns.TypeA)
+ if err != nil {
+ return nil, err
+ }
+ var ips []net.IP
+ for _, r := range rr {
+ switch t := r.(type) {
+ case *dns.A:
+ ips = append(ips, t.A)
+ }
+ }
+ return ips, nil
+}
+
+func (rs *ClientResolver) lookupIPv6(hostname string) ([]net.IP, error) {
+ rr, err := rs.lookup(hostname, dns.TypeAAAA)
+ if err != nil {
+ return nil, err
+ }
+ var ips []net.IP
+ for _, r := range rr {
+ switch t := r.(type) {
+ case *dns.AAAA:
+ ips = append(ips, t.AAAA)
+ }
+ }
+ return ips, nil
+}
+
+// LookupTLSA returns TLSA records for the given TLSA prefix.
+func (rs *ClientResolver) LookupTLSA(prefix string) ([]dns.TLSA, error) {
+ rr, err := rs.lookup(prefix, dns.TypeTLSA)
+ if err != nil {
+ return nil, err
+ }
+
+ var tr []dns.TLSA
+ for _, r := range rr {
+ switch t := r.(type) {
+ case *dns.TLSA:
+ tr = append(tr, *t)
+ }
+ }
+
+ return tr, nil
+}
+
+func (rs *ClientResolver) lookup(name string, qtype uint16) ([]dns.RR, error) {
+ if ans, ok := rs.checkCache(name, qtype); ok {
+ return ans.msg, nil
+ }
+
+ m := new(dns.Msg)
+ m.SetQuestion(dns.Fqdn(name), qtype)
+ m.RecursionDesired = true
+ m.AuthenticatedData = true
+
+ r, _, err := rs.exchange(m)
+ if err != nil {
+ return nil, err
+ }
+
+ if r.Truncated {
+ return nil, errors.New("dns: response truncated")
+ }
+
+ if qtype == dns.TypeTLSA && !r.AuthenticatedData {
+ return nil, errors.New("dns: resolver didn't confirm msg (no ad flag)")
+ }
+
+ e := &entry{
+ msg: r.Answer,
+ ttl: time.Now().Add(getMinTTL(r)),
+ }
+
+ rs.rrCache[qtype].set(name, e)
+
+ return r.Answer, nil
+}
+
+// getMinTTL get the ttl for dns msg
+// borrowed from coredns: https://github.com/coredns/coredns/blob/master/plugin/pkg/dnsutil/ttl.go
+func getMinTTL(m *dns.Msg) time.Duration {
+ // No records or OPT is the only record, return a short ttl as a fail safe.
+ if len(m.Answer)+len(m.Ns) == 0 &&
+ (len(m.Extra) == 0 || (len(m.Extra) == 1 && m.Extra[0].Header().Rrtype == dns.TypeOPT)) {
+ return minTTL
+ }
+
+ minTTL := maxTTL
+ for _, r := range m.Answer {
+ if r.Header().Ttl < uint32(minTTL.Seconds()) {
+ minTTL = time.Duration(r.Header().Ttl) * time.Second
+ }
+ }
+ for _, r := range m.Ns {
+ if r.Header().Ttl < uint32(minTTL.Seconds()) {
+ minTTL = time.Duration(r.Header().Ttl) * time.Second
+ }
+ }
+
+ for _, r := range m.Extra {
+ if r.Header().Rrtype == dns.TypeOPT {
+ // OPT records use TTL field for extended rcode and flags
+ continue
+ }
+ if r.Header().Ttl < uint32(minTTL.Seconds()) {
+ minTTL = time.Duration(r.Header().Ttl) * time.Second
+ }
+ }
+ return minTTL
+}
+
+func shouldResolve(hostname string) bool {
+ var tld string
+
+ index := strings.LastIndex(hostname, ".")
+ if index == -1 {
+ tld = hostname
+ } else {
+ tld = hostname[index+1:]
+ }
+
+ return tld != "test" && tld != "example" && tld != "invalid" && tld != "localhost"
+}
+
+// GetTLSAPrefix returns the TLSA prefix for the given host:port
+func GetTLSAPrefix(host string) string {
+ h, p, err := net.SplitHostPort(host)
+ if err != nil {
+ return host
+ }
+ return fmt.Sprintf("_%s._tcp.%s", p, h)
+}
diff --git a/resolver_test.go b/resolver_test.go
new file mode 100644
index 0000000..1c4f922
--- /dev/null
+++ b/resolver_test.go
@@ -0,0 +1,89 @@
+package godane
+
+import (
+ "github.com/miekg/dns"
+ "reflect"
+ "sync"
+ "testing"
+)
+
+func TestNewResolver(t *testing.T) {
+ t.Parallel()
+ var wg sync.WaitGroup
+ protos := []string{"udp", "tcp", "tls", "https"}
+ wg.Add(len(protos))
+ for _, p := range protos {
+ go func(proto string) {
+ defer wg.Done()
+
+ rs, err := NewResolver(proto + "://1.1.1.1")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ ips, err := rs.lookupIPv4("ip.godane.buffrr.dev")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if len(ips) == 0 {
+ t.Fatalf("got no ips")
+ }
+ }(p)
+ }
+
+ wg.Wait()
+
+ _, err := NewResolver("udp://:53")
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDNS_LookupIP(t *testing.T) {
+ t.Parallel()
+ rs, err := NewResolver("udp://8.8.8.8")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ ips, err := rs.LookupIP("ip.godane.buffrr.dev")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if len(ips) != 4 {
+ t.Fatalf("want 4 ips, got %d ips", len(ips))
+ }
+
+ _, err = rs.LookupIP("ip.godane.invalid")
+ if err == nil {
+ t.Fatal("want error, got nil")
+ }
+}
+
+var tlsaRRs = []dns.TLSA{
+ {
+ Usage: 3,
+ Selector: 1,
+ MatchingType: 1,
+ Certificate: "781c71783fcd0d2c4b4b82ae7636fef5d0de94f99ce6192afdf2640357835e0b",
+ },
+}
+
+func TestDNS_LookupTLSA(t *testing.T) {
+ t.Parallel()
+ d, _ := NewResolver("tls://9.9.9.9")
+ r, _ := d.LookupTLSA("tlsa.godane.buffrr.dev")
+
+ if len(r) != 1 {
+ t.Fatalf("want 1, got %d", len(r))
+ }
+
+ r[0].Hdr = tlsaRRs[0].Hdr
+
+ if !reflect.DeepEqual(r[0], tlsaRRs[0]) {
+ t.Fatalf("want %v, got %v", tlsaRRs[0], r[0])
+ }
+
+}
diff --git a/screenshot.png b/screenshot.png
new file mode 100644
index 0000000..399bed4
Binary files /dev/null and b/screenshot.png differ
diff --git a/transport.go b/transport.go
new file mode 100644
index 0000000..e327c27
--- /dev/null
+++ b/transport.go
@@ -0,0 +1,175 @@
+package godane
+
+import (
+ "context"
+ "crypto/tls"
+ "crypto/x509"
+ "errors"
+ "fmt"
+ "github.com/miekg/dns"
+ "net"
+ "net/http"
+ "time"
+)
+
+// Timeouts used in the dialer and http transport.
+const (
+ Timeout = 30 * time.Second
+ KeepAlive = 30 * time.Second
+ TLSHandshakeTimeout = 10 * time.Second
+ ExpectContinueTimeout = time.Second
+)
+
+var dialer = net.Dialer{
+ Timeout: Timeout,
+ KeepAlive: KeepAlive,
+}
+
+// RoundTripper returns a round tripper capable of performing DANE/TLSA
+// verification. Uses the given resolver for dns lookups.
+func RoundTripper(rs Resolver) http.RoundTripper {
+ return &http.Transport{
+ DialContext: func(ctx context.Context, network, addr string) (conn net.Conn, err error) {
+ return dialContext(ctx, network, addr, rs)
+ },
+ DialTLS: func(network, address string) (net.Conn, error) {
+ tlsa := GetTLSAPrefix(address)
+ if ans, err := rs.LookupTLSA(tlsa); err == nil && TLSASupported(ans) {
+ tlsConfig := newTLSVerifyConfig(ans)
+ return dialTLS(network, address, tlsConfig, rs)
+ }
+
+ return dialTLS(network, address, &tls.Config{InsecureSkipVerify: false}, rs)
+ },
+ TLSHandshakeTimeout: TLSHandshakeTimeout,
+ ExpectContinueTimeout: ExpectContinueTimeout,
+ }
+
+}
+
+// TLSASupported checks if DANE usage is supported
+// for the given TLSA records. currently checks for usage EE(3).
+func TLSASupported(rrs []dns.TLSA) bool {
+ for _, rr := range rrs {
+ if rr.Usage == 3 {
+ return true
+ }
+ }
+ return false
+}
+
+func newTLSVerifyConfig(rrs []dns.TLSA) *tls.Config {
+ return &tls.Config{
+ InsecureSkipVerify: true,
+ VerifyPeerCertificate: getTLSAValidator(rrs),
+ }
+}
+
+func getTLSAValidator(rrs []dns.TLSA) func([][]byte, [][]*x509.Certificate) error {
+ return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
+ certs := make([]*x509.Certificate, len(rawCerts))
+ for i, asn1Data := range rawCerts {
+ cert, err := x509.ParseCertificate(asn1Data)
+ if err != nil {
+ return errors.New("tls: failed to parse certificate from server: " + err.Error())
+ }
+ certs[i] = cert
+ }
+
+ // TLSA verification.
+ // Currently, supports DANE-EE(3). We only need to check the leaf certificate.
+ // https://tools.ietf.org/id/draft-ietf-dane-ops-02.html#type3
+ // https://tools.ietf.org/html/rfc6698
+ for _, t := range rrs {
+ if t.Usage != 3 {
+ continue
+ }
+
+ if err := t.Verify(certs[0]); err == nil {
+ return nil
+ }
+ }
+
+ return errors.New("tls: DANE verification failed")
+ }
+}
+
+// GetDialFunc returns a dial function that uses the given resolver.
+func GetDialFunc(rs Resolver) func(network string, addr string) (net.Conn, error) {
+ return func(network string, addr string) (net.Conn, error) {
+ _, port, ips, err := readAddr(addr, rs)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, ip := range ips {
+ ipaddr := net.JoinHostPort(ip.String(), port)
+ conn, err := dialer.Dial(network, ipaddr)
+ if err != nil {
+ continue
+ }
+ return conn, nil
+ }
+ return nil, fmt.Errorf("dial: could not reach %s", addr)
+ }
+}
+
+func dialContext(ctx context.Context, network, addr string, rs Resolver) (net.Conn, error) {
+ _, port, ips, err := readAddr(addr, rs)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, ip := range ips {
+ ipaddr := net.JoinHostPort(ip.String(), port)
+ conn, err := dialer.DialContext(ctx, network, ipaddr)
+ if err != nil {
+ continue
+ }
+ return conn, nil
+ }
+
+ return nil, fmt.Errorf("dial ctx: could not reach %s", addr)
+
+}
+
+func dialTLS(network, addr string, config *tls.Config, rs Resolver) (*tls.Conn, error) {
+ host, port, ips, err := readAddr(addr, rs)
+ if err != nil {
+ return nil, err
+ }
+
+ config.ServerName = host
+
+ for _, ip := range ips {
+ ipaddr := net.JoinHostPort(ip.String(), port)
+ conn, err := tls.Dial(network, ipaddr, config)
+ if err != nil {
+ continue
+ }
+ return conn, nil
+ }
+
+ return nil, fmt.Errorf("dial tls: could not reach %s", addr)
+
+}
+
+func readAddr(addr string, rs Resolver) (host, port string, ips []net.IP, err error) {
+ host, port, err = net.SplitHostPort(addr)
+ if err != nil {
+ return
+ }
+
+ ips, err = rs.LookupIP(host)
+ if err != nil {
+ err = fmt.Errorf("dial: %v", err)
+ return
+ }
+
+ if len(ips) == 0 {
+ err = fmt.Errorf("dial: lookup %s no such host", addr)
+ return
+ }
+
+ return
+}
diff --git a/transport_test.go b/transport_test.go
new file mode 100644
index 0000000..e92f0e5
--- /dev/null
+++ b/transport_test.go
@@ -0,0 +1,208 @@
+package godane
+
+import (
+ "bytes"
+ "crypto/rsa"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "github.com/google/martian/v3/mitm"
+ "github.com/miekg/dns"
+ "io/ioutil"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+)
+
+type TestResolver struct {
+ domain string
+ ip net.IP
+ tlsaPrefx string
+ tlsaRRs []dns.TLSA
+}
+
+func (rs TestResolver) LookupIP(name string) ([]net.IP, error) {
+ if name == rs.domain {
+ return []net.IP{rs.ip}, nil
+ }
+
+ return nil, errors.New("no such host")
+}
+
+func (rs TestResolver) LookupTLSA(prefix string) ([]dns.TLSA, error) {
+ if prefix == rs.tlsaPrefx {
+ return rs.tlsaRRs, nil
+ }
+
+ return nil, errors.New("not found")
+}
+
+func TestRoundTripperTLS(t *testing.T) {
+ ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintln(w, "hello")
+ }))
+ defer ts.Close()
+ cert, _, goodTLSA := testCreateCertTLSAPair(3, 1, 1)
+ ts.TLS = &tls.Config{
+ Certificates: []tls.Certificate{cert},
+ }
+
+ ts.StartTLS()
+
+ // https://127.0.0.1:port => https://example.com:port
+ url, _ := url.Parse(ts.URL)
+ host, port, _ := net.SplitHostPort(url.Host)
+ addr := net.JoinHostPort("example.com", port)
+ requrl := "https://" + addr
+
+ rs := TestResolver{
+ domain: "example.com",
+ ip: net.ParseIP(host),
+ }
+
+ client := ts.Client()
+ client.Transport = RoundTripper(rs)
+
+ // no tlsa
+ _, err := client.Get(requrl)
+ if err == nil {
+ t.Fatalf("want error, got nil")
+ }
+
+ // tlsa doesn't match server certificate
+ rs.tlsaPrefx = GetTLSAPrefix(addr)
+ _, _, tlsa2 := testCreateCertTLSAPair(3, 1, 1)
+ rs.tlsaRRs = []dns.TLSA{tlsa2}
+
+ client.Transport = RoundTripper(rs)
+ _, err = client.Get(requrl)
+ if err == nil {
+ t.Fatalf("want error, got nil")
+ }
+
+ // good tlsa
+ rs.tlsaRRs = []dns.TLSA{goodTLSA}
+ client.Transport = RoundTripper(rs)
+ res, err := client.Get(requrl)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ greeting, err := ioutil.ReadAll(res.Body)
+ res.Body.Close()
+
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ got := strings.TrimSpace(string(greeting))
+
+ if got != "hello" {
+ t.Fatalf("want `hello`, got `%s`", got)
+ }
+
+ // unsupported tlsa
+ _, _, tlsa3 := testCreateCertTLSAPair(1, 0, 1)
+ rs.tlsaRRs = []dns.TLSA{tlsa3}
+ client.Transport = RoundTripper(rs)
+ _, err = client.Get(requrl)
+
+ if err == nil {
+ t.Fatalf("want error, got nil")
+ }
+}
+
+func TestRoundTripperNoTLS(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintln(w, "hello")
+ })))
+ defer ts.Close()
+
+ // http://127.0.0.1:port => http://example.com:port
+ url, _ := url.Parse(ts.URL)
+ host, port, _ := net.SplitHostPort(url.Host)
+ addr := net.JoinHostPort("example.com", port)
+ requrl := "http://" + addr
+
+ rs := TestResolver{
+ domain: "example.com",
+ ip: net.ParseIP(host),
+ }
+
+ client := ts.Client()
+ client.Transport = RoundTripper(rs)
+
+ res, err := client.Get(requrl)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ greeting, err := ioutil.ReadAll(res.Body)
+ res.Body.Close()
+
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ got := strings.TrimSpace(string(greeting))
+
+ if got != "hello" {
+ t.Fatalf("want `hello`, got `%s`", got)
+ }
+}
+
+// creates a test certificate and a TLSA record for it.
+func testCreateCertTLSAPair(usage, selector, matching uint8) (tls.Certificate, *rsa.PrivateKey, dns.TLSA) {
+ ca, priv, err := mitm.NewAuthority("DNSSEC", "DNSSEC", time.Hour)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ m, err := mitm.NewConfig(ca, priv)
+ if err != nil {
+ log.Fatal(err)
+ }
+ mc := m.TLS()
+ cert, err := mc.GetCertificate(&tls.ClientHelloInfo{
+ ServerName: "example.com",
+ })
+
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ if cert == nil {
+ log.Fatal("no cert")
+ }
+
+ certStr, err := dns.CertificateToDANE(selector, matching, cert.Leaf)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ tlsa := dns.TLSA{
+ Usage: usage,
+ Selector: selector,
+ MatchingType: matching,
+ Certificate: certStr,
+ }
+
+ return *cert, priv, tlsa
+}
+
+func printCA(ca *x509.Certificate) {
+ raw := bytes.NewBuffer(make([]byte, 8000))
+ pem.Encode(raw, &pem.Block{
+ Type: "CERTIFICATE",
+ Bytes: ca.Raw,
+ })
+
+ fmt.Println(raw.String())
+}