From 415c557a8d97b4c3284cf78f1736df1dc587e890 Mon Sep 17 00:00:00 2001 From: wweir Date: Sat, 24 Nov 2018 21:19:56 +0800 Subject: [PATCH] First init --- .gitignore | 18 +++ LICENSE | 373 ++++++++++++++++++++++++++++++++++++++++++++++ Makefile | 19 +++ README.md | 5 + conf/conf.go | 35 +++++ conf/sower.toml | 9 ++ dns/dns.go | 108 ++++++++++++++ dns/suffixTree.go | 60 ++++++++ go.mod | 19 +++ go.sum | 50 +++++++ main.go | 23 +++ parser/addr.go | 75 ++++++++++ parser/sni.go | 232 ++++++++++++++++++++++++++++ proxy/client.go | 56 +++++++ proxy/server.go | 55 +++++++ proxy/util.go | 47 ++++++ 16 files changed, 1184 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 conf/conf.go create mode 100644 conf/sower.toml create mode 100644 dns/dns.go create mode 100644 dns/suffixTree.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go create mode 100644 parser/addr.go create mode 100644 parser/sni.go create mode 100644 proxy/client.go create mode 100644 proxy/server.go create mode 100644 proxy/util.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9ae07b4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +.DS_Store +**/.DS_Store +.vscode +.idea +sower diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c427fef --- /dev/null +++ b/Makefile @@ -0,0 +1,19 @@ +SERVER:=127.0.0.1:5533 + +default: build + +build: + GOBIN=$(PWD) go install -v + +kill: + sudo pkill -9 sower || true + +client: build kill + sudo $(PWD)/sower -f conf/sower.toml + +server: build kill + $(PWD)/sower -D true + +run: build kill + $(PWD)/sower -D true & + sudo $(PWD)/sower -f conf/sower.toml diff --git a/README.md b/README.md new file mode 100644 index 0000000..898f4fd --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# sower +another cross platform transparent proxy tool + +## todo +- [ ] broker \ No newline at end of file diff --git a/conf/conf.go b/conf/conf.go new file mode 100644 index 0000000..ba25054 --- /dev/null +++ b/conf/conf.go @@ -0,0 +1,35 @@ +package conf + +import ( + "flag" + + "github.com/BurntSushi/toml" +) + +var Conf = struct { + ConfigFile string + ServerPort string `toml:"server_port"` + ServerAddr string `toml:"server_addr"` + DnsServer string `toml:"dns_server"` + BlockList []string `toml:"blocklist"` + Debug bool `toml:"debug"` +}{} + +func init() { + flag.StringVar(&Conf.ConfigFile, "f", "", "config file location") + flag.StringVar(&Conf.ServerPort, "P", "5533", "server mode listen port") + flag.StringVar(&Conf.ServerAddr, "s", "", "server addr (run in client mode if set)") + flag.StringVar(&Conf.DnsServer, "d", "114.114.114.114", "client dns server") + flag.BoolVar(&Conf.Debug, "D", false, "run in debug mode") + + if !flag.Parsed() { + flag.Parse() + } + + if Conf.ConfigFile == "" { + return + } + if _, err := toml.DecodeFile(Conf.ConfigFile, &Conf); err != nil { + panic(err) + } +} diff --git a/conf/sower.toml b/conf/sower.toml new file mode 100644 index 0000000..a64b788 --- /dev/null +++ b/conf/sower.toml @@ -0,0 +1,9 @@ +server_port="5533" +server_addr="127.0.0.1:5533" +dns_server="114.114.114.114" +blocklist=[ + "*.google.com", + "*.youtube.com", + "zh.wikipedia.org", +] +debug=true \ No newline at end of file diff --git a/dns/dns.go b/dns/dns.go new file mode 100644 index 0000000..8abd38a --- /dev/null +++ b/dns/dns.go @@ -0,0 +1,108 @@ +package dns + +import ( + "log" + "net" + "strings" + "time" + + "github.com/miekg/dns" + "github.com/wweir/sower/conf" +) + +func StartDNS(dnsServer string, blocklist []string) { + var handle func(w dns.ResponseWriter, r *dns.Msg, name, dnsServer string) + if len(blocklist) == 0 { + handle = bestTry + } else { + initRule(blocklist) + handle = manual + } + + dns.HandleFunc(".", func(w dns.ResponseWriter, r *dns.Msg) { + // *Msg r has an TSIG record and it was validated + if r.IsTsig() != nil && w.TsigStatus() == nil { + r.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix()) + } + + //https://stackoverflow.com/questions/4082081/requesting-a-and-aaaa-records-in-single-dns-query/4083071#4083071 + if len(r.Question) == 0 { + return + } + + handle(w, r, r.Question[0].Name, dnsServer) + }) + + server := &dns.Server{Addr: ":53", Net: "udp"} + server.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="} + log.Fatalln(server.ListenAndServe()) +} + +// TODO: delete me +func bestTry(w dns.ResponseWriter, r *dns.Msg, name, dnsServer string) { + msg, err := dns.Exchange(r, dnsServer+":53") + if err != nil || len(msg.Answer) == 0 { + rr, _ := dns.NewRR(name + " A 127.0.0.1") + r.Answer = []dns.RR{rr} + w.WriteMsg(r) + return + } + + var ip string + switch msg.Answer[0].(type) { + case *dns.A: + ip = msg.Answer[0].(*dns.A).A.String() + case *dns.AAAA: + ip = "[" + msg.Answer[0].(*dns.AAAA).AAAA.String() + "]" + default: + w.WriteMsg(msg) + } + + if _, err := net.DialTimeout("tcp", ip+":http", time.Second); err != nil { + log.Println(ip+":80", err) + rr, _ := dns.NewRR(name + " A 127.0.0.1") + r.Answer = []dns.RR{rr} + w.WriteMsg(r) + return + } + w.WriteMsg(msg) +} + +var rule *Node + +func initRule(blocklist []string) { + rule = NewNode() + + for i := range blocklist { + rule.Add(strings.Split(blocklist[i], ".")) + } + + if conf.Conf.Debug { + log.Printf("block rule:\n%s", rule) + } +} + +func manual(w dns.ResponseWriter, r *dns.Msg, name, dnsServer string) { + if rule.Match(strings.TrimSuffix(name, ".")) { + if conf.Conf.Debug { + log.Printf("match %s suss", name) + } + + rr, _ := dns.NewRR(name + " A 127.0.0.1") + r.Answer = []dns.RR{rr} + w.WriteMsg(r) + return + } + if conf.Conf.Debug { + log.Printf("match %s fail", name) + } + + msg, err := dns.Exchange(r, dnsServer+":53") + if err != nil || len(msg.Answer) == 0 { + rr, _ := dns.NewRR(name + " A 127.0.0.1") + r.Answer = []dns.RR{rr} + w.WriteMsg(r) + return + } + w.WriteMsg(msg) +} diff --git a/dns/suffixTree.go b/dns/suffixTree.go new file mode 100644 index 0000000..23b2c22 --- /dev/null +++ b/dns/suffixTree.go @@ -0,0 +1,60 @@ +package dns + +import ( + "strings" +) + +type Node struct { + Node map[string]*Node +} + +func NewNode() *Node { + return &Node{Node: map[string]*Node{}} +} +func (n *Node) String() string { + return n.string("") +} +func (n *Node) string(prefix string) (out string) { + for key, val := range n.Node { + out += prefix + key + "\n" + val.string(prefix+" ") + } + return +} + +func (n *Node) Add(secs []string) { + length := len(secs) + switch length { + case 0: + return + case 1: + n.Node[secs[length-1]] = NewNode() + default: + subNode, ok := n.Node[secs[length-1]] + if !ok { + subNode = NewNode() + n.Node[secs[length-1]] = subNode + } + subNode.Add(secs[:length-1]) + } +} + +func (n *Node) Match(addr string) bool { + return n.matchSecs(strings.Split(addr, ".")) +} + +func (n *Node) matchSecs(secs []string) bool { + length := len(secs) + if length == 0 { + return true + } + + if n, ok := n.Node[secs[length-1]]; ok { + return n.matchSecs(secs[:length-1]) + } + + if n, ok := n.Node["*"]; ok { + return n.matchSecs(secs[:length-1]) + } + + return false +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..886cdee --- /dev/null +++ b/go.mod @@ -0,0 +1,19 @@ +module github.com/wweir/sower + +require ( + github.com/BurntSushi/toml v0.3.1 + github.com/bifurcation/mint v0.0.0-20181105071958-a14404e9a861 // indirect + github.com/cheekybits/genny v1.0.0 // indirect + github.com/golang/mock v1.1.1 // indirect + github.com/hashicorp/golang-lru v0.5.0 // indirect + github.com/lucas-clemente/aes12 v0.0.0-20171027163421-cd47fb39b79f // indirect + github.com/lucas-clemente/quic-go v0.10.0 + github.com/lucas-clemente/quic-go-certificates v0.0.0-20160823095156-d2f86524cced // indirect + github.com/miekg/dns v1.0.15 + github.com/onsi/ginkgo v1.7.0 // indirect + github.com/onsi/gomega v1.4.3 // indirect + golang.org/x/crypto v0.0.0-20181112202954-3d3f9f413869 // indirect + golang.org/x/net v0.0.0-20181114220301-adae6a3d119a // indirect + golang.org/x/sync v0.0.0-20181108010431-42b317875d0f // indirect + golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..43bb322 --- /dev/null +++ b/go.sum @@ -0,0 +1,50 @@ +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/bifurcation/mint v0.0.0-20181105071958-a14404e9a861 h1:x17NvoJaphEzay72TFej4OSSsgu3xRYBLkbIwdofS/4= +github.com/bifurcation/mint v0.0.0-20181105071958-a14404e9a861/go.mod h1:zVt7zX3K/aDCk9Tj+VM7YymsX66ERvzCJzw8rFCX2JU= +github.com/cheekybits/genny v1.0.0 h1:uGGa4nei+j20rOSeDeP5Of12XVm7TGUd4dJA9RDitfE= +github.com/cheekybits/genny v1.0.0/go.mod h1:+tQajlRqAUrPI7DOSpB0XAqZYtQakVtB7wXkRAgjxjQ= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/golang/mock v1.1.1 h1:G5FRp8JnTd7RQH5kemVNlMeyXQAztQ3mOWV95KxsXH8= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/hashicorp/golang-lru v0.5.0 h1:CL2msUPvZTLb5O648aiLNJw3hnBxN2+1Jq8rCOH9wdo= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/lucas-clemente/aes12 v0.0.0-20171027163421-cd47fb39b79f h1:sSeNEkJrs+0F9TUau0CgWTTNEwF23HST3Eq0A+QIx+A= +github.com/lucas-clemente/aes12 v0.0.0-20171027163421-cd47fb39b79f/go.mod h1:JpH9J1c9oX6otFSgdUHwUBUizmKlrMjxWnIAjff4m04= +github.com/lucas-clemente/quic-go v0.10.0 h1:xEF+pSHYAOcu+U10Meunf+DTtc8vhQDRqlA0BJ6hufc= +github.com/lucas-clemente/quic-go v0.10.0/go.mod h1:wuD+2XqEx8G9jtwx5ou2BEYBsE+whgQmlj0Vz/77PrY= +github.com/lucas-clemente/quic-go-certificates v0.0.0-20160823095156-d2f86524cced h1:zqEC1GJZFbGZA0tRyNZqRjep92K5fujFtFsu5ZW7Aug= +github.com/lucas-clemente/quic-go-certificates v0.0.0-20160823095156-d2f86524cced/go.mod h1:NCcRLrOTZbzhZvixZLlERbJtDtYsmMw8Jc4vS8Z0g58= +github.com/miekg/dns v1.0.15 h1:9+UupePBQCG6zf1q/bGmTO1vumoG13jsrbWOSX1W6Tw= +github.com/miekg/dns v1.0.15/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +golang.org/x/crypto v0.0.0-20181112202954-3d3f9f413869 h1:kkXA53yGe04D0adEYJwEVQjeBppL01Exg+fnMjfUraU= +golang.org/x/crypto v0.0.0-20181112202954-3d3f9f413869/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a h1:gOpx8G595UYyvj8UK4+OFyY4rx037g3fmfhe5SasG3U= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTmV7VDcZyvRZ+QQXkXTZQ= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b h1:MQE+LT/ABUuuvEZ+YQAMSXindAdUh7slEmAkup74op4= +golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/main.go b/main.go new file mode 100644 index 0000000..5f898f5 --- /dev/null +++ b/main.go @@ -0,0 +1,23 @@ +package main + +import ( + "log" + + "github.com/wweir/sower/conf" + "github.com/wweir/sower/dns" + "github.com/wweir/sower/proxy" +) + +func init() { + log.SetFlags(log.LstdFlags | log.Lshortfile) +} +func main() { + log.Println(conf.Conf) + + if conf.Conf.ServerAddr == "" { + proxy.StartServer(conf.Conf.ServerPort) + } else { + dns.StartDNS(conf.Conf.DnsServer, conf.Conf.BlockList) + proxy.StartClient(conf.Conf.ServerAddr) + } +} diff --git a/parser/addr.go b/parser/addr.go new file mode 100644 index 0000000..fbc39a5 --- /dev/null +++ b/parser/addr.go @@ -0,0 +1,75 @@ +package parser + +import ( + "bufio" + "fmt" + "io" + "net" + "net/http" + "strings" +) + +type TeeConn struct { + net.Conn + buf []byte + offset int + Tee bool // read +} + +func (t *TeeConn) Reset() { + t.offset = 0 +} + +func (t *TeeConn) Read(b []byte) (n int, err error) { + length := len(t.buf) - t.offset + if length > 0 { + n = copy(b, t.buf[t.offset:]) + t.offset += n + return + } + + n, err = t.Conn.Read(b) + if t.Tee { + t.buf = append(t.buf, b[:n]...) + t.offset += n + } + return n, err +} + +func ParseAddr(conn net.Conn) (teeConn *TeeConn, addr string, err error) { + teeConn = &TeeConn{Conn: conn, Tee: true} + defer func() { + teeConn.Reset() + teeConn.Tee = false + }() + + buf := make([]byte, 1) + if n, err := teeConn.Read(buf); err != nil || n != 1 { + return teeConn, "", fmt.Errorf("Read conn fail: %v, readed: %d %v", err, n, buf) + } + + teeConn.Reset() + + // https + if buf[0] == 0x16 { // SSL handleshake + host, _, err := extractSNI(io.Reader(teeConn)) + if err != nil { + return teeConn, "", err + } + if strings.Contains(host, ":") { + return teeConn, host, nil + } + return teeConn, host + ":443", nil + } + + // http + b := bufio.NewReader(teeConn) + resp, err := http.ReadRequest(b) + if err != nil { + return teeConn, "", err + } + if strings.Contains(resp.Host, ":") { + return teeConn, resp.Host, nil + } + return teeConn, resp.Host + ":80", nil +} diff --git a/parser/sni.go b/parser/sni.go new file mode 100644 index 0000000..aa665d1 --- /dev/null +++ b/parser/sni.go @@ -0,0 +1,232 @@ +// Copyright 2016 Google Inc. +// +// 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. + +package parser + +import ( + "encoding/binary" + "errors" + "fmt" + "io" +) + +func extractSNI(r io.Reader) (string, int, error) { + handshake, tlsver, err := handshakeRecord(r) + if err != nil { + return "", 0, fmt.Errorf("reading TLS record: %s", err) + } + + sni, err := parseHello(handshake) + if err != nil { + return "", 0, fmt.Errorf("reading ClientHello: %s", err) + } + if len(sni) == 0 { + // ClientHello did not present an SNI extension. Valid packet, + // no hostname. + return "", tlsver, nil + } + + hostname, err := parseSNI(sni) + if err != nil { + return "", 0, fmt.Errorf("parsing SNI extension: %s", err) + } + return hostname, tlsver, nil +} + +// Extract the indicated hostname, if any, from the given SNI +// extension bytes. +func parseSNI(b []byte) (string, error) { + b, _, err := vector(b, 2) + if err != nil { + return "", err + } + + var ret []byte + for len(b) >= 3 { + typ := b[0] + ret, b, err = vector(b[1:], 2) + if err != nil { + return "", fmt.Errorf("truncated SNI extension") + } + + if typ == sniHostnameID { + return string(ret), nil + } + } + + if len(b) != 0 { + return "", fmt.Errorf("trailing garbage at end of SNI extension") + } + + // No DNS-based SNI present. + return "", nil +} + +const sniExtensionID = 0 +const sniHostnameID = 0 + +// Parse a TLS handshake record as a ClientHello message and extract +// the SNI extension bytes, if any. +func parseHello(b []byte) ([]byte, error) { + if len(b) == 0 { + return nil, errors.New("zero length handshake record") + } + if b[0] != 1 { + return nil, fmt.Errorf("non-ClientHello handshake record type %d", b[0]) + } + + // We're expecting a stricter TLS parser to run after we've + // proxied, so we ignore any trailing bytes that might be present + // (e.g. another handshake message). + b, _, err := vector(b[1:], 3) + if err != nil { + return nil, fmt.Errorf("reading ClientHello: %s", err) + } + + // ClientHello must be at least 34 bytes to reach the first vector + // length byte. The actual minimal size is larger than that, but + // vector() will correctly handle truncated packets. + if len(b) < 34 { + return nil, errors.New("ClientHello packet too short") + } + + if b[0] != 3 { + return nil, fmt.Errorf("ClientHello has unsupported version %d.%d", b[0], b[1]) + } + switch b[1] { + case 1, 2, 3: + // TLS 1.0, TLS 1.1, TLS 1.2 + default: + return nil, fmt.Errorf("TLS record has unsupported version %d.%d", b[0], b[1]) + } + + // Skip over version and random struct + b = b[34:] + + // We don't technically care about SessionID, but we care that the + // framing is well-formed all the way up to the SNI field, so that + // we are sure that we're pulling the same SNI bytes as the + // eventual TLS implementation. + vec, b, err := vector(b, 1) + if err != nil { + return nil, fmt.Errorf("reading ClientHello SessionID: %s", err) + } + if len(vec) > 32 { + return nil, fmt.Errorf("ClientHello SessionID too long (%db)", len(vec)) + } + + // Likewise, we're just checking the bare minimum of framing. + vec, b, err = vector(b, 2) + if err != nil { + return nil, fmt.Errorf("reading ClientHello CipherSuites: %s", err) + } + if len(vec) < 2 || len(vec)%2 != 0 { + return nil, fmt.Errorf("ClientHello CipherSuites invalid length %d", len(vec)) + } + + vec, b, err = vector(b, 1) + if err != nil { + return nil, fmt.Errorf("reading ClientHello CompressionMethods: %s", err) + } + if len(vec) < 1 { + return nil, fmt.Errorf("ClientHello CompressionMethods invalid length %d", len(vec)) + } + + // Finally, we reach the extensions. + if len(b) == 0 { + // No extensions. This is not an error, it just means we have + // no SNI payload. + return nil, nil + } + b, vec, err = vector(b, 2) + if err != nil { + return nil, fmt.Errorf("reading ClientHello extensions: %s", err) + } + if len(vec) != 0 { + return nil, fmt.Errorf("%d bytes of trailing garbage in ClientHello", len(vec)) + } + + for len(b) >= 4 { + typ := binary.BigEndian.Uint16(b[:2]) + vec, b, err = vector(b[2:], 2) + if err != nil { + return nil, fmt.Errorf("reading ClientHello extension %d: %s", typ, err) + } + if typ == sniExtensionID { + // Found the SNI extension, return its payload. We don't + // care about anything in the packet beyond this point. + return vec, nil + } + } + + if len(b) != 0 { + return nil, fmt.Errorf("%d bytes of trailing garbage in ClientHello", len(b)) + } + + // Successfully parsed all extensions, but there was no SNI. + return nil, nil +} + +const maxTLSRecordLength = 16384 + +// Read one TLS record, which must be for the handshake protocol, from r. +func handshakeRecord(r io.Reader) ([]byte, int, error) { + var hdr struct { + Type uint8 + Major, Minor uint8 + Length uint16 + } + if err := binary.Read(r, binary.BigEndian, &hdr); err != nil { + return nil, 0, fmt.Errorf("reading TLS record header: %s", err) + } + + if hdr.Type != 22 { + return nil, 0, fmt.Errorf("TLS record is not a handshake") + } + + if hdr.Major != 3 { + return nil, 0, fmt.Errorf("TLS record has unsupported version %d.%d", hdr.Major, hdr.Minor) + } + switch hdr.Minor { + case 1, 2, 3: + // TLS 1.0, TLS 1.1, TLS 1.2 + default: + return nil, 0, fmt.Errorf("TLS record has unsupported version %d.%d", hdr.Major, hdr.Minor) + } + + if hdr.Length > maxTLSRecordLength { + return nil, 0, fmt.Errorf("TLS record length is greater than %d", maxTLSRecordLength) + } + + ret := make([]byte, hdr.Length) + if _, err := io.ReadFull(r, ret); err != nil { + return nil, 0, err + } + + return ret, int(hdr.Minor), nil +} + +func vector(b []byte, lenBytes int) ([]byte, []byte, error) { + if len(b) < lenBytes { + return nil, nil, errors.New("not enough space in packet for vector") + } + var l int + for _, b := range b[:lenBytes] { + l = (l << 8) + int(b) + } + if len(b) < l+lenBytes { + return nil, nil, errors.New("not enough space in packet for vector") + } + return b[lenBytes : l+lenBytes], b[l+lenBytes:], nil +} diff --git a/proxy/client.go b/proxy/client.go new file mode 100644 index 0000000..62876a4 --- /dev/null +++ b/proxy/client.go @@ -0,0 +1,56 @@ +package proxy + +import ( + "log" + "net" + + "github.com/lucas-clemente/quic-go" +) + +func StartClient(server string) { + connCh := listenLocal([]string{":80", ":443"}) + sess, err := quic.DialAddr(server, nil, nil) + if err != nil { + log.Printf("connect to remote(%s) fail:%s\n", server, err) + return + } + + for { + go func(conn net.Conn) { + defer conn.Close() + conn.(*net.TCPConn).SetKeepAlive(true) + + stream, err := sess.OpenStream() + if err != nil { + log.Printf("connect to remote(%s) fail:%s\n", server, err) + return + } + defer stream.Close() + + relay(&streamConn{stream, sess}, conn) + }(<-connCh) + } +} + +func listenLocal(ports []string) <-chan net.Conn { + connCh := make(chan net.Conn) + for i := range ports { + go func(port string) { + ln, err := net.Listen("tcp", port) + if err != nil { + log.Fatalln(err) + } + + for { + conn, err := ln.Accept() + if err != nil { + log.Println("accept", port, "fail:", err) + } + + connCh <- conn + } + }(ports[i]) + } + + return connCh +} diff --git a/proxy/server.go b/proxy/server.go new file mode 100644 index 0000000..cc040b9 --- /dev/null +++ b/proxy/server.go @@ -0,0 +1,55 @@ +package proxy + +import ( + "log" + "net" + + "github.com/lucas-clemente/quic-go" + "github.com/wweir/sower/parser" +) + +func StartServer(port string) { + ln, err := quic.ListenAddr(":"+port, nil, nil) + if err != nil { + log.Fatalln(err) + } + + for { + sess, err := ln.Accept() + if err != nil { + log.Println(err) + } + go acceptSession(sess) + } +} + +func acceptSession(sess quic.Session) { + for { + stream, err := sess.AcceptStream() + if err != nil { + log.Println(err) + } + go acceptStream(stream, sess) + } +} + +func acceptStream(stream quic.Stream, sess quic.Session) { + defer stream.Close() + + conn, addr, err := parser.ParseAddr(&streamConn{stream, sess}) + if err != nil { + log.Panicln(err) + return + } + log.Println(addr) + + rc, err := net.Dial("tcp", addr) + if err != nil { + log.Println(err) + return + } + defer rc.Close() + rc.(*net.TCPConn).SetKeepAlive(true) + + relay(rc, conn) +} diff --git a/proxy/util.go b/proxy/util.go new file mode 100644 index 0000000..53b42f3 --- /dev/null +++ b/proxy/util.go @@ -0,0 +1,47 @@ +package proxy + +import ( + "io" + "log" + "net" + "sync" + "sync/atomic" + "time" + + "github.com/lucas-clemente/quic-go" +) + +type streamConn struct { + quic.Stream + sess quic.Session +} + +func (s *streamConn) LocalAddr() net.Addr { + return s.sess.LocalAddr() +} + +func (s *streamConn) RemoteAddr() net.Addr { + return s.sess.RemoteAddr() +} + +func relay(conn1, conn2 net.Conn) { + wg := &sync.WaitGroup{} + exitFlag := new(int32) + wg.Add(2) + go redirect(conn1, conn2, wg, exitFlag) + redirect(conn2, conn1, wg, exitFlag) + wg.Wait() +} + +func redirect(conn1, conn2 net.Conn, wg *sync.WaitGroup, exitFlag *int32) { + if _, err := io.Copy(conn2, conn1); err != nil && (atomic.LoadInt32(exitFlag) == 0) { + log.Printf("%s<>%s -> %s<>%s: %s", conn1.RemoteAddr(), conn1.LocalAddr(), conn2.LocalAddr(), conn2.RemoteAddr(), err) + } + + // wakeup all conn goroutine + atomic.AddInt32(exitFlag, 1) + now := time.Now() + conn1.SetDeadline(now) + conn2.SetDeadline(now) + wg.Done() +}