Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add hysteria2 protocol dialer support #9

Merged
merged 13 commits into from
Jun 10, 2024
134 changes: 134 additions & 0 deletions dialer/hysteria2/hysteria2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package hysteria2

import (
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"errors"
"net"
"net/url"
"strconv"
"strings"

"github.com/daeuniverse/outbound/dialer"
"github.com/daeuniverse/outbound/netproxy"
"github.com/daeuniverse/outbound/protocol"
)

func init() {
dialer.FromLinkRegister("hysteria2", NewHysteria2)
dialer.FromLinkRegister("hy2", NewHysteria2)
}

type Hysteria2 struct {
Name string
User string
Server string
Port int
Insecure bool
Sni string
PinSHA256 string
}

func NewHysteria2(option *dialer.ExtraOption, nextDialer netproxy.Dialer, link string) (netproxy.Dialer, *dialer.Property, error) {
s, err := ParseHysteria2URL(link)
if err != nil {
return nil, nil, err
}
return s.Dialer(option, nextDialer)
}

func (s *Hysteria2) Dialer(option *dialer.ExtraOption, nextDialer netproxy.Dialer) (netproxy.Dialer, *dialer.Property, error) {
d := nextDialer
proxyAddress := net.JoinHostPort(s.Server, strconv.Itoa(s.Port))
header := protocol.Header{
ProxyAddress: proxyAddress,
TlsConfig: &tls.Config{
ServerName: s.Sni,
InsecureSkipVerify: s.Insecure || option.AllowInsecure,
},
SNI: s.Sni,
User: s.User,
IsClient: true,
}
if s.PinSHA256 != "" {
nHash := normalizeCertHash(s.PinSHA256)
header.TlsConfig.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
for _, cert := range rawCerts {
hash := sha256.Sum256(cert)
hashHex := hex.EncodeToString(hash[:])
if hashHex == nHash {
return nil
}
}
// No match
return errors.New("no certificate matches the pinned hash")
}
}
var err error
if d, err = protocol.NewDialer("hysteria2", d, header); err != nil {
return nil, nil, err
}
return d, &dialer.Property{
Name: s.Name,
Address: proxyAddress,
Protocol: "hysteria2",
Link: s.ExportToURL(),
}, nil
}

func normalizeCertHash(hash string) string {
r := strings.ToLower(hash)
r = strings.ReplaceAll(r, ":", "")
r = strings.ReplaceAll(r, "-", "")
return r
}

// ref: https://v2.hysteria.network/zh/docs/developers/URI-Scheme/
func ParseHysteria2URL(link string) (*Hysteria2, error) {
// TODO: support salamander obfuscation
t, err := url.Parse(link)
if err != nil {
return nil, err
}
port, err := strconv.Atoi(t.Port())
if err != nil {
return nil, dialer.InvalidParameterErr
}
q := t.Query()
sni := q.Get("sni")
if sni == "" {
sni = t.Hostname()
}
return &Hysteria2{
Name: t.Fragment,
User: t.User.String(),
Server: t.Hostname(),
Port: port,
Insecure: q.Get("insecure") == "1",
Sni: sni,
PinSHA256: q.Get("pinSHA256"),
}, nil
}

func (s *Hysteria2) ExportToURL() string {
t := url.URL{
Scheme: "hysteria2",
Host: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
User: url.User(s.User),
Fragment: s.Name,
}
q := t.Query()
if s.Insecure {
q.Set("insecure", "1")
}
if s.Sni != "" {
q.Set("sni", s.Sni)
}
if s.PinSHA256 != "" {
q.Set("pinSHA256", s.PinSHA256)
}
t.RawQuery = q.Encode()
return t.String()
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/onsi/ginkgo/v2 v2.11.0 // indirect
github.com/quic-go/qpack v0.4.0 // indirect
go.uber.org/mock v0.4.0 // indirect
golang.org/x/mod v0.12.0 // indirect
golang.org/x/text v0.14.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ github.com/onsi/gomega v1.27.8 h1:gegWiwZjBsf2DgiSbf5hpokZ98JVDMcWkUiigk6/KXc=
github.com/onsi/gomega v1.27.8/go.mod h1:2J8vzI/s+2shY9XHRApDkdgPo1TKT7P2u6fXeJKFnNQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.4.0 h1:Cr9BXA1sQS2SmDUWjSofMPNKmvF6IiIfDRmgU0w1ZCo=
github.com/quic-go/qpack v0.4.0/go.mod h1:UZVnYIfi5GRk+zI9UMaCPsmZ2xKJP7XBUvVyT1Knj9A=
github.com/refraction-networking/utls v1.6.4 h1:aeynTroaYn7y+mFtqv8D0bQ4bw0y9nJHneGxJ7lvRDM=
github.com/refraction-networking/utls v1.6.4/go.mod h1:2VL2xfiqgFAZtJKeUTlf+PSYFs3Eu7km0gCtXJ3m8zs=
github.com/seiflotfy/cuckoofilter v0.0.0-20220411075957-e3b120b3f5fb h1:XfLJSPIOUX+osiMraVgIrMR27uMXnRJWGm1+GL8/63U=
Expand Down
17 changes: 17 additions & 0 deletions protocol/hysteria2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Hysteria2

This part of the code is modified from [`apernet/hysteria`](https://github.com/apernet/hysteria/) with many thanks.

## License

See the [LICENSE](/LICENSE) file for license rights and limitations.

Portions of this code are derived from the Hysteria project under the [MIT License](https://github.com/apernet/hysteria/blob/52c8f82c2ba3172660152b3d6918797dd49eff13/LICENSE.md):

Copyright 2023 Toby

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.
Loading