Compare commits

...
68 Commits
Author SHA1 Message Date
Lanlan13-14 e26714a181 feat: support TLS rekey fix, data-ciphers negotiation, tls-crypt-v2 for OpenVPN (#2989) 2026-07-18 19:18:54 +08:00
anytls bd749c65bc feat: sync anytls v0.0.13 (#2990) 2026-07-18 10:41:27 +08:00
wwqgtxx 9ae1cc2be2 fix: shadowquic JLS pre-flight fallback handle 2026-07-17 15:52:42 +08:00
wwqgtxx 1eb49e0571 doc: explain the flaws in the official Shadowquic implementation regarding JLS 0-RTT authentication 2026-07-17 08:39:14 +08:00
wwqgtxx a5167fa4ab fix: allow JLS fallback before the server flight
Decide whether fallback is safe based on bytes actually written instead of JLS authentication status. This allows authenticated preflight failures, including HRR and TLS configuration mismatches, to relay the untouched ClientHello to the camouflage target.

Keep rejecting fallback after a partial or complete server flight, update jls-tls for pre-write alert suppression, and add coverage for both sides of the write boundary.
2026-07-16 23:02:17 +08:00
wwqgtxx f86bc224dc fix: align HelloRetryRequest handling with JLS v3
JLS v3 does not permit HelloRetryRequest during JLS authentication. Keep the ClientHello random unchanged across HRR and make clients continue as ordinary TLS with certificate verification.

When an authenticated ClientHello would require HRR, fail before writing handshake data and wrap ErrJLSAuthFailed. This allows stream and QUIC callers to forward the untouched handshake to the camouflage fallback instead of accepting a non-standard JLS exchange.
2026-07-16 22:17:24 +08:00
wwqgtxx 423611628c chore: better UserFromConn implementation 2026-07-16 20:47:52 +08:00
freephilx 0ee584171e fix: reconnect OpenVPN on server soft reset (#2978) 2026-07-16 17:04:33 +08:00
wwqgtxx 9a7e726657 fix: performance regression caused by unnecessary wrapping in stream encryption 2026-07-16 16:27:34 +08:00
wwqgtxx a70af27451 fix: remove unnecessary quinn-jls compatibility behavior 2026-07-16 10:03:47 +08:00
wwqgtxx 5c1b8bfc31 chore: authenticate JLS ServerHello using its wire encoding
JLS authenticates the serialized ServerHello with only the random field zeroed. The previous marshalForJLS implementation reordered extensions to match rustls-jls's internal struct order, even when that order differed from the bytes sent on the wire.

That canonical order is not defined by TLS or the JLS specification and couples this package to a rustls-jls implementation detail. Use the normal marshal output when sending and the original wire bytes when receiving, preserving extension order and leaving the TLS transcript untouched.

This intentionally removes compatibility with rustls-jls clients that re-encode ServerHello extensions before JLS verification.
2026-07-16 09:04:31 +08:00
wwqgtxx e3c1ea06a4 chore: better handshakeRecorderConn impl 2026-07-16 08:40:18 +08:00
wwqgtxx e9119858b2 chore: change the brutal negotiation in shadowquic to be asynchronous 2026-07-16 00:02:50 +08:00
AaronChen0 c079b0cc12 fix: panic on full-width IP-SUFFIX rules (#2975) 2026-07-15 21:51:32 +08:00
wwqgtxx b75a776d39 chore: clean up duplicate helpers in tests 2026-07-15 18:29:59 +08:00
wwqgtxx 9ab75434a9 feat: support restls/jls for snell outbound and listener 2026-07-15 18:16:38 +08:00
wwqgtxx da5a3e52ae chore: rewrite the internal mutual exclusion logic of the outbound 2026-07-15 17:55:48 +08:00
wwqgtxx b6ed8e2643 chore: rewrite the internal mutual exclusion logic of the listener 2026-07-15 17:43:18 +08:00
wwqgtxx 8507c1e221 fix: missing override shadow-tls-opts and restls-opts in xhttp download-settings 2026-07-15 17:42:58 +08:00
wwqgtxx bc5976f4ed chore: sync internal logic 2026-07-15 16:59:59 +08:00
wwqgtxx 0e7c3c79e3 feat: support restls for anytls outbound and listener 2026-07-15 16:52:21 +08:00
wwqgtxx 769ea6f5b4 feat: support restls for vmess/vless/trojan outbound and listener 2026-07-15 16:49:02 +08:00
wwqgtxx bc0e5aa835 feat: support shadowtls for anytls outbound and listener 2026-07-15 16:18:37 +08:00
wwqgtxx c015694bf3 feat: support shadowtls for vmess/vless/trojan outbound and listener 2026-07-15 15:51:35 +08:00
wwqgtxx 8413f50407 chore: skip frequently failed tests on windows go1.20 2026-07-15 10:18:47 +08:00
wwqgtxx 86984831ed fix: the incorrect tls stack was used in shadowtls tests 2026-07-15 08:54:41 +08:00
wwqgtxx 2b0d8411fa fix: make shadowtls v2 read deadlines recoverable 2026-07-15 00:31:49 +08:00
wwqgtxx 7a3c37cb33 fix: make shadowtls v3 read deadlines recoverable 2026-07-15 00:31:14 +08:00
wwqgtxx 3f22309b51 chore: respect the incoming context during JLS fallback 2026-07-14 21:51:12 +08:00
wwqgtxx 4d7ef85adb chore: sync logic to legacy shadowsocks listener 2026-07-14 21:02:36 +08:00
wwqgtxx 44dd834fef chore: preserve jls in-user for shadowsocks listeners 2026-07-14 17:58:28 +08:00
wwqgtxx 309cfbd613 chore: reimplement shadowtls 2026-07-14 17:22:01 +08:00
wwqgtxx ba5c45b735 fix: anytls listener config parsing 2026-07-14 12:31:41 +08:00
wwqgtxx 94409eb659 chore: remove redundant writeFull in sudoku 2026-07-14 09:16:29 +08:00
wwqgtxx 1d1b370e4c chore: remove redundant writeFull in snell v4 2026-07-14 09:16:19 +08:00
wwqgtxx f23e43e68a chore: remove redundant writeFull in gost relay 2026-07-14 09:16:19 +08:00
wwqgtxx 95af34af06 chore: remove redundant writeFull in shadowquic 2026-07-14 09:16:19 +08:00
wwqgtxx bfa9ea1d2b feat: support brutal for shadowquic (mihomo private extension) 2026-07-14 08:49:22 +08:00
wwqgtxx 3b73922fb9 chore: cleanup shadowquic code 2026-07-14 00:28:24 +08:00
wwqgtxx cb8cde8da8 fix: missing override jls-opts in xhttp download-settings 2026-07-14 00:28:24 +08:00
wwqgtxx 8fe7f74811 feat: support jls for anytls outbound and listener 2026-07-13 23:50:40 +08:00
wwqgtxx 611a4481fa feat: support jls for vmess/vless/trojan outbound and listener 2026-07-13 18:49:53 +08:00
wwqgtxx dc4d4fcb8c chore: allow jls with utls client-fingerprint 2026-07-13 08:57:32 +08:00
wwqgtxx 2b2bdf6d22 feat: support jls for shadowsocks outbound and listener 2026-07-13 01:31:09 +08:00
wwqgtxx a35045d9f1 fix: consume CachedConn data in ReadCached 2026-07-13 00:39:52 +08:00
wwqgtxx aea5ce4142 feat: support shadowquic outbound and listener 2026-07-12 22:28:43 +08:00
wwqgtxx 46f9b78626 chore: export internal OverrideExpr for api user 2026-07-12 19:12:58 +08:00
wwqgtxx 5677fd3808 feat: add name-cert-verify to support separate certificate verification name 2026-07-12 18:12:59 +08:00
wwqgtxx 3766a08754 fix: set global CA pool and NTP time for restls 2026-07-12 17:53:03 +08:00
lyaaz 76d80883dd feat: add support for TLSAuth for Openvpn (#2969) 2026-07-12 16:33:45 +08:00
saba-futai 9729296862 chore: sync to sudoku v0.4.8 (#2966) 2026-07-12 08:16:44 +08:00
wwqgtxx 75eeba4292 chore: significantly trim unnecessary code from tailscale
reduced size by 2.3 MB on Windows/Linux build
2026-07-11 23:02:57 +08:00
AaronChen0 45f7930936 fix: CNAME query matching a hosts domain-entry returns an empty answer (#2965) 2026-07-11 19:14:42 +08:00
AaronChen0 41549236fe fix: stop reaper goroutine busy-looping after context cancel (#2964) 2026-07-11 17:47:56 +08:00
wwqgtxx 6d96163e6f feat: support override-expr for proxy provider override 2026-07-11 15:40:54 +08:00
wwqgtxx 975389a1e5 fix: intermittent timeouts during the soak test 2026-07-10 22:30:38 +08:00
AaronChen0 75a3ea8b2d fix: leaked openStreams on failure in TUIC client (#2959) 2026-07-10 21:36:51 +08:00
AaronChen0 12c30af92f fix: wireguard per-peer reserved ignored (#2958) 2026-07-10 20:35:23 +08:00
AaronChen0 c5834396c4 fix: DOMAIN-WILDCARD ignores sniffed hostname (#2956) 2026-07-10 19:29:08 +08:00
Medium1992 6a52d23a13 chore: do not force trailing path / when both sessionID and seq are placed elsewhere for xhttp 2026-07-09 07:35:14 +08:00
SaltyMonkey 02dfcf2b4d fix: incorrect alphabet size used in session-table for predefined tables in xhttp-config 2026-07-09 07:34:03 +08:00
wwqgtxx 5ec37681f9 doc: update doc 2026-07-08 22:02:47 +08:00
wwqgtxx e8ab2d047e fix: alpnAwareRoundTripper behavior in mekya client 2026-07-08 15:50:32 +08:00
wwqgtxx 9cece132be chore: add test for alpnAwareRoundTripper in mekya client 2026-07-08 15:50:32 +08:00
wwqgtxx 2d45f9ec16 chore: using new net/http api in mekya client 2026-07-08 15:50:32 +08:00
wwqgtxx cf8545dbd1 chore: stabilize traffic wait timing in tlsmirror test 2026-07-08 15:50:32 +08:00
wwqgtxx ee80e8d641 chore: more comprehensive interop test 2026-07-08 15:50:32 +08:00
AaronChen0 2c7309e2af fix: listener duplicate-name check (#2948) 2026-07-08 14:52:54 +08:00
177 changed files with 17006 additions and 1320 deletions

No files matched your search

+53 -16
View File
@@ -2,8 +2,10 @@ package outbound
import (
"context"
"errors"
"net"
"strconv"
"strings"
"time"
N "github.com/metacubex/mihomo/common/net"
@@ -24,22 +26,27 @@ type AnyTLS struct {
type AnyTLSOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
ALPN []string `proxy:"alpn,omitempty"`
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
UDP bool `proxy:"udp,omitempty"`
IdleSessionCheckInterval int `proxy:"idle-session-check-interval,omitempty"`
IdleSessionTimeout int `proxy:"idle-session-timeout,omitempty"`
MinIdleSession int `proxy:"min-idle-session,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
ALPN []string `proxy:"alpn,omitempty"`
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
ShadowTLSOpts ShadowTLSOptions `proxy:"shadow-tls-opts,omitempty"`
RestlsOpts RestlsOptions `proxy:"restls-opts,omitempty"`
JLSOpts JLSOptions `proxy:"jls-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
UDP bool `proxy:"udp,omitempty"`
IdleSessionCheckInterval int `proxy:"idle-session-check-interval,omitempty"`
IdleSessionTimeout int `proxy:"idle-session-timeout,omitempty"`
MinIdleSession int `proxy:"min-idle-session,omitempty"`
DisableReuse bool `proxy:"disable-reuse,omitempty"`
}
func (t *AnyTLS) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
@@ -110,20 +117,50 @@ func NewAnyTLS(option AnyTLSOption) (*AnyTLS, error) {
IdleSessionCheckInterval: time.Duration(option.IdleSessionCheckInterval) * time.Second,
IdleSessionTimeout: time.Duration(option.IdleSessionTimeout) * time.Second,
MinIdleSession: option.MinIdleSession,
DisableReuse: option.DisableReuse,
}
echConfig, err := option.ECHOpts.Parse()
if err != nil {
return nil, err
}
shadowTLSConfig, err := option.ShadowTLSOpts.Parse()
if err != nil {
return nil, err
}
restlsConfig, err := option.RestlsOpts.Parse(option.SNI, option.ClientFingerprint)
if err != nil {
return nil, err
}
jlsConfig, err := option.JLSOpts.Parse()
if err != nil {
return nil, err
}
securityModes := make([]string, 0, 3)
if shadowTLSConfig != nil {
securityModes = append(securityModes, "ShadowTLS")
}
if restlsConfig != nil {
securityModes = append(securityModes, "Restls")
}
if jlsConfig != nil {
securityModes = append(securityModes, "JLS")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
tlsConfig := &vmess.TLSConfig{
Host: option.SNI,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
NextProtos: option.ALPN,
FingerPrint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
ECH: echConfig,
ShadowTLS: shadowTLSConfig,
Restls: restlsConfig,
JLS: jlsConfig,
}
if tlsConfig.Host == "" {
tlsConfig.Host = option.Server
+2
View File
@@ -29,6 +29,7 @@ type GostRelayOption struct {
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -100,6 +101,7 @@ func NewGostRelay(option GostRelayOption) (*GostRelay, error) {
Username: option.Username,
Password: option.Password,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
+5 -3
View File
@@ -35,6 +35,7 @@ type HttpOption struct {
TLS bool `proxy:"tls,omitempty"`
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -157,9 +158,10 @@ func NewHttp(option HttpOption) (*Http, error) {
InsecureSkipVerify: option.SkipCertVerify,
ServerName: sni,
},
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
Fingerprint: option.Fingerprint,
NameCertVerify: option.NameCertVerify,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
})
if err != nil {
return nil, err
+5 -3
View File
@@ -116,6 +116,7 @@ type HysteriaOption struct {
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -158,9 +159,10 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
InsecureSkipVerify: option.SkipCertVerify,
MinVersion: tls.VersionTLS13,
},
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
Fingerprint: option.Fingerprint,
NameCertVerify: option.NameCertVerify,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
})
if err != nil {
return nil, err
+10 -6
View File
@@ -53,6 +53,7 @@ type Hysteria2Option struct {
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -80,6 +81,7 @@ type Hysteria2RealmOption struct {
// for ServerURL
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -170,9 +172,10 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
InsecureSkipVerify: option.SkipCertVerify,
MinVersion: tls.VersionTLS13,
},
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
Fingerprint: option.Fingerprint,
NameCertVerify: option.NameCertVerify,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
})
if err != nil {
return nil, err
@@ -269,9 +272,10 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
InsecureSkipVerify: option.RealmOpts.SkipCertVerify,
NextProtos: option.RealmOpts.ALPN,
},
Fingerprint: option.RealmOpts.Fingerprint,
Certificate: option.RealmOpts.Certificate,
PrivateKey: option.RealmOpts.PrivateKey,
Fingerprint: option.RealmOpts.Fingerprint,
NameCertVerify: option.RealmOpts.NameCertVerify,
Certificate: option.RealmOpts.Certificate,
PrivateKey: option.RealmOpts.PrivateKey,
})
if err != nil {
return nil, err
+15
View File
@@ -0,0 +1,15 @@
package outbound
import "github.com/metacubex/mihomo/transport/jls"
type JLSOptions struct {
Username string `proxy:"username"`
Password string `proxy:"password"`
}
func (o JLSOptions) Parse() (*jls.Config, error) {
if o.Username == "" && o.Password == "" {
return nil, nil
}
return jls.NewConfig(o.Username, o.Password)
}
+1
View File
@@ -67,6 +67,7 @@ type MasqueOption struct {
UDP bool `proxy:"udp,omitempty"`
HandshakeTimeout int `proxy:"handshake-timeout,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"` // placeholder; MASQUE does not verify certificate names
Network string `proxy:"network,omitempty"`
CongestionController string `proxy:"congestion-controller,omitempty"`
+46 -36
View File
@@ -41,26 +41,31 @@ type OpenVPN struct {
type OpenVPNOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Proto string `proxy:"proto,omitempty"`
Dev string `proxy:"dev,omitempty"`
Cipher string `proxy:"cipher,omitempty"`
Auth string `proxy:"auth,omitempty"`
CompLZO string `proxy:"comp-lzo,omitempty"`
CA string `proxy:"ca"`
Cert string `proxy:"cert,omitempty"`
Key string `proxy:"key,omitempty"`
TLSCrypt string `proxy:"tls-crypt,omitempty"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
PeerInfo map[string]string `proxy:"peer-info,omitempty"`
Ping int `proxy:"ping,omitempty"`
PingRestart int `proxy:"ping-restart,omitempty"`
HandshakeTimeout int `proxy:"handshake-timeout,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Proto string `proxy:"proto,omitempty"`
Dev string `proxy:"dev,omitempty"`
Cipher string `proxy:"cipher,omitempty"`
DataCiphers []string `proxy:"data-ciphers,omitempty"`
DataCipherFallback string `proxy:"data-ciphers-fallback,omitempty"`
Auth string `proxy:"auth,omitempty"`
CompLZO string `proxy:"comp-lzo,omitempty"`
CA string `proxy:"ca"`
Cert string `proxy:"cert,omitempty"`
Key string `proxy:"key,omitempty"`
TLSAuth string `proxy:"tls-auth,omitempty"`
KeyDirection string `proxy:"key-direction,omitempty"`
TLSCrypt string `proxy:"tls-crypt,omitempty"`
TLSCryptV2 string `proxy:"tls-crypt-v2,omitempty"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
PeerInfo map[string]string `proxy:"peer-info,omitempty"`
Ping int `proxy:"ping,omitempty"`
PingRestart int `proxy:"ping-restart,omitempty"`
HandshakeTimeout int `proxy:"handshake-timeout,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
Dns []string `proxy:"dns,omitempty"`
@@ -71,22 +76,27 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
return nil, errors.New("openvpn handshake timeout must be non-negative")
}
cfg := &ovpn.ClientConfig{
RemoteHost: option.Server,
RemotePort: uint16(option.Port),
Proto: option.Proto,
Dev: option.Dev,
Cipher: option.Cipher,
Auth: option.Auth,
CompLZO: option.CompLZO,
CA: []byte(option.CA),
Cert: []byte(option.Cert),
Key: []byte(option.Key),
TLSCrypt: []byte(option.TLSCrypt),
Username: option.Username,
Password: option.Password,
PeerInfo: option.PeerInfo,
PingInterval: time.Duration(option.Ping) * time.Second,
PingRestart: time.Duration(option.PingRestart) * time.Second,
RemoteHost: option.Server,
RemotePort: uint16(option.Port),
Proto: option.Proto,
Dev: option.Dev,
Cipher: option.Cipher,
DataCiphers: option.DataCiphers,
FallbackCipher: option.DataCipherFallback,
Auth: option.Auth,
CompLZO: option.CompLZO,
CA: []byte(option.CA),
Cert: []byte(option.Cert),
Key: []byte(option.Key),
TLSAuth: []byte(option.TLSAuth),
KeyDirection: option.KeyDirection,
TLSCrypt: []byte(option.TLSCrypt),
TLSCryptV2: []byte(option.TLSCryptV2),
Username: option.Username,
Password: option.Password,
PeerInfo: option.PeerInfo,
PingInterval: time.Duration(option.Ping) * time.Second,
PingRestart: time.Duration(option.PingRestart) * time.Second,
}
if err := cfg.Prepare(); err != nil {
return nil, err
+16
View File
@@ -0,0 +1,16 @@
package outbound
import "github.com/metacubex/mihomo/transport/restls"
type RestlsOptions struct {
Password string `proxy:"password,omitempty"`
VersionHint string `proxy:"version-hint,omitempty"`
RestlsScript string `proxy:"restls-script,omitempty"`
}
func (o RestlsOptions) Parse(serverName, clientFingerprint string) (*restls.Config, error) {
if o.Password == "" && o.VersionHint == "" && o.RestlsScript == "" {
return nil, nil
}
return restls.NewRestlsConfig(serverName, o.Password, o.VersionHint, o.RestlsScript, clientFingerprint)
}
+193
View File
@@ -0,0 +1,193 @@
package outbound
import (
"context"
"net"
"strconv"
"time"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/ca"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/transport/shadowquic"
"github.com/metacubex/mihomo/transport/tuic"
"github.com/metacubex/jls-quic-go"
"github.com/metacubex/jls-tls"
)
type ShadowQuic struct {
*Base
option *ShadowQuicOption
client *shadowquic.Client
quicConfig *quic.Config
tlsConfig *tls.Config
}
type ShadowQuicOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
SNI string `proxy:"sni,omitempty"`
ALPN []string `proxy:"alpn,omitempty"`
QUICVersions []string `proxy:"quic-versions,omitempty"`
UDPOverStream bool `proxy:"udp-over-stream,omitempty"`
ZeroRTT bool `proxy:"zero-rtt,omitempty"`
KeepAliveInterval int `proxy:"keep-alive-interval,omitempty"`
CongestionController string `proxy:"congestion-controller,omitempty"`
Up string `proxy:"up,omitempty"`
Down string `proxy:"down,omitempty"`
CWND int `proxy:"cwnd,omitempty"`
BBRProfile string `proxy:"bbr-profile,omitempty"`
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
ReceiveWindow int `proxy:"recv-window,omitempty"`
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
MaxDatagramFrameSize int `proxy:"max-datagram-frame-size,omitempty"`
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
}
func (s *ShadowQuic) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
conn, err := s.client.DialContext(ctx, metadata)
if err != nil {
return nil, err
}
return NewConn(conn, s), nil
}
func (s *ShadowQuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
if err := s.ResolveUDP(ctx, metadata); err != nil {
return nil, err
}
pc, err := s.client.ListenPacket(ctx, metadata)
if err != nil {
return nil, err
}
return NewPacketConn(pc, s), nil
}
func (s *ShadowQuic) Close() error {
if s.client != nil {
return s.client.Close()
}
return nil
}
func (s *ShadowQuic) ProxyInfo() C.ProxyInfo {
info := s.Base.ProxyInfo()
info.DialerProxy = s.option.DialerProxy
return info
}
func NewShadowQuic(option ShadowQuicOption) (*ShadowQuic, error) {
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
serverName := option.SNI
if serverName == "" {
serverName = option.Server
}
tlsConfig := &tls.Config{
ServerName: serverName,
MinVersion: tls.VersionTLS13,
Time: ntp.Now,
RootCAs: ca.GetCertPool(),
}
if option.ALPN != nil {
tlsConfig.NextProtos = option.ALPN
} else {
tlsConfig.NextProtos = []string{"h3"}
}
tlsConfig.JLSConfig = &tls.JLSConfig{
Enable: true,
User: tls.JLSUser{
Username: option.Username,
Password: option.Password,
},
}
if option.ZeroRTT {
// DialEarly can only send 0-RTT data after TLS has cached a session
// ticket from an earlier connection to this server.
tlsConfig.ClientSessionCache = tls.NewLRUClientSessionCache(1)
}
if option.MaxDatagramFrameSize == 0 {
option.MaxDatagramFrameSize = 1400
}
if option.MaxOpenStreams == 0 {
option.MaxOpenStreams = 1024
}
if option.CWND == 0 {
option.CWND = 32
}
quicVersions := shadowquic.DefaultQUICVersions()
if len(option.QUICVersions) > 0 {
parsedVersions, _, err := shadowquic.ParseQUICVersionProfile(option.QUICVersions)
if err != nil {
return nil, err
}
quicVersions = parsedVersions
}
quicConfig := &quic.Config{
Versions: quicVersions,
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
MaxIncomingStreams: int64(option.MaxOpenStreams),
MaxIncomingUniStreams: int64(option.MaxOpenStreams),
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
MaxDatagramFrameSize: int64(option.MaxDatagramFrameSize),
EnableDatagrams: true,
}
if option.KeepAliveInterval > 0 {
quicConfig.KeepAlivePeriod = time.Duration(option.KeepAliveInterval) * time.Millisecond
}
if option.ReceiveWindowConn == 0 {
quicConfig.InitialStreamReceiveWindow = tuic.DefaultStreamReceiveWindow / 10
quicConfig.MaxStreamReceiveWindow = tuic.DefaultStreamReceiveWindow
}
if option.ReceiveWindow == 0 {
quicConfig.InitialConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow / 10
quicConfig.MaxConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow
}
outbound := &ShadowQuic{
Base: NewBase(BaseOption{
Name: option.Name,
Addr: addr,
Type: C.ShadowQuic,
ProviderName: option.ProviderName,
UDP: true,
Interface: option.Interface,
RoutingMark: option.RoutingMark,
Prefer: option.IPVersion,
}),
option: &option,
quicConfig: quicConfig,
tlsConfig: tlsConfig,
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
outbound.client = shadowquic.NewClient(&shadowquic.ClientOption{
UDPOverStream: option.UDPOverStream,
CongestionController: option.CongestionController,
SendBPS: utils.StringToBps(option.Up),
ReceiveBPS: utils.StringToBps(option.Down),
CWND: option.CWND,
BBRProfile: option.BBRProfile,
Dial: func(ctx context.Context) (*quic.Conn, error) {
_, quicConn, err := shadowquic.DialQuic(ctx, outbound.addr, outbound.DialOptions(), outbound.dialer, outbound.tlsConfig, outbound.quicConfig, option.ZeroRTT)
if err != nil {
return nil, err
}
return quicConn, nil
},
})
return outbound, nil
}
+39 -2
View File
@@ -11,10 +11,11 @@ import (
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/ntp"
gost "github.com/metacubex/mihomo/transport/gost"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/kcptun"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowtls"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
v2rayObfs "github.com/metacubex/mihomo/transport/v2ray-plugin"
shadowsocks "github.com/metacubex/sing-shadowsocks2"
@@ -35,6 +36,7 @@ type ShadowSocks struct {
gostOption *gost.Option
shadowTLSOption *shadowtls.ShadowTLSOption
restlsConfig *restls.Config
jlsConfig *jls.ClientConfig
kcptunClient *kcptun.Client
}
@@ -69,6 +71,7 @@ type v2rayObfsOption struct {
PrivateKey string `obfs:"private-key,omitempty"`
Headers map[string]string `obfs:"headers,omitempty"`
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
NameCertVerify string `obfs:"name-cert-verify,omitempty"`
Mux bool `obfs:"mux,omitempty"`
V2rayHttpUpgrade bool `obfs:"v2ray-http-upgrade,omitempty"`
V2rayHttpUpgradeFastOpen bool `obfs:"v2ray-http-upgrade-fast-open,omitempty"`
@@ -85,6 +88,7 @@ type gostObfsOption struct {
PrivateKey string `obfs:"private-key,omitempty"`
Headers map[string]string `obfs:"headers,omitempty"`
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
NameCertVerify string `obfs:"name-cert-verify,omitempty"`
Mux bool `obfs:"mux,omitempty"`
}
@@ -95,6 +99,7 @@ type shadowTLSOption struct {
Certificate string `obfs:"certificate,omitempty"`
PrivateKey string `obfs:"private-key,omitempty"`
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
NameCertVerify string `obfs:"name-cert-verify,omitempty"`
Version int `obfs:"version,omitempty"`
ALPN []string `obfs:"alpn,omitempty"`
}
@@ -106,9 +111,17 @@ type restlsOption struct {
RestlsScript string `obfs:"restls-script,omitempty"`
Fingerprint string `obfs:"fingerprint,omitempty"`
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
NameCertVerify string `obfs:"name-cert-verify,omitempty"`
ForceTLS12 bool `obfs:"force-tls12,omitempty"` // for test
}
type jlsOption struct {
Host string `obfs:"host"`
Username string `obfs:"username"`
Password string `obfs:"password"`
ALPN []string `obfs:"alpn,omitempty"`
}
type kcpTunOption struct {
Key string `obfs:"key,omitempty"`
Crypt string `obfs:"crypt,omitempty"`
@@ -169,6 +182,12 @@ func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metada
return nil, fmt.Errorf("%s (restls) connect error: %w", ss.addr, err)
}
useEarly = true
case jls.Mode:
c, err = jls.NewClient(ctx, c, ss.jlsConfig)
if err != nil {
return nil, fmt.Errorf("%s (jls) connect error: %w", ss.addr, err)
}
useEarly = true
}
useEarly = useEarly || N.NeedHandshake(c)
if !useEarly {
@@ -294,6 +313,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
var obfsOption *simpleObfsOption
var shadowTLSOpt *shadowtls.ShadowTLSOption
var restlsConfig *restls.Config
var jlsConfig *jls.ClientConfig
var kcptunClient *kcptun.Client
obfsMode := ""
@@ -331,6 +351,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
if opts.TLS {
v2rayOption.TLS = true
v2rayOption.SkipCertVerify = opts.SkipCertVerify
v2rayOption.NameCertVerify = opts.NameCertVerify
v2rayOption.Fingerprint = opts.Fingerprint
v2rayOption.Certificate = opts.Certificate
v2rayOption.PrivateKey = opts.PrivateKey
@@ -361,6 +382,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
if opts.TLS {
gostOption.TLS = true
gostOption.SkipCertVerify = opts.SkipCertVerify
gostOption.NameCertVerify = opts.NameCertVerify
gostOption.Fingerprint = opts.Fingerprint
gostOption.Certificate = opts.Certificate
gostOption.PrivateKey = opts.PrivateKey
@@ -388,6 +410,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
PrivateKey: opt.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
SkipCertVerify: opt.SkipCertVerify,
NameCertVerify: opt.NameCertVerify,
Version: opt.Version,
}
@@ -409,12 +432,25 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
}
restlsConfig.InsecureSkipVerify = restlsOpt.SkipCertVerify
if restlsOpt.Fingerprint != "" {
err = restls.SetFingerprint(restlsConfig, restlsOpt.Fingerprint)
err = restls.SetFingerprint(restlsConfig, restlsOpt.Fingerprint, restlsOpt.NameCertVerify)
if err != nil {
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
}
} else if restlsOpt.NameCertVerify != "" {
restls.SetNameCertVerify(restlsConfig, restlsOpt.NameCertVerify)
}
restlsConfig.ForceTLS12 = restlsOpt.ForceTLS12
} else if option.Plugin == jls.Mode {
obfsMode = jls.Mode
jlsOpt := &jlsOption{}
if err := decoder.Decode(option.PluginOpts, jlsOpt); err != nil {
return nil, fmt.Errorf("ss %s initialize jls-plugin error: %w", addr, err)
}
jlsConfig, err = jls.NewClientConfig(jlsOpt.Host, jlsOpt.Username, jlsOpt.Password, jlsOpt.ALPN)
if err != nil {
return nil, fmt.Errorf("ss %s initialize jls-plugin error: %w", addr, err)
}
jlsConfig.ClientFingerprint = option.ClientFingerprint
} else if option.Plugin == kcptun.Mode {
obfsMode = kcptun.Mode
kcptunOpt := &kcpTunOption{}
@@ -481,6 +517,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
obfsOption: obfsOption,
shadowTLSOption: shadowTLSOpt,
restlsConfig: restlsConfig,
jlsConfig: jlsConfig,
kcptunClient: kcptunClient,
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
+15
View File
@@ -0,0 +1,15 @@
package outbound
import "github.com/metacubex/mihomo/transport/shadowtls"
type ShadowTLSOptions struct {
Password string `proxy:"password,omitempty"`
Version int `proxy:"version,omitempty"`
}
func (o ShadowTLSOptions) Parse() (*shadowtls.Config, error) {
if o.Password == "" && o.Version == 0 {
return nil, nil
}
return shadowtls.NewConfig(o.Password, o.Version)
}
+52 -1
View File
@@ -9,8 +9,10 @@ import (
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/structure"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowtls"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
"github.com/metacubex/mihomo/transport/snell"
)
@@ -21,6 +23,8 @@ type Snell struct {
pool *snell.Pool
obfsOption *simpleObfsOption
shadowTLSOption *shadowtls.ShadowTLSOption
restlsConfig *restls.Config
jlsConfig *jls.ClientConfig
version int
reuse bool
}
@@ -51,6 +55,16 @@ func (s *Snell) streamConnContext(ctx context.Context, c net.Conn) (*snell.Snell
if err != nil {
return nil, err
}
case restls.Mode:
c, err = restls.NewRestls(ctx, c, s.restlsConfig)
if err != nil {
return nil, err
}
case jls.Mode:
c, err = jls.NewClient(ctx, c, s.jlsConfig)
if err != nil {
return nil, err
}
}
return snell.StreamConn(c, s.psk, s.version), nil
}
@@ -161,6 +175,8 @@ func NewSnell(option SnellOption) (*Snell, error) {
}
var shadowTLSOpt *shadowtls.ShadowTLSOption
var restlsConfig *restls.Config
var jlsConfig *jls.ClientConfig
switch obfsOption.Mode {
case "tls", "http", "":
break
@@ -180,6 +196,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
PrivateKey: opt.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
SkipCertVerify: opt.SkipCertVerify,
NameCertVerify: opt.NameCertVerify,
Version: opt.Version,
}
@@ -188,6 +205,38 @@ func NewSnell(option SnellOption) (*Snell, error) {
} else {
shadowTLSOpt.ALPN = shadowtls.DefaultALPN
}
case restls.Mode:
opt := &restlsOption{}
if err := decoder.Decode(option.ObfsOpts, opt); err != nil {
return nil, fmt.Errorf("snell %s initialize restls-plugin error: %w", addr, err)
}
var err error
restlsConfig, err = restls.NewRestlsConfig(opt.Host, opt.Password, opt.VersionHint, opt.RestlsScript, option.ClientFingerprint)
if err != nil {
return nil, fmt.Errorf("snell %s initialize restls-plugin error: %w", addr, err)
}
restlsConfig.InsecureSkipVerify = opt.SkipCertVerify
if opt.Fingerprint != "" {
if err = restls.SetFingerprint(restlsConfig, opt.Fingerprint, opt.NameCertVerify); err != nil {
return nil, fmt.Errorf("snell %s initialize restls-plugin error: %w", addr, err)
}
} else if opt.NameCertVerify != "" {
restls.SetNameCertVerify(restlsConfig, opt.NameCertVerify)
}
restlsConfig.ForceTLS12 = opt.ForceTLS12
case jls.Mode:
opt := &jlsOption{}
if err := decoder.Decode(option.ObfsOpts, opt); err != nil {
return nil, fmt.Errorf("snell %s initialize jls-plugin error: %w", addr, err)
}
var err error
jlsConfig, err = jls.NewClientConfig(opt.Host, opt.Username, opt.Password, opt.ALPN)
if err != nil {
return nil, fmt.Errorf("snell %s initialize jls-plugin error: %w", addr, err)
}
jlsConfig.ClientFingerprint = option.ClientFingerprint
default:
return nil, fmt.Errorf("snell %s obfs mode error: %s", addr, obfsOption.Mode)
}
@@ -228,6 +277,8 @@ func NewSnell(option SnellOption) (*Snell, error) {
psk: psk,
obfsOption: obfsOption,
shadowTLSOption: shadowTLSOpt,
restlsConfig: restlsConfig,
jlsConfig: jlsConfig,
version: option.Version,
reuse: reuse,
}
+5 -3
View File
@@ -37,6 +37,7 @@ type Socks5Option struct {
TLS bool `proxy:"tls,omitempty"`
UDP bool `proxy:"udp,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -178,9 +179,10 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
InsecureSkipVerify: option.SkipCertVerify,
ServerName: option.Server,
},
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
Fingerprint: option.Fingerprint,
NameCertVerify: option.NameCertVerify,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
})
if err != nil {
return nil, err
+32 -87
View File
@@ -19,8 +19,7 @@ type Sudoku struct {
option *SudokuOption
baseConf sudoku.ProtocolConfig
muxMu sync.Mutex
muxClient *sudoku.MultiplexClient
muxDialer *sudoku.MultiplexDialer
httpMaskMu sync.Mutex
httpMaskClient *httpmask.TunnelClient
@@ -43,7 +42,8 @@ type SudokuOption struct {
HTTPMaskTLS bool `proxy:"http-mask-tls,omitempty"` // only for http-mask-mode stream/poll/auto
HTTPMaskHost string `proxy:"http-mask-host,omitempty"` // optional Host/SNI override (domain or domain:port)
PathRoot string `proxy:"path-root,omitempty"` // optional first-level path prefix for HTTP tunnel endpoints
HTTPMaskMultiplex string `proxy:"http-mask-multiplex,omitempty"` // "off" (default), "auto" (reuse h1/h2), "on" (single tunnel, multi-target)
Multiplex string `proxy:"multiplex,omitempty"` // "off" (default), "auto" (HTTP reuse), "on" (session mux over raw TCP or HTTPMask)
HTTPMaskMultiplex string `proxy:"http-mask-multiplex,omitempty"` // legacy flat alias for multiplex
HTTPMaskOptions *SudokuHTTPMaskOptions `proxy:"httpmask,omitempty"`
CustomTable string `proxy:"custom-table,omitempty"` // optional custom byte layout, e.g. xpxvvpvv
CustomTables []string `proxy:"custom-tables,omitempty"` // optional table rotation patterns, overrides custom-table when non-empty
@@ -65,8 +65,7 @@ func (s *Sudoku) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Con
return nil, err
}
muxMode := normalizeHTTPMaskMultiplex(cfg.HTTPMaskMultiplex)
if muxMode == "on" {
if cfg.SessionMuxEnabled() {
stream, muxErr := s.dialMultiplex(ctx, cfg.TargetAddress)
if muxErr == nil {
return NewConn(stream, s), nil
@@ -172,9 +171,12 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
httpMaskTLS := option.HTTPMaskTLS
httpMaskHost := option.HTTPMaskHost
pathRoot := strings.TrimSpace(option.PathRoot)
httpMaskMultiplex := defaultConf.HTTPMaskMultiplex
if option.HTTPMaskMultiplex != "" {
httpMaskMultiplex = option.HTTPMaskMultiplex
multiplex := defaultConf.Multiplex
if mode := strings.TrimSpace(option.Multiplex); mode != "" {
multiplex = mode
}
if mode := strings.TrimSpace(option.HTTPMaskMultiplex); mode != "" {
multiplex = mode
}
if hm := option.HTTPMaskOptions; hm != nil {
@@ -188,9 +190,7 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
pathRoot = pr
}
if mux := strings.TrimSpace(hm.Multiplex); mux != "" {
httpMaskMultiplex = mux
} else {
httpMaskMultiplex = defaultConf.HTTPMaskMultiplex
multiplex = mux
}
}
@@ -207,7 +207,7 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
HTTPMaskTLSEnabled: httpMaskTLS,
HTTPMaskHost: httpMaskHost,
HTTPMaskPathRoot: pathRoot,
HTTPMaskMultiplex: httpMaskMultiplex,
Multiplex: multiplex,
}
tables, err := sudoku.NewClientTablesWithCustomPatterns(sudoku.ClientAEADSeed(option.Key), tableType, option.CustomTable, option.CustomTables)
if err != nil {
@@ -221,6 +221,9 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
if option.AEADMethod != "" {
baseConf.AEADMethod = option.AEADMethod
}
if err := baseConf.Validate(); err != nil {
return nil, err
}
outbound := &Sudoku{
Base: NewBase(BaseOption{
@@ -239,28 +242,26 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
baseConf: baseConf,
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
if baseConf.SessionMuxEnabled() {
outbound.muxDialer, err = sudoku.NewMultiplexDialer(func(ctx context.Context) (net.Conn, error) {
cfg := outbound.baseConf
return outbound.dialAndHandshake(ctx, &cfg)
})
if err != nil {
return nil, err
}
}
return outbound, nil
}
func (s *Sudoku) Close() error {
s.resetMuxClient()
if s.muxDialer != nil {
_ = s.muxDialer.Close()
}
s.resetHTTPMaskClient()
return s.Base.Close()
}
func normalizeHTTPMaskMultiplex(mode string) string {
switch strings.ToLower(strings.TrimSpace(mode)) {
case "", "off":
return "off"
case "auto":
return "auto"
case "on":
return "on"
default:
return "off"
}
}
func httpTunnelModeEnabled(mode string) bool {
switch strings.ToLower(strings.TrimSpace(mode)) {
case "stream", "poll", "auto", "ws":
@@ -289,7 +290,7 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
handshakeDone bool
)
if !cfg.DisableHTTPMask && httpTunnelModeEnabled(cfg.HTTPMaskMode) {
muxMode := normalizeHTTPMaskMultiplex(cfg.HTTPMaskMultiplex)
muxMode := cfg.MultiplexMode()
if muxMode == "auto" && strings.ToLower(strings.TrimSpace(cfg.HTTPMaskMode)) != "ws" {
if client, cerr := s.getOrCreateHTTPMaskClient(cfg); cerr == nil && client != nil {
c, err = client.DialTunnel(ctx, httpmask.TunnelDialOptions{
@@ -299,7 +300,7 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
PathRoot: cfg.HTTPMaskPathRoot,
AuthKey: sudoku.ClientAEADSeed(cfg.Key),
Upgrade: upgrade,
Multiplex: cfg.HTTPMaskMultiplex,
Multiplex: muxMode,
DialContext: s.dialer.DialContext,
})
if err != nil {
@@ -339,66 +340,10 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
}
func (s *Sudoku) dialMultiplex(ctx context.Context, targetAddress string) (net.Conn, error) {
for attempt := 0; attempt < 2; attempt++ {
client, err := s.getOrCreateMuxClient(ctx)
if err != nil {
return nil, err
}
stream, err := client.Dial(ctx, targetAddress)
if err != nil {
s.resetMuxClient()
continue
}
return stream, nil
}
return nil, fmt.Errorf("multiplex open stream failed")
}
func (s *Sudoku) getOrCreateMuxClient(ctx context.Context) (*sudoku.MultiplexClient, error) {
if s == nil {
return nil, fmt.Errorf("nil adapter")
}
s.muxMu.Lock()
if s.muxClient != nil && !s.muxClient.IsClosed() {
client := s.muxClient
s.muxMu.Unlock()
return client, nil
}
s.muxMu.Unlock()
s.muxMu.Lock()
defer s.muxMu.Unlock()
if s.muxClient != nil && !s.muxClient.IsClosed() {
return s.muxClient, nil
}
baseCfg := s.baseConf
baseConn, err := s.dialAndHandshake(ctx, &baseCfg)
if err != nil {
return nil, err
}
client, err := sudoku.StartMultiplexClient(baseConn)
if err != nil {
_ = baseConn.Close()
return nil, err
}
s.muxClient = client
return client, nil
}
func (s *Sudoku) resetMuxClient() {
s.muxMu.Lock()
defer s.muxMu.Unlock()
if s.muxClient != nil {
_ = s.muxClient.Close()
s.muxClient = nil
if s == nil || s.muxDialer == nil {
return nil, fmt.Errorf("multiplex dialer is unavailable")
}
return s.muxDialer.Dial(ctx, targetAddress)
}
func (s *Sudoku) resetHTTPMaskClient() {
+104 -38
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"net"
"strconv"
"strings"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/component/ca"
@@ -13,7 +14,10 @@ import (
tlsC "github.com/metacubex/mihomo/component/tls"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/gun"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowsocks/core"
"github.com/metacubex/mihomo/transport/shadowtls"
"github.com/metacubex/mihomo/transport/trojan"
"github.com/metacubex/mihomo/transport/vmess"
@@ -29,32 +33,39 @@ type Trojan struct {
// for gun mux
gunClient *gun.Client
realityConfig *tlsC.RealityConfig
echConfig *ech.Config
echConfig *ech.Config
shadowTLSConfig *shadowtls.Config
restlsConfig *restls.Config
jlsConfig *jls.Config
realityConfig *tlsC.RealityConfig
ssCipher core.Cipher
}
type TrojanOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
ALPN []string `proxy:"alpn,omitempty"`
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
UDP bool `proxy:"udp,omitempty"`
Network string `proxy:"network,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
SSOpts TrojanSSOption `proxy:"ss-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
ALPN []string `proxy:"alpn,omitempty"`
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
UDP bool `proxy:"udp,omitempty"`
Network string `proxy:"network,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
ShadowTLSOpts ShadowTLSOptions `proxy:"shadow-tls-opts,omitempty"`
RestlsOpts RestlsOptions `proxy:"restls-opts,omitempty"`
JLSOpts JLSOptions `proxy:"jls-opts,omitempty"`
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
SSOpts TrojanSSOption `proxy:"ss-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
}
// TrojanSSOption from https://github.com/p4gefau1t/trojan-go/blob/v0.10.6/tunnel/shadowsocks/config.go#L5
@@ -97,20 +108,40 @@ func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.
alpn = t.option.ALPN
}
wsOpts.TLS = true
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
NextProtos: alpn,
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: t.option.SkipCertVerify,
ServerName: t.option.SNI,
},
Fingerprint: t.option.Fingerprint,
Certificate: t.option.Certificate,
PrivateKey: t.option.PrivateKey,
})
if err != nil {
return nil, err
if t.shadowTLSConfig != nil || t.restlsConfig != nil || t.jlsConfig != nil {
c, err = vmess.StreamTLSConn(ctx, c, &vmess.TLSConfig{
Host: t.option.SNI,
SkipCertVerify: t.option.SkipCertVerify,
NameCertVerify: t.option.NameCertVerify,
FingerPrint: t.option.Fingerprint,
Certificate: t.option.Certificate,
PrivateKey: t.option.PrivateKey,
ClientFingerprint: t.option.ClientFingerprint,
NextProtos: []string{"http/1.1"},
ShadowTLS: t.shadowTLSConfig,
Restls: t.restlsConfig,
JLS: t.jlsConfig,
})
if err != nil {
return nil, err
}
} else {
wsOpts.TLS = true
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
NextProtos: alpn,
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: t.option.SkipCertVerify,
ServerName: t.option.SNI,
},
Fingerprint: t.option.Fingerprint,
NameCertVerify: t.option.NameCertVerify,
Certificate: t.option.Certificate,
PrivateKey: t.option.PrivateKey,
})
if err != nil {
return nil, err
}
}
c, err = vmess.StreamWebsocketConn(ctx, c, wsOpts)
@@ -126,12 +157,16 @@ func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.
c, err = vmess.StreamTLSConn(ctx, c, &vmess.TLSConfig{
Host: t.option.SNI,
SkipCertVerify: t.option.SkipCertVerify,
NameCertVerify: t.option.NameCertVerify,
FingerPrint: t.option.Fingerprint,
Certificate: t.option.Certificate,
PrivateKey: t.option.PrivateKey,
ClientFingerprint: t.option.ClientFingerprint,
NextProtos: alpn,
ECH: t.echConfig,
ShadowTLS: t.shadowTLSConfig,
Restls: t.restlsConfig,
JLS: t.jlsConfig,
Reality: t.realityConfig,
})
}
@@ -271,14 +306,41 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
t.dialer = option.NewDialer(t.DialOptions())
var err error
t.echConfig, err = option.ECHOpts.Parse()
if err != nil {
return nil, err
}
t.shadowTLSConfig, err = option.ShadowTLSOpts.Parse()
if err != nil {
return nil, err
}
t.restlsConfig, err = option.RestlsOpts.Parse(option.SNI, option.ClientFingerprint)
if err != nil {
return nil, err
}
t.jlsConfig, err = option.JLSOpts.Parse()
if err != nil {
return nil, err
}
t.realityConfig, err = option.RealityOpts.Parse()
if err != nil {
return nil, err
}
t.echConfig, err = option.ECHOpts.Parse()
if err != nil {
return nil, err
securityModes := make([]string, 0, 4)
if t.shadowTLSConfig != nil {
securityModes = append(securityModes, "ShadowTLS")
}
if t.restlsConfig != nil {
securityModes = append(securityModes, "Restls")
}
if t.jlsConfig != nil {
securityModes = append(securityModes, "JLS")
}
if t.realityConfig != nil {
securityModes = append(securityModes, "REALITY")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
if option.SSOpts.Enabled {
@@ -307,12 +369,16 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
tlsConfig := &vmess.TLSConfig{
Host: option.SNI,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
FingerPrint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
NextProtos: []string{"h2"},
ECH: t.echConfig,
ShadowTLS: t.shadowTLSConfig,
Restls: t.restlsConfig,
JLS: t.jlsConfig,
Reality: t.realityConfig,
}
+2
View File
@@ -29,6 +29,7 @@ type TrustTunnelOption struct {
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -124,6 +125,7 @@ func NewTrustTunnel(option TrustTunnelOption) (*TrustTunnel, error) {
tlsConfig := &vmess.TLSConfig{
Host: option.SNI,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
NextProtos: option.ALPN,
FingerPrint: option.Fingerprint,
Certificate: option.Certificate,
+5 -3
View File
@@ -54,6 +54,7 @@ type TuicOption struct {
CWND int `proxy:"cwnd,omitempty"`
BBRProfile string `proxy:"bbr-profile,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -138,9 +139,10 @@ func NewTuic(option TuicOption) (*Tuic, error) {
InsecureSkipVerify: option.SkipCertVerify,
MinVersion: tls.VersionTLS13,
},
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
Fingerprint: option.Fingerprint,
NameCertVerify: option.NameCertVerify,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
})
if err != nil {
return nil, err
+174 -45
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/metacubex/mihomo/common/convert"
@@ -16,6 +17,9 @@ import (
tlsC "github.com/metacubex/mihomo/component/tls"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/gun"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowtls"
"github.com/metacubex/mihomo/transport/tuic/common"
"github.com/metacubex/mihomo/transport/vless"
"github.com/metacubex/mihomo/transport/vless/encryption"
@@ -43,8 +47,11 @@ type Vless struct {
// for xhttp
xhttpClient *xhttp.Client
realityConfig *tlsC.RealityConfig
echConfig *ech.Config
echConfig *ech.Config
shadowTLSConfig *shadowtls.Config
restlsConfig *restls.Config
jlsConfig *jls.Config
realityConfig *tlsC.RealityConfig
}
type VlessOption struct {
@@ -63,6 +70,9 @@ type VlessOption struct {
Encryption string `proxy:"encryption,omitempty"`
Network string `proxy:"network,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
ShadowTLSOpts ShadowTLSOptions `proxy:"shadow-tls-opts,omitempty"`
RestlsOpts RestlsOptions `proxy:"restls-opts,omitempty"`
JLSOpts JLSOptions `proxy:"jls-opts,omitempty"`
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
@@ -71,6 +81,7 @@ type VlessOption struct {
XHTTPOpts XHTTPOptions `proxy:"xhttp-opts,omitempty"`
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -122,18 +133,22 @@ type XHTTPDownloadSettings struct {
Headers *map[string]string `proxy:"headers,omitempty"`
ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX
// proxy part
Server *string `proxy:"server,omitempty"`
Port *int `proxy:"port,omitempty"`
TLS *bool `proxy:"tls,omitempty"`
ALPN *[]string `proxy:"alpn,omitempty"`
ECHOpts *ECHOptions `proxy:"ech-opts,omitempty"`
RealityOpts *RealityOptions `proxy:"reality-opts,omitempty"`
SkipCertVerify *bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint *string `proxy:"fingerprint,omitempty"`
Certificate *string `proxy:"certificate,omitempty"`
PrivateKey *string `proxy:"private-key,omitempty"`
ServerName *string `proxy:"servername,omitempty"`
ClientFingerprint *string `proxy:"client-fingerprint,omitempty"`
Server *string `proxy:"server,omitempty"`
Port *int `proxy:"port,omitempty"`
TLS *bool `proxy:"tls,omitempty"`
ALPN *[]string `proxy:"alpn,omitempty"`
ECHOpts *ECHOptions `proxy:"ech-opts,omitempty"`
ShadowTLSOpts *ShadowTLSOptions `proxy:"shadow-tls-opts,omitempty"`
RestlsOpts *RestlsOptions `proxy:"restls-opts,omitempty"`
JLSOpts *JLSOptions `proxy:"jls-opts,omitempty"`
RealityOpts *RealityOptions `proxy:"reality-opts,omitempty"`
SkipCertVerify *bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify *string `proxy:"name-cert-verify,omitempty"`
Fingerprint *string `proxy:"fingerprint,omitempty"`
Certificate *string `proxy:"certificate,omitempty"`
PrivateKey *string `proxy:"private-key,omitempty"`
ServerName *string `proxy:"servername,omitempty"`
ClientFingerprint *string `proxy:"client-fingerprint,omitempty"`
}
func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
@@ -159,25 +174,46 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
}
}
if v.option.TLS {
wsOpts.TLS = true
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
ServerName: host,
InsecureSkipVerify: v.option.SkipCertVerify,
NextProtos: []string{"http/1.1"},
},
Fingerprint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
})
if err != nil {
return nil, err
serverName := host
if v.option.ServerName != "" {
serverName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
serverName = host
}
if v.option.ServerName != "" {
wsOpts.TLSConfig.ServerName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
wsOpts.TLSConfig.ServerName = host
if v.shadowTLSConfig != nil || v.restlsConfig != nil || v.jlsConfig != nil {
c, err = vmess.StreamTLSConn(ctx, c, &vmess.TLSConfig{
Host: serverName,
SkipCertVerify: v.option.SkipCertVerify,
NameCertVerify: v.option.NameCertVerify,
FingerPrint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
ClientFingerprint: v.option.ClientFingerprint,
NextProtos: []string{"http/1.1"},
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
})
if err != nil {
return nil, err
}
} else {
wsOpts.TLS = true
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
ServerName: serverName,
InsecureSkipVerify: v.option.SkipCertVerify,
NextProtos: []string{"http/1.1"},
},
Fingerprint: v.option.Fingerprint,
NameCertVerify: v.option.NameCertVerify,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
})
if err != nil {
return nil, err
}
}
} else {
if host := wsOpts.Headers.Get("Host"); host == "" {
@@ -273,11 +309,15 @@ func (v *Vless) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (ne
tlsOpts := vmess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
NameCertVerify: v.option.NameCertVerify,
FingerPrint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
ClientFingerprint: v.option.ClientFingerprint,
ECH: v.echConfig,
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
Reality: v.realityConfig,
NextProtos: v.option.ALPN,
}
@@ -472,14 +512,48 @@ func NewVless(option VlessOption) (*Vless, error) {
return nil, err
}
v.echConfig, err = v.option.ECHOpts.Parse()
if err != nil {
return nil, err
}
v.shadowTLSConfig, err = option.ShadowTLSOpts.Parse()
if err != nil {
return nil, err
}
v.restlsConfig, err = option.RestlsOpts.Parse(option.ServerName, option.ClientFingerprint)
if err != nil {
return nil, err
}
v.jlsConfig, err = option.JLSOpts.Parse()
if err != nil {
return nil, err
}
v.realityConfig, err = v.option.RealityOpts.Parse()
if err != nil {
return nil, err
}
v.echConfig, err = v.option.ECHOpts.Parse()
if err != nil {
return nil, err
securityModes := make([]string, 0, 4)
if v.shadowTLSConfig != nil {
securityModes = append(securityModes, "ShadowTLS")
}
if v.restlsConfig != nil {
securityModes = append(securityModes, "Restls")
}
if v.jlsConfig != nil {
securityModes = append(securityModes, "JLS")
}
if v.realityConfig != nil {
securityModes = append(securityModes, "REALITY")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
securityMode := ""
if len(securityModes) == 1 {
securityMode = securityModes[0]
}
if securityMode != "" && !option.TLS {
return nil, fmt.Errorf("%s requires TLS", securityMode)
}
switch option.Network {
@@ -510,12 +584,16 @@ func NewVless(option VlessOption) (*Vless, error) {
tlsConfig = &vmess.TLSConfig{
Host: option.ServerName,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
FingerPrint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
NextProtos: []string{"h2"},
ECH: v.echConfig,
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
Reality: v.realityConfig,
}
if option.ServerName == "" {
@@ -596,6 +674,7 @@ func NewVless(option VlessOption) (*Vless, error) {
tlsOpts := &vmess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
NameCertVerify: v.option.NameCertVerify,
FingerPrint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
@@ -610,8 +689,8 @@ func NewVless(option VlessOption) (*Vless, error) {
if !v.option.TLS {
return nil, errors.New("xhttp HTTP/3 requires TLS")
}
if v.realityConfig != nil {
return nil, errors.New("xhttp HTTP/3 does not support reality")
if securityMode != "" {
return nil, fmt.Errorf("xhttp HTTP/3 does not support %s", securityMode)
}
tlsConfig, err := tlsOpts.ToStdConfig()
if err != nil {
@@ -643,6 +722,13 @@ func NewVless(option VlessOption) (*Vless, error) {
downloadPort := lo.FromPtrOr(ds.Port, v.option.Port)
downloadTLS := lo.FromPtrOr(ds.TLS, v.option.TLS)
downloadALPN := lo.FromPtrOr(ds.ALPN, v.option.ALPN)
downloadSkipCertVerify := lo.FromPtrOr(ds.SkipCertVerify, v.option.SkipCertVerify)
downloadNameCertVerify := lo.FromPtrOr(ds.NameCertVerify, v.option.NameCertVerify)
downloadFingerprint := lo.FromPtrOr(ds.Fingerprint, v.option.Fingerprint)
downloadCertificate := lo.FromPtrOr(ds.Certificate, v.option.Certificate)
downloadPrivateKey := lo.FromPtrOr(ds.PrivateKey, v.option.PrivateKey)
downloadServerName := lo.FromPtrOr(ds.ServerName, v.option.ServerName)
downloadClientFingerprint := lo.FromPtrOr(ds.ClientFingerprint, v.option.ClientFingerprint)
downloadEchConfig := v.echConfig
if ds.ECHOpts != nil {
downloadEchConfig, err = ds.ECHOpts.Parse()
@@ -650,6 +736,27 @@ func NewVless(option VlessOption) (*Vless, error) {
return nil, err
}
}
downloadShadowTLSConfig := v.shadowTLSConfig
if ds.ShadowTLSOpts != nil {
downloadShadowTLSConfig, err = ds.ShadowTLSOpts.Parse()
if err != nil {
return nil, err
}
}
downloadRestlsConfig := v.restlsConfig
if ds.RestlsOpts != nil {
downloadRestlsConfig, err = ds.RestlsOpts.Parse(downloadServerName, downloadClientFingerprint)
if err != nil {
return nil, err
}
}
downloadJLSConfig := v.jlsConfig
if ds.JLSOpts != nil {
downloadJLSConfig, err = ds.JLSOpts.Parse()
if err != nil {
return nil, err
}
}
downloadRealityCfg := v.realityConfig
if ds.RealityOpts != nil {
downloadRealityCfg, err = ds.RealityOpts.Parse()
@@ -657,12 +764,29 @@ func NewVless(option VlessOption) (*Vless, error) {
return nil, err
}
}
downloadSkipCertVerify := lo.FromPtrOr(ds.SkipCertVerify, v.option.SkipCertVerify)
downloadFingerprint := lo.FromPtrOr(ds.Fingerprint, v.option.Fingerprint)
downloadCertificate := lo.FromPtrOr(ds.Certificate, v.option.Certificate)
downloadPrivateKey := lo.FromPtrOr(ds.PrivateKey, v.option.PrivateKey)
downloadServerName := lo.FromPtrOr(ds.ServerName, v.option.ServerName)
downloadClientFingerprint := lo.FromPtrOr(ds.ClientFingerprint, v.option.ClientFingerprint)
downloadSecurityModes := make([]string, 0, 4)
if downloadShadowTLSConfig != nil {
downloadSecurityModes = append(downloadSecurityModes, "ShadowTLS")
}
if downloadRestlsConfig != nil {
downloadSecurityModes = append(downloadSecurityModes, "Restls")
}
if downloadJLSConfig != nil {
downloadSecurityModes = append(downloadSecurityModes, "JLS")
}
if downloadRealityCfg != nil {
downloadSecurityModes = append(downloadSecurityModes, "REALITY")
}
if len(downloadSecurityModes) > 1 {
return nil, errors.New("xhttp download-settings security modes are mutually exclusive: " + strings.Join(downloadSecurityModes, ", "))
}
downloadSecurityMode := ""
if len(downloadSecurityModes) == 1 {
downloadSecurityMode = downloadSecurityModes[0]
}
if downloadSecurityMode != "" && !downloadTLS {
return nil, fmt.Errorf("xhttp download-settings: %s requires TLS", downloadSecurityMode)
}
downloadAddr := net.JoinHostPort(downloadServer, strconv.Itoa(downloadPort))
@@ -707,11 +831,15 @@ func NewVless(option VlessOption) (*Vless, error) {
tlsOpts := vmess.TLSConfig{
Host: host,
SkipCertVerify: downloadSkipCertVerify,
NameCertVerify: downloadNameCertVerify,
FingerPrint: downloadFingerprint,
Certificate: downloadCertificate,
PrivateKey: downloadPrivateKey,
ClientFingerprint: downloadClientFingerprint,
ECH: downloadEchConfig,
ShadowTLS: downloadShadowTLSConfig,
Restls: downloadRestlsConfig,
JLS: downloadJLSConfig,
Reality: downloadRealityCfg,
NextProtos: downloadALPN,
}
@@ -734,6 +862,7 @@ func NewVless(option VlessOption) (*Vless, error) {
tlsOpts := &vmess.TLSConfig{
Host: host,
SkipCertVerify: downloadSkipCertVerify,
NameCertVerify: downloadNameCertVerify,
FingerPrint: downloadFingerprint,
Certificate: downloadCertificate,
PrivateKey: downloadPrivateKey,
@@ -748,8 +877,8 @@ func NewVless(option VlessOption) (*Vless, error) {
if !downloadTLS {
return nil, errors.New("xhttp HTTP/3 requires TLS")
}
if downloadRealityCfg != nil {
return nil, errors.New("xhttp HTTP/3 does not support reality")
if downloadSecurityMode != "" {
return nil, fmt.Errorf("xhttp HTTP/3 does not support %s", downloadSecurityMode)
}
tlsConfig, err := tlsOpts.ToStdConfig()
if err != nil {
+97 -17
View File
@@ -18,8 +18,11 @@ import (
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/transport/gun"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/mekya"
"github.com/metacubex/mihomo/transport/mkcp"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowtls"
mihomoVMess "github.com/metacubex/mihomo/transport/vmess"
"github.com/metacubex/http"
@@ -40,8 +43,11 @@ type Vmess struct {
gunClient *gun.Client
mekyaClient *mekya.Client
realityConfig *tlsC.RealityConfig
echConfig *ech.Config
echConfig *ech.Config
shadowTLSConfig *shadowtls.Config
restlsConfig *restls.Config
jlsConfig *jls.Config
realityConfig *tlsC.RealityConfig
}
type VmessOption struct {
@@ -57,11 +63,15 @@ type VmessOption struct {
TLS bool `proxy:"tls,omitempty"`
ALPN []string `proxy:"alpn,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
ServerName string `proxy:"servername,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
ShadowTLSOpts ShadowTLSOptions `proxy:"shadow-tls-opts,omitempty"`
RestlsOpts RestlsOptions `proxy:"restls-opts,omitempty"`
JLSOpts JLSOptions `proxy:"jls-opts,omitempty"`
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
TLSMirrorOpts TLSMirrorOptions `proxy:"tlsmirror-opts,omitempty"`
MekyaOpts MekyaOptions `proxy:"mekya-opts,omitempty"`
@@ -185,7 +195,31 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
}
if v.option.TLS {
if v.option.TLSMirrorOpts.PrimaryKey != "" {
serverName := host
if v.option.ServerName != "" {
serverName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
serverName = host
}
if v.shadowTLSConfig != nil || v.restlsConfig != nil || v.jlsConfig != nil {
c, err = mihomoVMess.StreamTLSConn(ctx, c, &mihomoVMess.TLSConfig{
Host: serverName,
SkipCertVerify: v.option.SkipCertVerify,
NameCertVerify: v.option.NameCertVerify,
FingerPrint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
ClientFingerprint: v.option.ClientFingerprint,
NextProtos: []string{"http/1.1"},
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
})
if err != nil {
return nil, err
}
} else if v.option.TLSMirrorOpts.PrimaryKey != "" {
c, err = v.streamTLSConn(ctx, c, false)
if err != nil {
return nil, err
@@ -194,23 +228,18 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
wsOpts.TLS = true
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
ServerName: host,
ServerName: serverName,
InsecureSkipVerify: v.option.SkipCertVerify,
NextProtos: []string{"http/1.1"},
},
Fingerprint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
Fingerprint: v.option.Fingerprint,
NameCertVerify: v.option.NameCertVerify,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
})
if err != nil {
return nil, err
}
if v.option.ServerName != "" {
wsOpts.TLSConfig.ServerName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
wsOpts.TLSConfig.ServerName = host
}
}
}
c, err = mihomoVMess.StreamWebsocketConn(ctx, c, wsOpts)
@@ -321,11 +350,15 @@ func (v *Vmess) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (ne
tlsOpts := mihomoVMess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
NameCertVerify: v.option.NameCertVerify,
FingerPrint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
ClientFingerprint: v.option.ClientFingerprint,
ECH: v.echConfig,
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
Reality: v.realityConfig,
NextProtos: v.option.ALPN,
TLSMirror: v.option.TLSMirrorOpts.Build(),
@@ -477,14 +510,57 @@ func NewVmess(option VmessOption) (*Vmess, error) {
}
v.dialer = option.NewDialer(v.DialOptions())
v.echConfig, err = v.option.ECHOpts.Parse()
if err != nil {
return nil, err
}
v.shadowTLSConfig, err = option.ShadowTLSOpts.Parse()
if err != nil {
return nil, err
}
v.restlsConfig, err = option.RestlsOpts.Parse(option.ServerName, option.ClientFingerprint)
if err != nil {
return nil, err
}
v.jlsConfig, err = option.JLSOpts.Parse()
if err != nil {
return nil, err
}
v.realityConfig, err = v.option.RealityOpts.Parse()
if err != nil {
return nil, err
}
v.echConfig, err = v.option.ECHOpts.Parse()
if err != nil {
return nil, err
securityModes := make([]string, 0, 5)
if v.shadowTLSConfig != nil {
securityModes = append(securityModes, "ShadowTLS")
}
if v.restlsConfig != nil {
securityModes = append(securityModes, "Restls")
}
if v.jlsConfig != nil {
securityModes = append(securityModes, "JLS")
}
if v.realityConfig != nil {
securityModes = append(securityModes, "REALITY")
}
if option.TLSMirrorOpts.PrimaryKey != "" {
securityModes = append(securityModes, "TLSMirror")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
securityMode := ""
if len(securityModes) == 1 {
securityMode = securityModes[0]
}
if securityMode != "" && !option.TLS {
return nil, fmt.Errorf("%s requires TLS", securityMode)
}
if option.Network == "mkcp" || option.Network == "kcp" {
switch securityMode {
case "ShadowTLS", "Restls", "JLS":
return nil, fmt.Errorf("%s only supports TCP transports", securityMode)
}
}
switch option.Network {
@@ -538,12 +614,16 @@ func NewVmess(option VmessOption) (*Vmess, error) {
tlsConfig = &mihomoVMess.TLSConfig{
Host: option.ServerName,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
FingerPrint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
NextProtos: []string{"h2"},
ECH: v.echConfig,
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
Reality: v.realityConfig,
TLSMirror: option.TLSMirrorOpts.Build(),
TLSMirrorDialer: proxydialer.New(v, false).DialContext,
+1 -1
View File
@@ -482,7 +482,7 @@ func (w *WireGuard) genIpcConf(ctx context.Context, updateOnly bool) (string, er
ipcConf += "endpoint=" + destination.String() + "\n"
if len(peer.Reserved) > 0 {
var reserved [3]uint8
copy(reserved[:], w.option.Reserved)
copy(reserved[:], peer.Reserved)
w.bind.SetReservedForEndpoint(destination, reserved)
}
if updateOnly {
+7
View File
@@ -111,6 +111,13 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error)
break
}
proxy, err = outbound.NewTuic(*tuicOption)
case "shadowquic":
shadowQuicOption := &outbound.ShadowQuicOption{BasicOption: basicOption}
err = decoder.Decode(mapping, shadowQuicOption)
if err != nil {
break
}
proxy, err = outbound.NewShadowQuic(*shadowQuicOption)
case "gost-relay":
relayOption := &outbound.GostRelayOption{BasicOption: basicOption}
err = decoder.Decode(mapping, relayOption)
+10
View File
@@ -16,6 +16,7 @@ type overrideSchema struct {
Down *string `provider:"down,omitempty"`
DialerProxy *string `provider:"dialer-proxy,omitempty"`
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
NameCertVerify *string `provider:"name-cert-verify,omitempty"`
Interface *string `provider:"interface-name,omitempty"`
RoutingMark *int `provider:"routing-mark,omitempty"`
IPVersion *string `provider:"ip-version,omitempty"`
@@ -23,6 +24,7 @@ type overrideSchema struct {
AdditionalPrefix *string `provider:"additional-prefix,omitempty"`
AdditionalSuffix *string `provider:"additional-suffix,omitempty"`
ProxyName []overrideProxyNameSchema `provider:"proxy-name,omitempty"`
OverrideExpr []OverrideExpr `provider:"override-expr,omitempty"`
}
type overrideProxyNameSchema struct {
@@ -59,6 +61,9 @@ func (o *overrideSchema) Apply(mapping map[string]any) error {
if o.SkipCertVerify != nil {
mapping["skip-cert-verify"] = *o.SkipCertVerify
}
if o.NameCertVerify != nil {
mapping["name-cert-verify"] = *o.NameCertVerify
}
if o.Interface != nil {
mapping["interface-name"] = *o.Interface
}
@@ -83,6 +88,11 @@ func (o *overrideSchema) Apply(mapping map[string]any) error {
if o.AdditionalSuffix != nil {
mapping["name"] = fmt.Sprintf("%s%s", mapping["name"], *o.AdditionalSuffix)
}
for idx, expr := range o.OverrideExpr {
if err := expr.Apply(mapping); err != nil {
return fmt.Errorf("override-expr[%d] %q: %w", idx, expr.String(), err)
}
}
return nil
}
File diff suppressed because it is too large. Load diff
+488
View File
@@ -0,0 +1,488 @@
package provider
import (
"math"
"testing"
"github.com/stretchr/testify/require"
"github.com/metacubex/mihomo/common/structure"
)
func mustOverrideExprs(t *testing.T, sources ...string) []OverrideExpr {
t.Helper()
expressions := make([]OverrideExpr, len(sources))
for idx, source := range sources {
expr, err := NewOverrideExpr(source)
require.NoError(t, err)
expressions[idx] = expr
}
return expressions
}
func TestOverrideExprDecode(t *testing.T) {
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
var schema overrideSchema
err := decoder.Decode(map[string]any{
"override-expr": []any{
".udp = true",
`.name = "prefix-" + .name`,
},
}, &schema)
require.NoError(t, err)
require.Len(t, schema.OverrideExpr, 2)
require.Equal(t, ".udp = true", schema.OverrideExpr[0].String())
require.Equal(t, `.name = "prefix-" + .name`, schema.OverrideExpr[1].String())
}
func TestOverrideExprTextRoundTrip(t *testing.T) {
const source = ` .name = "prefix-" + .name # keep formatting`
var expr OverrideExpr
require.NoError(t, expr.UnmarshalText([]byte(source)))
text, err := expr.MarshalText()
require.NoError(t, err)
require.Equal(t, source, string(text))
require.Equal(t, source, expr.String())
}
func TestOverrideExprAssignments(t *testing.T) {
mapping := map[string]any{
"name": "node",
"existing": "keep",
"ports": []any{80, 443},
"tags": []any{"base"},
"weights": map[string]any{"a": 1, "b": 2},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.udp = true`,
`.skip-cert-verify = false`,
`.plugin-opts.mode = "tls"`,
`.ports[1] = 8443`,
`.slots[2].enabled = true`,
`.weights[] += 1`,
`."quoted.field" = "quoted"`,
`.tags += ["edge"]`,
`.missing = .missing // "fallback"`,
`.existing = .existing // "ignored"`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, true, mapping["udp"])
require.Equal(t, false, mapping["skip-cert-verify"])
require.Equal(t, map[string]any{"mode": "tls"}, mapping["plugin-opts"])
require.Equal(t, []any{80, 8443}, mapping["ports"])
require.Equal(t, []any{nil, nil, map[string]any{"enabled": true}}, mapping["slots"])
require.Equal(t, map[string]any{"a": 2, "b": 3}, mapping["weights"])
require.Equal(t, "quoted", mapping["quoted.field"])
require.Equal(t, []any{"base", "edge"}, mapping["tags"])
require.Equal(t, "fallback", mapping["missing"])
require.Equal(t, "keep", mapping["existing"])
}
func TestOverrideExprUpdateFunctionsAndConditionalPath(t *testing.T) {
mapping := map[string]any{
"name": "HK-01",
"score": 3,
"labels": []any{"edge", "premium"},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.name |= sub("^HK-(.*)$"; "Hong Kong $1")`,
`.name = "[Provider] " + .name`,
`.score *= 2`,
`.labels[] |= upcase`,
`.enabled = (.score >= 6 and has("name"))`,
`(select(.score > 5) | .tier) = "fast" | (select(.score <= 5) | .tier) = "slow"`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, "[Provider] Hong Kong 01", mapping["name"])
require.Equal(t, 6, mapping["score"])
require.Equal(t, []any{"EDGE", "PREMIUM"}, mapping["labels"])
require.Equal(t, true, mapping["enabled"])
require.Equal(t, "fast", mapping["tier"])
}
func TestOverrideExprCollectionsAndDelete(t *testing.T) {
mapping := map[string]any{
"password": "secret",
"obsolete": true,
"ports": []any{80, 443, 8080},
"options": map[string]any{
"tls": map[string]any{"sni": "example.com"},
},
"servers": []any{
map[string]any{"host": "a", "secret": "x"},
map[string]any{"host": "b", "secret": "y"},
},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.options *= {"tls": {"enabled": true}, "retries": 3}`,
`.ports -= [80, 8080]`,
`del(.password, .obsolete)`,
`del(.servers[].secret)`,
)}
require.NoError(t, override.Apply(mapping))
require.NotContains(t, mapping, "password")
require.NotContains(t, mapping, "obsolete")
require.Equal(t, []any{443}, mapping["ports"])
require.Equal(t, map[string]any{
"tls": map[string]any{"sni": "example.com", "enabled": true},
"retries": 3,
}, mapping["options"])
require.Equal(t, []any{
map[string]any{"host": "a"},
map[string]any{"host": "b"},
}, mapping["servers"])
}
func TestOverrideExprDeleteUsesOriginalArrayIndexes(t *testing.T) {
mapping := map[string]any{"values": []any{0, 1, 2, 3}}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, `del(.values[0], .values[2])`)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, []any{1, 3}, mapping["values"])
}
func TestOverrideExprRunsAfterStructuredOverride(t *testing.T) {
udp := true
override := overrideSchema{
UDP: &udp,
OverrideExpr: mustOverrideExprs(t, `.udp = false`),
}
mapping := map[string]any{"name": "node"}
require.NoError(t, override.Apply(mapping))
require.Equal(t, false, mapping["udp"])
}
func TestOverrideExprYQCompatibility(t *testing.T) {
mapping := map[string]any{
"name": "edge-01",
"key.with.dot": "quoted",
"items": []any{"first", "last"},
"csv": "a,b,c",
"number": "42",
"options": map[string]any{"b": 2, "a": 1},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.quoted = .["key.with.dot"]`,
`.quoted-again = ."key.with.dot"`,
`.last = .items[-1]`,
`.csv |= split(",") | .csv |= join("-")`,
`.number |= tonumber`,
`.name-length = .name | .name-length |= length`,
`.option-keys = .options | .option-keys |= keys`,
`.fallback = false // "default"`,
`.calculated = (5 + 3) * 2`,
`. = . * {"root-merged": true}`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, "quoted", mapping["quoted"])
require.Equal(t, "quoted", mapping["quoted-again"])
require.Equal(t, "last", mapping["last"])
require.Equal(t, "a-b-c", mapping["csv"])
require.Equal(t, 42, mapping["number"])
require.Equal(t, 7, mapping["name-length"])
require.Equal(t, []any{"a", "b"}, mapping["option-keys"])
require.Equal(t, "default", mapping["fallback"])
require.Equal(t, 16, mapping["calculated"])
require.Equal(t, true, mapping["root-merged"])
}
func TestOverrideExprOperatorsAndFunctions(t *testing.T) {
testCases := []struct {
name string
input any
expr string
expected any
}{
{name: "negative literal", input: 4, expr: `.value = -4`, expected: -4},
{name: "not", input: true, expr: `.value |= not`, expected: false},
{name: "numeric subtraction", input: 5, expr: `.value -= 2`, expected: 3},
{name: "division", input: 5, expr: `.value = .value / 2`, expected: 2.5},
{name: "string division", input: "a,b", expr: `.value = .value / ","`, expected: []any{"a", "b"}},
{name: "empty string division", input: "", expr: `.value = .value / ","`, expected: []any{}},
{name: "split null can default", input: nil, expr: `.value = (.value | split(",")) // "fallback"`, expected: "fallback"},
{name: "modulo", input: 5, expr: `.value = .value % 2`, expected: 1},
{name: "float modulo", input: 5.5, expr: `.value = .value % 2`, expected: 1.5},
{name: "repeat", input: "ab", expr: `.value *= 2`, expected: "abab"},
{name: "repeat with integer first", input: "ab", expr: `.value = 2 * .value`, expected: "abab"},
{name: "multiply null identity", input: []any{1}, expr: `.value = .value * null`, expected: []any{1}},
{name: "multiply arrays replaces left", input: []any{1}, expr: `.value = .value * [2]`, expected: []any{2}},
{name: "sub replaces all", input: "a-b-c", expr: `.value |= sub("-", "_")`, expected: "a_b_c"},
{name: "test", input: "edge-01", expr: `.value |= test("^edge-")`, expected: true},
{name: "contains string", input: "edge-01", expr: `.value |= contains("ge-")`, expected: true},
{name: "contains array", input: []any{1, 2}, expr: `.value |= contains([2])`, expected: true},
{name: "contains scalar", input: 2, expr: `.value |= contains(2)`, expected: true},
{name: "string plus number", input: "port-", expr: `.value = .value + 443`, expected: "port-443"},
{name: "array plus scalar", input: []any{1}, expr: `.value = .value + 2`, expected: []any{1, 2}},
{name: "null subtraction", input: nil, expr: `.value = .value - 2`, expected: 2},
{name: "shallow map addition", input: map[string]any{"a": 1, "nested": map[string]any{"left": true}}, expr: `.value += {"b": 2, "nested": {"right": true}}`, expected: map[string]any{"a": 1, "b": 2, "nested": map[string]any{"right": true}}},
{name: "not equal", input: 2, expr: `.value = .value != 1`, expected: true},
{name: "numeric types are distinct", input: 1, expr: `.value = .value == 1.0`, expected: false},
{name: "scalar equality uses text", input: 1, expr: `.value = .value == "1"`, expected: true},
{name: "boolean equality uses text", input: true, expr: `.value = .value == "true"`, expected: true},
{name: "less than", input: 1, expr: `.value = .value < 2`, expected: true},
{name: "boolean or", input: false, expr: `.value = (.value or true)`, expected: true},
{name: "trim downcase", input: " EDGE ", expr: `.value |= trim | .value |= downcase`, expected: "edge"},
{name: "comma function arguments", input: "a-b", expr: `.value |= sub("-", "_")`, expected: "a_b"},
{name: "to string", input: []any{1, 2}, expr: `.value |= tostring`, expected: "- 1\n- 2"},
{name: "map to string", input: map[string]any{"a": 1}, expr: `.value |= tostring`, expected: "a: 1"},
{name: "type", input: []any{1}, expr: `.value |= type`, expected: "!!seq"},
{name: "map type", input: map[string]any{"a": 1}, expr: `.value |= type`, expected: "!!map"},
{name: "array keys", input: []any{"a", "b"}, expr: `.value |= keys`, expected: []any{0, 1}},
{name: "has array index", input: []any{"a"}, expr: `.value |= has(0)`, expected: true},
{name: "has negative array index", input: []any{"a"}, expr: `.value |= has(-1)`, expected: true},
{name: "contains keeps scalar tags distinct", input: 1, expr: `.value |= contains(1.0)`, expected: false},
{name: "test accepts global option", input: "edge-edge", expr: `.value |= test("edge", "g")`, expected: true},
{name: "null alternative", input: nil, expr: `.value = ~ // "fallback"`, expected: "fallback"},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
mapping := map[string]any{"value": testCase.input}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, testCase.expr)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, testCase.expected, mapping["value"])
})
}
}
func TestOverrideExprDivisionAndModuloByZero(t *testing.T) {
mapping := map[string]any{"one": 1, "zero": 0, "float": 1.5}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.infinite = .one / .zero`,
`.not-a-number = .zero / .zero`,
`.float-modulo = .float % .zero`,
)}
require.NoError(t, override.Apply(mapping))
require.True(t, math.IsInf(mapping["infinite"].(float64), 1))
require.True(t, math.IsNaN(mapping["not-a-number"].(float64)))
require.True(t, math.IsNaN(mapping["float-modulo"].(float64)))
}
func TestOverrideExprSelectAndPipelines(t *testing.T) {
mapping := map[string]any{
"name": " edge ",
"score": 8,
"servers": []any{
map[string]any{"name": "first", "enabled": true},
map[string]any{"name": "second", "enabled": false},
},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.name = (.name | trim | upcase)`,
`(select(.score > 5) | .tier) = "fast"`,
`(select(.score < 0) | .ignored) = true`,
`(.servers[] | select(.enabled) | .name) |= upcase`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, "EDGE", mapping["name"])
require.Equal(t, "fast", mapping["tier"])
require.NotContains(t, mapping, "ignored")
require.Equal(t, []any{
map[string]any{"name": "FIRST", "enabled": true},
map[string]any{"name": "second", "enabled": false},
}, mapping["servers"])
lowScore := map[string]any{"score": 3}
conditional := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`(select(.score > 5) | .tier) = "fast" | (select(.score <= 5) | .tier) = "slow"`,
)}
require.NoError(t, conditional.Apply(lowScore))
require.Equal(t, "slow", lowScore["tier"])
}
func TestOverrideExprYQBehaviorDetails(t *testing.T) {
testCases := []struct {
name string
input any
expr string
expected any
}{
{name: "scalar path produces null", input: "text", expr: `.result = .value.missing`, expected: nil},
{name: "scalar path can default", input: "text", expr: `.result = .value.missing // "fallback"`, expected: "fallback"},
{name: "recursive contains array", input: []any{map[string]any{"a": 1, "b": 2}}, expr: `.result = (.value | contains([{"a": 1}]))`, expected: true},
{name: "recursive contains map", input: map[string]any{"a": map[string]any{"b": 1, "c": 2}}, expr: `.result = (.value | contains({"a": {"b": 1}}))`, expected: true},
{name: "float type", input: 1.0, expr: `.result = (.value | type)`, expected: "!!float"},
{name: "number length", input: 1234, expr: `.result = (.value | length)`, expected: 4},
{name: "bool length", input: false, expr: `.result = (.value | length)`, expected: 5},
{name: "null length", input: nil, expr: `.result = (.value | length)`, expected: 0},
{name: "array length", input: []any{1, 2}, expr: `.result = (.value | length)`, expected: 2},
{name: "map length", input: map[string]any{"a": 1, "b": 2}, expr: `.result = (.value | length)`, expected: 2},
{name: "unicode byte length", input: "a界", expr: `.result = (.value | length)`, expected: 4},
{name: "join skips collections", input: []any{"a", nil, []any{1}, map[string]any{"a": 1}, 2}, expr: `.result = (.value | join("-"))`, expected: "a----2"},
{name: "has rejects float index", input: []any{"a"}, expr: `.result = (.value | has(0.5))`, expected: false},
{name: "decimal leading zero", input: "010", expr: `.result = (.value | tonumber)`, expected: 10},
{name: "octal", input: "0o10", expr: `.result = (.value | tonumber)`, expected: 8},
{name: "hexadecimal", input: "0x10", expr: `.result = (.value | tonumber)`, expected: 16},
{name: "float", input: "1.5", expr: `.result = (.value | tonumber)`, expected: 1.5},
{name: "unknown string escape stays literal", input: nil, expr: `.result = "a\tb\u754c"`, expected: `a\tb\u754c`},
{name: "array equality", input: []any{1, 2}, expr: `.result = (.value == [1, 2])`, expected: false},
{name: "mapping inequality", input: map[string]any{"a": 1}, expr: `.result = (.value != {"a": 1})`, expected: true},
{name: "null comparison", input: nil, expr: `.result = (.value < false)`, expected: false},
{name: "null equality comparison", input: nil, expr: `.result = (.value <= null)`, expected: true},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
mapping := map[string]any{"value": testCase.input}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, testCase.expr)}
require.NoError(t, override.Apply(mapping))
require.Contains(t, mapping, "result")
require.Equal(t, testCase.expected, mapping["result"])
})
}
}
func TestOverrideExprInterpolationAndCollections(t *testing.T) {
mapping := map[string]any{
"name": "node",
"type": "ss",
"port": 443,
"options": map[string]any{"b": 2, "a": 1},
"mixed": []any{3, nil, false, 2, true},
"duplicates": []any{1, 1, "1", "1"},
"nested": []any{1, []any{2, []any{3}}},
"truthy": []any{nil, false, "value"},
"all-true": []any{1, "value", true},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.label = "[\(.type)] \(.name):\(.port)"`,
`.fallback-label = "\(.missing // \"default\")-\(.name)"`,
`.first-label = "\((.name, .type))"`,
`.options-text = "\(.options)"`,
`.hex = 0x10`,
`.reversed = (.mixed | reverse)`,
`.sorted = (.mixed | sort)`,
`.deduplicated = (.duplicates | unique)`,
`.flattened = (.nested | flatten)`,
`.flattened-once = (.nested | flatten(1))`,
`.has-truthy = (.truthy | any)`,
`.all-truthy = (.all-true | all)`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, "[ss] node:443", mapping["label"])
require.Equal(t, "default-node", mapping["fallback-label"])
require.Equal(t, "node", mapping["first-label"])
require.Equal(t, "a: 1\nb: 2", mapping["options-text"])
require.Equal(t, 16, mapping["hex"])
require.Equal(t, []any{true, 2, false, nil, 3}, mapping["reversed"])
require.Equal(t, []any{nil, false, true, 2, 3}, mapping["sorted"])
require.Equal(t, []any{1}, mapping["deduplicated"])
require.Equal(t, []any{1, 2, 3}, mapping["flattened"])
require.Equal(t, []any{1, 2, []any{3}}, mapping["flattened-once"])
require.Equal(t, true, mapping["has-truthy"])
require.Equal(t, true, mapping["all-truthy"])
}
func TestOverrideExprMultiResultPipelines(t *testing.T) {
mapping := map[string]any{
"items": []any{
map[string]any{"name": "first", "port": 80, "enabled": true},
map[string]any{"name": "second", "port": 443, "enabled": false},
},
"scores": map[string]any{"a": 1, "b": 2},
"options": map[string]any{"a": 1, "b": 2},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.names = [.items[].name]`,
`.enabled-names = [.items[] | select(.enabled) | .name]`,
`.name-ports = [.items[] | (.name, .port)]`,
`.incremented-ports = [.items[].port + 1]`,
`.mapped-names = (.items | map(.name))`,
`.mapped-union = (.items | map(.name, .port))`,
`.filtered = (.items | filter(.enabled))`,
`.mapped-scores = (.scores | map_values(. + 1))`,
`.selected-scores = (.scores | map_values(select(. > 1)))`,
`.entries = (.options | to_entries)`,
`.roundtrip = (.options | to_entries | from_entries)`,
`.upper-options = (.options | with_entries(.key |= upcase))`,
`.has-large-port = ([.items[].port] | any_c(. > 100))`,
`.all-positive = ([.items[].port] | all_c(. > 0))`,
`.no-matches = [.items[] | select(false)]`,
`.defaults = [.items[].missing // "default"]`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, []any{"first", "second"}, mapping["names"])
require.Equal(t, []any{"first"}, mapping["enabled-names"])
require.Equal(t, []any{"first", "second", 80, 443}, mapping["name-ports"])
require.Equal(t, []any{81, 444}, mapping["incremented-ports"])
require.Equal(t, []any{"first", "second"}, mapping["mapped-names"])
require.Equal(t, []any{"first", "second", 80, 443}, mapping["mapped-union"])
require.Equal(t, []any{map[string]any{"name": "first", "port": 80, "enabled": true}}, mapping["filtered"])
require.Equal(t, map[string]any{"a": 2, "b": 3}, mapping["mapped-scores"])
require.Equal(t, map[string]any{"a": 1, "b": 2}, mapping["selected-scores"])
require.Equal(t, []any{
map[string]any{"key": "a", "value": 1},
map[string]any{"key": "b", "value": 2},
}, mapping["entries"])
require.Equal(t, map[string]any{"a": 1, "b": 2}, mapping["roundtrip"])
require.Equal(t, map[string]any{"A": 1, "B": 2}, mapping["upper-options"])
require.Equal(t, true, mapping["has-large-port"])
require.Equal(t, true, mapping["all-positive"])
require.Equal(t, []any{}, mapping["no-matches"])
require.Equal(t, []any{"default", "default"}, mapping["defaults"])
}
func TestOverrideExprMappingValuesUseYQStreamSemantics(t *testing.T) {
mapping := map[string]any{"items": []any{1, 2}}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.result = {"omitted": select(false), "last": (.items[])}`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, map[string]any{"last": 2}, mapping["result"])
}
func TestOverrideExprRequiresMultiResultsToBeCollected(t *testing.T) {
mapping := map[string]any{"items": []any{1, 2}}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, `.result = (.items[])`)}
err := override.Apply(mapping)
require.ErrorContains(t, err, "expression produced 2 results")
require.ErrorContains(t, err, "collect them with [...]")
}
func TestOverrideExprTopLevelFilterPipeline(t *testing.T) {
mapping := map[string]any{"name": "node", "udp": false}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`. | with_entries(.key |= upcase)`,
`{"name": .NAME, "udp": .UDP, "type": "ss"}`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, map[string]any{"name": "node", "udp": false, "type": "ss"}, mapping)
}
func TestOverrideExprErrors(t *testing.T) {
t.Run("syntax", func(t *testing.T) {
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
var schema overrideSchema
err := decoder.Decode(map[string]any{"override-expr": []any{`.udp =`}}, &schema)
require.ErrorContains(t, err, "override-expr[0]")
require.ErrorContains(t, err, "expected value")
})
t.Run("runtime", func(t *testing.T) {
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, `.port += [1]`)}
mapping := map[string]any{"port": 443}
err := override.Apply(mapping)
require.ErrorContains(t, err, `override-expr[0] ".port += [1]"`)
require.ErrorContains(t, err, "operator + cannot be used")
})
t.Run("string repeat limit", func(t *testing.T) {
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, `.value = "x" * 10000001`)}
err := override.Apply(map[string]any{"value": "x"})
require.ErrorContains(t, err, "cannot exceed 10 million")
})
}
+3 -1
View File
@@ -28,7 +28,9 @@ func (c *CachedConn) Read(b []byte) (n int, err error) {
func (c *CachedConn) ReadCached() *buf.Buffer { // call in sing/common/bufio.Copy
if len(c.data) > 0 {
return buf.As(c.data)
data := c.data
c.data = nil
return buf.As(data)
}
return nil
}
+22
View File
@@ -37,3 +37,25 @@ func SetupContextForConn(ctx context.Context, conn net.Conn) (done func(*error))
}
}
}
// RelayContext copies between left and right bidirectionally.
// If ctx is canceled, both connections are closed to interrupt pending I/O.
func RelayContext(ctx context.Context, leftConn, rightConn net.Conn) error {
if ctx.Done() == nil {
Relay(leftConn, rightConn)
return nil
}
done := make(chan struct{})
stop := contextutils.AfterFunc(ctx, func() {
_ = leftConn.Close()
_ = rightConn.Close()
close(done)
})
Relay(leftConn, rightConn)
if !stop() {
<-done
return ctx.Err()
}
return nil
}
+29
View File
@@ -101,3 +101,32 @@ func TestSetupContextForConnWithTimeout2(t *testing.T) {
t.Fatal("conn not be canceled")
}
}
func TestRelayContextWithCancel(t *testing.T) {
t.Parallel()
leftConn, leftPeer := N.Pipe()
rightConn, rightPeer := N.Pipe()
defer leftPeer.Close()
defer rightPeer.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
errc := make(chan error)
go func() {
errc <- N.RelayContext(ctx, leftConn, rightConn)
}()
select {
case <-errc:
t.Fatal("relay stopped before cancel")
case <-time.After(100 * time.Millisecond):
cancel()
}
select {
case err := <-errc:
assert.ErrorIs(t, err, context.Canceled)
case <-time.After(100 * time.Millisecond):
t.Fatal("relay was not canceled")
}
}
+28
View File
@@ -0,0 +1,28 @@
package net
import "net"
type netConn interface {
NetConn() net.Conn
}
// FindUpstream finds a value in an upstream wrapper chain. If accept rejects a
// matching value, the search continues so an outer wrapper cannot hide a valid
// inner value of the same type.
func FindUpstream[T any](value any, accept func(T) bool) (T, bool) {
for value != nil {
if candidate, ok := value.(T); ok && (accept == nil || accept(candidate)) {
return candidate, true
}
switch wrapper := value.(type) {
case WithUpstream:
value = wrapper.Upstream()
case netConn:
value = wrapper.NetConn()
default:
value = nil
}
}
var zero T
return zero, false
}
+17 -6
View File
@@ -77,11 +77,12 @@ func GetCertPool() *x509.CertPool {
}
type Option struct {
TLSConfig *tls.Config
Fingerprint string
ZeroTrust bool
Certificate string
PrivateKey string
TLSConfig *tls.Config
Fingerprint string
NameCertVerify string
ZeroTrust bool
Certificate string
PrivateKey string
}
func GetTLSConfig(opt Option) (tlsConfig *tls.Config, err error) {
@@ -106,7 +107,17 @@ func GetTLSConfig(opt Option) (tlsConfig *tls.Config, err error) {
// [ConnectionState.ServerName] can return the actual ServerName needed for verification,
// avoiding inconsistencies caused by [tlsConfig.ServerName] being modified after the [NewFingerprintVerifier] call.
// https://github.com/golang/go/issues/36736#issuecomment-587925536
return verifier(state.PeerCertificates, state.ServerName)
serverName := state.ServerName
if opt.NameCertVerify != "" {
serverName = opt.NameCertVerify
}
return verifier(state.PeerCertificates, serverName)
}
tlsConfig.InsecureSkipVerify = true
} else if opt.NameCertVerify != "" {
verifier := NewNameCertVerifier(opt.NameCertVerify, tlsConfig.RootCAs, tlsConfig.Time)
tlsConfig.VerifyConnection = func(state tls.ConnectionState) error {
return verifier(state.PeerCertificates)
}
tlsConfig.InsecureSkipVerify = true
}
+31
View File
@@ -0,0 +1,31 @@
package ca
import (
"crypto/x509"
"errors"
"time"
)
// NewNameCertVerifier returns a verifier for a certificate chain and an explicit DNSName.
func NewNameCertVerifier(dnsName string, roots *x509.CertPool, now func() time.Time) func([]*x509.Certificate) error {
return func(certificates []*x509.Certificate) error {
if len(certificates) == 0 {
return errors.New("tls: no peer certificates")
}
intermediates := x509.NewCertPool()
for _, certificate := range certificates[1:] {
intermediates.AddCert(certificate)
}
verifyOptions := x509.VerifyOptions{
Roots: roots,
Intermediates: intermediates,
DNSName: dnsName,
}
if now != nil {
verifyOptions.CurrentTime = now()
}
_, err := certificates[0].Verify(verifyOptions)
return err
}
}
+98
View File
@@ -0,0 +1,98 @@
package ca
import (
"crypto/x509"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestNameCertVerifier(t *testing.T) {
roots := x509.NewCertPool()
roots.AddCert(rootCert)
untrustedRoots := x509.NewCertPool()
untrustedRoots.AddCert(smimeRootCert)
tests := []struct {
name string
dnsName string
roots *x509.CertPool
now func() time.Time
certificates []*x509.Certificate
wantErr bool
}{
{
name: "valid chain",
dnsName: leafServerName,
roots: roots,
now: certTime,
certificates: []*x509.Certificate{leafCert, intermediateCert},
},
{
name: "valid chain with root",
dnsName: leafServerName,
roots: roots,
now: certTime,
certificates: []*x509.Certificate{leafCert, intermediateCert, rootCert},
},
{
name: "wrong DNS name",
dnsName: wrongLeafServerName,
roots: roots,
now: certTime,
certificates: []*x509.Certificate{leafCert, intermediateCert},
wantErr: true,
},
{
name: "no certificates",
dnsName: leafServerName,
roots: roots,
now: certTime,
wantErr: true,
},
{
name: "missing intermediate",
dnsName: leafServerName,
roots: roots,
now: certTime,
certificates: []*x509.Certificate{leafCert},
wantErr: true,
},
{
name: "untrusted root",
dnsName: leafServerName,
roots: untrustedRoots,
now: certTime,
certificates: []*x509.Certificate{leafCert, intermediateCert},
wantErr: true,
},
{
name: "expired certificate",
dnsName: leafServerName,
roots: roots,
now: func() time.Time { return leafCert.NotAfter.Add(time.Second) },
certificates: []*x509.Certificate{leafCert, intermediateCert},
wantErr: true,
},
{
name: "invalid certificate signature",
dnsName: leafServerName,
roots: roots,
now: certTime,
certificates: []*x509.Certificate{leafWithInvalidHashCert, intermediateCert},
wantErr: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := NewNameCertVerifier(test.dnsName, test.roots, test.now)(test.certificates)
if test.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}
+2 -2
View File
@@ -997,11 +997,11 @@ func parseListeners(cfg *RawConfig) (listeners map[string]C.InboundListener, err
for index, mapping := range cfg.Listeners {
inboundListener, err := listener.ParseListener(mapping)
if err != nil {
return nil, fmt.Errorf("proxy %d: %w", index, err)
return nil, fmt.Errorf("listener %d: %w", index, err)
}
name := inboundListener.Name()
if _, exist := mapping[name]; exist {
if _, exist := listeners[name]; exist {
return nil, fmt.Errorf("listener %s is the duplicate name", name)
}
+3
View File
@@ -49,6 +49,7 @@ const (
Sudoku
Masque
TrustTunnel
ShadowQuic
OpenVPN
Tailscale
GostRelay
@@ -227,6 +228,8 @@ func (at AdapterType) String() string {
return "Masque"
case TrustTunnel:
return "TrustTunnel"
case ShadowQuic:
return "ShadowQuic"
case OpenVPN:
return "OpenVPN"
case Tailscale:
+5
View File
@@ -42,6 +42,7 @@ const (
MIERU
SUDOKU
TRUSTTUNNEL
SHADOWQUIC
INNER
)
@@ -121,6 +122,8 @@ func (t Type) String() string {
return "Sudoku"
case TRUSTTUNNEL:
return "TrustTunnel"
case SHADOWQUIC:
return "ShadowQuic"
case INNER:
return "Inner"
default:
@@ -169,6 +172,8 @@ func ParseType(t string) (*Type, error) {
res = SUDOKU
case "TRUSTTUNNEL":
res = TRUSTTUNNEL
case "SHADOWQUIC":
res = SHADOWQUIC
case "INNER":
res = INNER
default:
+3
View File
@@ -69,6 +69,7 @@ type dnsOverHTTPS struct {
dialer *dnsDialer
addr string
skipCertVerify bool
nameCertVerify string
}
// type check
@@ -100,6 +101,7 @@ func newDoHClient(urlString string, r resolver.Resolver, preferH3 bool, params m
if params["skip-cert-verify"] == "true" {
doh.skipCertVerify = true
}
doh.nameCertVerify = params["name-cert-verify"]
runtime.SetFinalizer(doh, (*dnsOverHTTPS).Close)
@@ -406,6 +408,7 @@ func (doh *dnsOverHTTPS) createTransport(ctx context.Context) (t http.RoundTripp
MinVersion: tls.VersionTLS12,
SessionTicketsDisabled: false,
},
NameCertVerify: doh.nameCertVerify,
})
if err != nil {
return nil, err
+3
View File
@@ -62,6 +62,7 @@ type dnsOverQUIC struct {
addr string
dialer *dnsDialer
skipCertVerify bool
nameCertVerify string
}
// type check
@@ -81,6 +82,7 @@ func newDoQ(addr string, resolver resolver.Resolver, params map[string]string, p
if params["skip-cert-verify"] == "true" {
doq.skipCertVerify = true
}
doq.nameCertVerify = params["name-cert-verify"]
runtime.SetFinalizer(doq, (*dnsOverQUIC).Close)
return doq
@@ -349,6 +351,7 @@ func (doq *dnsOverQUIC) openConnection(ctx context.Context) (quicConn *quic.Conn
},
SessionTicketsDisabled: false,
},
NameCertVerify: doq.nameCertVerify,
})
if err != nil {
return nil, err
+3
View File
@@ -24,6 +24,7 @@ type dnsOverTLS struct {
host string
dialer *dnsDialer
skipCertVerify bool
nameCertVerify string
disableReuse bool
access sync.Mutex
@@ -128,6 +129,7 @@ func (t *dnsOverTLS) dialContext(ctx context.Context) (net.Conn, error) {
ServerName: t.host,
InsecureSkipVerify: t.skipCertVerify,
},
NameCertVerify: t.nameCertVerify,
})
if err != nil {
_ = conn.Close()
@@ -171,6 +173,7 @@ func newDoTClient(addr string, resolver resolver.Resolver, params map[string]str
if params["skip-cert-verify"] == "true" {
c.skipCertVerify = true
}
c.nameCertVerify = params["name-cert-verify"]
if params["disable-reuse"] == "true" {
c.disableReuse = true
}
+1 -1
View File
@@ -82,7 +82,7 @@ func withHosts(mapping *lru.LruCache[netip.Addr, string]) middleware {
case D.TypeAAAA:
handleIPs()
case D.TypeCNAME:
handleCName(r, record.Domain)
handleCName(msg, record.Domain)
default:
return next(ctx, r)
}
+369 -10
View File
@@ -379,6 +379,7 @@ proxies: # socks5
# certificate: ./client.crt # 证书 PEM 格式,或者 证书的路径
# private-key: ./client.key # 证书对应的私钥 PEM 格式,或者私钥路径
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# udp: true
# ip-version: ipv6
@@ -391,6 +392,7 @@ proxies: # socks5
# password: password
# tls: true # https
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# sni: custom.com
# fingerprint: xxxx # 配置指纹将实现 SSL Pining 效果, 可使用 openssl x509 -noout -fingerprint -sha256 -inform pem -in yourcert.pem 获取
# 下面两项如果填写则开启 mTLS(需要同时填写)
@@ -408,7 +410,7 @@ proxies: # socks5
# udp: true # support UDP on version 3/4/5
# reuse: false # v4/5 only
# obfs-opts:
# mode: http # or tls/shadow-tls
# mode: http # or tls/shadow-tls/restls/jls
- name: "snell-shadow-tls"
type: snell
@@ -426,6 +428,32 @@ proxies: # socks5
version: 2 # support 1/2/3
alpn: ["h2","http/1.1"]
- name: "snell-restls"
type: snell
server: server
port: 44046
psk: yourpsk
# version: 4 # support 1/2/3/4/5
# client-fingerprint: chrome
obfs-opts:
mode: restls
host: bing.com
password: "restls_password"
version-hint: tls13
- name: "snell-jls"
type: snell
server: server
port: 44046
psk: yourpsk
# version: 4 # support 1/2/3/4/5
# client-fingerprint: chrome
obfs-opts:
mode: jls
host: bing.com
username: jls-user
password: "jls_password"
# Shadowsocks
# cipher支持:
# aes-128-gcm aes-192-gcm aes-256-gcm
@@ -489,6 +517,7 @@ proxies: # socks5
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# host: bing.com
# path: "/"
# mux: true
@@ -526,12 +555,27 @@ proxies: # socks5
# certificate: ./client.crt # 证书 PEM 格式,或者 证书的路径
# private-key: ./client.key # 证书对应的私钥 PEM 格式,或者私钥路径
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# host: bing.com
# path: "/"
# mux: true
# headers:
# custom: value
- name: "ss-jls"
type: ss
server: server
port: 443
cipher: chacha20-ietf-poly1305
password: "password"
plugin: jls
client-fingerprint: chrome
plugin-opts:
host: "www.example.com"
username: "jls-user"
password: "jls-password"
# alpn: [h2, http/1.1]
- name: "gost-relay-hop"
type: gost-relay
# Dynamic mode: relay connects to the target address requested by the upper proxy.
@@ -549,6 +593,7 @@ proxies: # socks5
# certificate: ./client.crt
# private-key: ./client.key
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
- name: "ss6-gost-relay"
type: ss
@@ -677,8 +722,9 @@ proxies: # socks5
# private-key: ./client.key # 证书对应的私钥 PEM 格式,或者私钥路径
# client-fingerprint: chrome # Available: "chrome","firefox","safari","ios","random", currently only support TLS transport in TCP/GRPC/WS/HTTP for VLESS/Vmess and trojan.
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# servername: example.com # priority over wss host
# 如果填写 tlsmirror-opts 则开启 tlsmirror(当 tls: true 时),servername 和 alpn 使用上层配置
# 如果填写 tlsmirror-opts 则开启 tlsmirror(当 tls: true 时)。tlsmirror 的 TLS 载体会使用同一出站中的 `servername`、`alpn`、`skip-cert-verify`、`name-cert-verify`、`fingerprint`、`certificate`、`private-key`、`client-fingerprint` 和 `ech-opts` 配置;`servername` 为空时使用 `server`。
# tlsmirror-opts:
# primary-key: MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY= # 必填,32 字节主密钥的 base64 编码
# explicit-nonce-ciphersuites: [156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 49195, 49196, 49197, 49198, 49199, 49200, 49201, 49202, 49290, 49291, 49293, 49316, 49317, 49318, 49319, 49320, 49321, 49322, 49323, 49324, 49325, 49326, 49327, 52392, 52393, 52394, 52395, 52396, 52397, 52398] # TLS 1.2 载体使用显式 nonce 的加密套件
@@ -709,6 +755,17 @@ proxies: # socks5
# # 如果config为空则通过dns解析,不为空则通过该值指定,格式为经过base64编码的ech参数(dig +short TYPE65 tls-ech.dev)
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
# shadow-tls-opts: # 需要 tls: true;使用 servername 作为 ShadowTLS SNI
# version: 3 # 支持 v1/v2/v3;留空时默认为 v2
# password: shadow-tls-password
# restls-opts: # 需要 tls: true;使用 servername 作为 Restls SNI
# password: restls-password
# version-hint: tls13 # 可选值:tls12、tls13
# # restls-script: ""
# jls-opts: # 需要 tls: true;使用 servername 作为 JLS SNI
# username: jls-user
# password: jls-password
# reality-opts: ...
# ws-opts:
# path: /path
# headers:
@@ -816,6 +873,7 @@ proxies: # socks5
# private-key: ./client.key # 证书对应的私钥 PEM 格式,或者私钥路径
servername: example.com
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
grpc-opts:
grpc-service-name: "example"
# grpc-user-agent: "grpc-go/1.36.0"
@@ -834,6 +892,7 @@ proxies: # socks5
network: tcp
servername: example.com # AKA SNI
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# 下面两项如果填写则开启 mTLS(需要同时填写)
# certificate: ./client.crt # 证书 PEM 格式,或者 证书的路径
# private-key: ./client.key # 证书对应的私钥 PEM 格式,或者私钥路径
@@ -844,6 +903,17 @@ proxies: # socks5
# # 如果config为空则通过dns解析,不为空则通过该值指定,格式为经过base64编码的ech参数(dig +short TYPE65 tls-ech.dev)
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
# shadow-tls-opts: # 需要 tls: true;使用 servername 作为 ShadowTLS SNI
# version: 3 # 支持 v1/v2/v3;留空时默认为 v2
# password: shadow-tls-password
# restls-opts: # 需要 tls: true;使用 servername 作为 Restls SNI
# password: restls-password
# version-hint: tls13 # 可选值:tls12、tls13
# # restls-script: ""
# jls-opts: # 需要 tls: true;使用 servername 作为 JLS SNI
# username: jls-user
# password: jls-password
# reality-opts: ...
- name: "vless-vision"
type: vless
@@ -860,6 +930,7 @@ proxies: # socks5
# private-key: ./client.key # 证书对应的私钥 PEM 格式,或者私钥路径
# fingerprint: xxxx # 配置指纹将实现 SSL Pining 效果, 可使用 openssl x509 -noout -fingerprint -sha256 -inform pem -in yourcert.pem 获取
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
- name: "vless-encryption"
type: vless
@@ -908,6 +979,7 @@ proxies: # socks5
udp: true
flow:
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
client-fingerprint: chrome
servername: testingcf.jsdelivr.net
grpc-opts:
@@ -934,6 +1006,7 @@ proxies: # socks5
# client-fingerprint: random # Available: "chrome","firefox","safari","random","none"
servername: example.com # priority over wss host
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# fingerprint: xxxx # 配置指纹将实现 SSL Pining 效果, 可使用 openssl x509 -noout -fingerprint -sha256 -inform pem -in yourcert.pem 获取
# 下面两项如果填写则开启 mTLS(需要同时填写)
# certificate: ./client.crt # 证书 PEM 格式,或者 证书的路径
@@ -957,6 +1030,7 @@ proxies: # socks5
# ech-opts: ...
# reality-opts: ...
# skip-cert-verify: false
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# fingerprint: ...
# certificate: ...
# private-key: ...
@@ -1012,8 +1086,12 @@ proxies: # socks5
# tls: true
# alpn: ...
# ech-opts: ...
# shadow-tls-opts: ...
# restls-opts: ...
# jls-opts: ...
# reality-opts: ...
# skip-cert-verify: false
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# fingerprint: ...
# certificate: ...
# private-key: ...
@@ -1038,6 +1116,7 @@ proxies: # socks5
# - h2
# - http/1.1
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# ss-opts: # like trojan-go's `shadowsocks` config
# enabled: false
# method: aes-128-gcm # aes-128-gcm/aes-256-gcm/chacha20-ietf-poly1305
@@ -1047,6 +1126,17 @@ proxies: # socks5
# # 如果config为空则通过dns解析,不为空则通过该值指定,格式为经过base64编码的ech参数(dig +short TYPE65 tls-ech.dev)
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
# shadow-tls-opts: # 使用 sni 作为 ShadowTLS SNI
# version: 3 # 支持 v1/v2/v3;留空时默认为 v2
# password: shadow-tls-password
# restls-opts: # 使用 sni 作为 Restls SNI
# password: restls-password
# version-hint: tls13 # 可选值:tls12、tls13
# # restls-script: ""
# jls-opts: # 使用 sni 作为 JLS SNI
# username: jls-user
# password: jls-password
# reality-opts: ...
- name: trojan-grpc
server: server
@@ -1056,6 +1146,7 @@ proxies: # socks5
network: grpc
sni: example.com
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# fingerprint: xxxx # 配置指纹将实现 SSL Pining 效果, 可使用 openssl x509 -noout -fingerprint -sha256 -inform pem -in yourcert.pem 获取
# 下面两项如果填写则开启 mTLS(需要同时填写)
# certificate: ./client.crt # 证书 PEM 格式,或者 证书的路径
@@ -1077,6 +1168,7 @@ proxies: # socks5
network: ws
sni: example.com
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# fingerprint: xxxx # 配置指纹将实现 SSL Pining 效果, 可使用 openssl x509 -noout -fingerprint -sha256 -inform pem -in yourcert.pem 获取
# 下面两项如果填写则开启 mTLS(需要同时填写)
# certificate: ./client.crt # 证书 PEM 格式,或者 证书的路径
@@ -1099,6 +1191,7 @@ proxies: # socks5
# udp: true
# sni: example.com # aka server name
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# fingerprint: xxxx # 配置指纹将实现 SSL Pining 效果, 可使用 openssl x509 -noout -fingerprint -sha256 -inform pem -in yourcert.pem 获取
# 下面两项如果填写则开启 mTLS(需要同时填写)
# certificate: ./client.crt # 证书 PEM 格式,或者 证书的路径
@@ -1124,6 +1217,7 @@ proxies: # socks5
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
# skip-cert-verify: false
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# recv-window-conn: 12582912
# recv-window: 52428800
# disable-mtu-discovery: false
@@ -1156,6 +1250,7 @@ proxies: # socks5
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
# skip-cert-verify: false
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# fingerprint: xxxx # 配置指纹将实现 SSL Pining 效果, 可使用 openssl x509 -noout -fingerprint -sha256 -inform pem -in yourcert.pem 获取
# 下面两项如果填写则开启 mTLS(需要同时填写)
# certificate: ./client.crt # 证书 PEM 格式,或者 证书的路径
@@ -1171,8 +1266,9 @@ proxies: # socks5
# - stun.nextcloud.com:3478
# - stun.sip.us:3478
# - global.stun.twilio.com:3478
# # 下面支持填写针对server-url的TLS配置(sni, skip-cert-verify, fingerprint, certificate, private-key, alpn)
# # 下面支持填写针对server-url的TLS配置(sni, skip-cert-verify, name-cert-verify, fingerprint, certificate, private-key, alpn)
# # skip-cert-verify: false
# # name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# # ......
###quic-go特殊配置项,不要随意修改除非你知道你在干什么###
# initial-stream-receive-window: 8388608
@@ -1263,6 +1359,8 @@ proxies: # socks5
proto: udp # udp/tcp,默认 udp
# dev: tun # 目前仅支持 tun,默认 tun
# cipher: AES-128-GCM # 支持 AES-128-GCM / AES-192-GCM / AES-256-GCM / AES-128-CBC / AES-192-CBC / AES-256-CBC / CHACHA20-POLY1305,默认 AES-128-GCM;AES-CBC 会按 AES-128-CBC 处理
# data-ciphers: [AES-256-GCM, AES-128-GCM] # 数据通道 cipher 协商列表,发送 IV_CIPHERS 给服务端;服务端 push 的 cipher 列表与本地列表取交集,取第一个匹配项
# data-ciphers-fallback: AES-128-CBC # 协商失败时的回退 cipher(对应 --data-ciphers-fallback)
# auth: SHA256 # 支持 MD5 / SHA1 / SHA256 / SHA384 / SHA512,默认 SHA256;AEAD cipher 会忽略 auth
# comp-lzo: "no" # 可选值:"yes", "no", "adaptive"
# username / password: auth-user-pass 模式(与下方 cert+key 二选一,不能都不填)
@@ -1283,12 +1381,24 @@ proxies: # socks5
-----BEGIN PRIVATE KEY-----
MIIE...example
-----END PRIVATE KEY-----
# 从 .ovpn 中复制 <tls-crypt></tls-crypt> 内的内容,不需要保留 <tls-crypt> 标签;没有 tls-crypt 的配置可省略
# 从 .ovpn 中复制 <tls-auth></tls-auth> 内的内容,不需要保留 <tls-auth> 标签;与 tls-crypt 互斥
# tls-auth: |
# -----BEGIN OpenVPN Static key V1-----
# 00000000000000000000000000000000
# ...
# -----END OpenVPN Static key V1-----
# key-direction: "1" # tls-auth 使用,支持 "1" 或 "0";如果不填或为空字符串,则为双向模式(bidirectional)
# 从 .ovpn 中复制 <tls-crypt></tls-crypt> 内的内容,不需要保留 <tls-crypt> 标签;没有 tls-crypt 的配置可省略;与 tls-auth / tls-crypt-v2 互斥
# tls-crypt: |
# -----BEGIN OpenVPN Static key V1-----
# 00000000000000000000000000000000
# ...
# -----END OpenVPN Static key V1-----
# 从 .ovpn 中复制 <tls-crypt-v2></tls-crypt-v2> 内的内容;tls-crypt-v2 使用独立客户端密钥(PEM 内含 256 字节密钥 + wrapped key);与 tls-auth / tls-crypt 互斥
# tls-crypt-v2: |
# -----BEGIN OpenVPN tls-crypt-v2 client key-----
# AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8...
# -----END OpenVPN tls-crypt-v2 client key-----
# peer-info: # 透传给服务端的 peer-info 键值对,追加在内置 IV_VER/IV_PROTO/IV_CIPHERS 之后;用于服务端基于 peer-info 做准入决策
# IV_HWADDR: "52:54:00:ff:72:87"
# UV_DEVICE_ID: "laptop-001"
@@ -1377,6 +1487,7 @@ proxies: # socks5
# max-udp-relay-packet-size: 1500
# fast-open: true
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# max-open-streams: 20 # default 100, too many open streams may hurt performance
# sni: example.com
# ech-opts:
@@ -1390,6 +1501,30 @@ proxies: # socks5
# udp-over-stream: false
# udp-over-stream-version: 1
# shadowquic
- name: shadowquic
server: www.example.com
port: 10443
type: shadowquic
username: username
password: password
# sni: example.com
# alpn: [h3]
# quic-versions: [v1] # support v1/v2, default v1
# udp-over-stream: false # UDP over stream, default false
# zero-rtt: false # 官方 server 的 0-RTT 路径可能在 JLS 认证完成前读取用户状态(已确认影响 v0.3.11);使用官方 server 如果遇到不通或断联情况,请在服务端关闭 zero-rtt
# keep-alive-interval: 10000
# congestion-controller: bbr # Available: "cubic", "new_reno", "bbr". Default: "cubic"
# up: 100 Mbps # enables brutal negotiation via a mihomo private extension; client upload speed; falls back to congestion-controller when unsupported
# down: 100 Mbps # enables brutal negotiation via a mihomo private extension; requested client download speed, capped by listener up; falls back to congestion-controller when unsupported
# cwnd: 10 # default: 32
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
# max-datagram-frame-size: 1400
# max-open-streams: 1024
# recv-window-conn: 0
# recv-window: 0
# disable-mtu-discovery: false
# ShadowsocksR
# The supported ciphers (encryption methods): all stream ciphers in ss
# The supported obfses:
@@ -1448,6 +1583,7 @@ proxies: # socks5
table-type: prefer_ascii # 可选值:prefer_ascii、prefer_entropy、up_ascii_down_entropy、up_entropy_down_ascii
# custom-table: xpxvvpvv # 可选,自定义字节布局,必须包含2个x、2个p、4个v,可随意组合;只对 entropy 方向生效
# custom-tables: ["xpxvvpvv", "vxpvxvvp"] # 可选,自定义字节布局列表(x/v/p),非空时覆盖 custom-table
# multiplex: "off" # 可选:off(默认)、auto(仅复用 HTTPMask 底层连接)、on(在原始 TCP 或 HTTPMask 上启用 Sudoku 单会话多目标 mux)
# 推荐:使用 httpmask 对象统一管理 HTTPMask 相关字段:
httpmask:
disable: false # true 禁用所有 HTTP 伪装/隧道
@@ -1455,7 +1591,7 @@ proxies: # socks5
# tls: true # 可选:按需开启 HTTPS/WSS
# host: "" # 可选:覆盖 Host/SNI(支持 example.com 或 example.com:443);仅在 mode 为 stream/poll/auto/ws 时生效
# path-root: "" # 可选:HTTP 隧道端点一级路径前缀(双方需一致),例如 "aabbcc" 或 "/aabbcc/" => /aabbcc/session、/aabbcc/stream、/aabbcc/api/v1/upload、/aabbcc/ws
# multiplex: "off" # 可选字符串:off(默认)、auto(复用底层 HTTP 连接,减少建链 RTT)、on(Sudoku mux 单隧道多目标;仅在 mode=stream/poll/auto 生效;ws 强制 off)
# multiplex: "off" # 兼容旧配置;设置时优先于顶层 multiplex
enable-pure-downlink: false # 可选:false=带宽优化下行;true=纯 Sudoku 下行
# anytls
@@ -1474,6 +1610,17 @@ proxies: # socks5
# - h2
# - http/1.1
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# shadow-tls-opts: # 使用 sni 作为 ShadowTLS SNI
# version: 3 # 支持 v1/v2/v3;留空时默认为 v2
# password: shadow-tls-password
# restls-opts: # 使用 sni 作为 Restls SNI
# password: restls-password
# version-hint: tls13 # 可选值:tls12、tls13
# # restls-script: ""
# jls-opts: # 使用 sni 作为 JLS SNI
# username: jls-user
# password: jls-password
# trusttunnel
- name: trusttunnel
@@ -1489,6 +1636,7 @@ proxies: # socks5
# alpn:
# - h2
# skip-cert-verify: true
# name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
### quic options
# quic: true # 默认为false
# congestion-controller: bbr
@@ -1611,6 +1759,7 @@ proxy-providers:
# expected-status: 204 # 当健康检查返回状态码与期望值不符时,认为节点不可用
override: # 覆写节点加载时的一些配置项
skip-cert-verify: true
name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
udp: true
# down: "50 Mbps"
# up: "10 Mbps"
@@ -1626,6 +1775,54 @@ proxy-providers:
# target: "TEST"
# - pattern: "IPLC-(.*?)倍"
# target: "iplc x $1"
# # 这是 yq v4 风格的配置覆盖子集。数组项按顺序执行,且晚于上面的固定字段覆盖。
# # 路径:.、.name、."a.b"、.["a.b"]、.items[0]、.items[-1]。[] 可以遍历数组或 mapping。
# # 读取缺失路径或穿过标量时返回 null。赋值会创建缺失的 mapping 和非负数组索引,但不会穿过标量更新。
# # 赋值:=、|=、+=、-=、*=。删除:del(.field)、del(.a, .b)。
# # 值:null(或 ~)、布尔值、十进制/十六进制整数、浮点数、双引号字符串、数组及双引号键的 mapping。
# # 负号只用于十进制整数和浮点数。浮点数支持科学计数法。
# # 字符串按 yq 规则解码 \n、\"、\\;其他反斜杠序列保留原文。
# # 数组会收集每一项的全部结果。mapping 的 value 为零结果时省略 key,多结果时保留最后一个。
# # 运算:+、-、*、/、%、==、!=、<、<=、>、>=、and、or、//(默认值)。
# # + 可拼接字符串/数组或浅合并 mapping;* 可做数乘、字符串重复、数组替换或深合并 mapping;/ 可分割字符串。
# # 流:管道 |、逗号 union、select。使用 [...] 将零到多个结果收集为数组。
# # 字符串支持 "[\(.type)] \(.name)" 形式的插值。插值表达式有多个结果时使用第一个。
# # 字符串外的 # 会忽略该数组项中的后续表达式内容。
# # 查询函数:length、keys、has(key/index)、contains(value)、select(condition)。字符串 length 按 UTF-8 字节数计算。
# # 数组函数:reverse、sort、unique、flatten([depth])、any、all。
# # 转换函数:map、map_values、filter、to_entries、from_entries、with_entries、any_c、all_c。
# # map/filter/map_values 支持数组或 mapping。with_entries 只支持 mapping,any_c/all_c 只支持数组。
# # map/filter 返回数组,map_values 保持输入集合类型。to_entries(null) 不产生结果。
# # from_entries 只接受具有字符串 key 的 entries 数组。
# # 字符串函数:test(pattern[, "g"])、sub(pattern, replacement)、split(separator)、join(separator)、upcase、downcase、trim。
# # split(null) 不产生结果,join 只接受数组。
# # 类型函数:tostring、tonumber、type、not。tonumber 支持十进制、0x 十六进制、0o 八进制和浮点字符串。
# override-expr:
# - '.name = "[provider1] " + .name' # 普通赋值
# - '.plugin-opts.mode = "tls"' # 自动创建缺失的 mapping
# - '.alpn[] |= upcase' # 更新数组中的每一项
# - 'del(.skip-cert-verify)' # 删除字段
# - '.name = (.name | trim | upcase)' # 赋值右侧的管道需加括号
# - '.name = "[\(.type)] \(.name):\(.port)"' # 字符串插值
# - '(select(.port == 443) | .tls) = true' # 条件不匹配时不修改
# - '.tags |= (unique | sort)' # 去重后排序
# - '.names = [.servers[] | select(.enabled) | .name]' # 收集多个结果
# - '.servers |= map(select(.enabled))' # 筛选数组
# - '.options |= with_entries(.key |= upcase)' # 转换 mapping
# - '. | with_entries(.key |= upcase)' # 整体过滤结果仍须为 mapping
# # 每一项最终必须恰好产生一个 mapping。未收集的多结果及 del(.) 不受支持。
# # 赋值右侧使用管道或 and/or 时必须加括号。from_entries 只接受字符串 key。
# # sort 只支持标量数组。any/all 只支持无参数形式。
# # ==/!= 按 yq 的标量文本值比较,不对数组或 mapping 做结构化比较。
# # <、<=、>、>= 只支持数字、字符串和 null。只有 false 和 null 按假值处理。
# # 普通函数参数不得产生多个结果;map/filter 等接收表达式的函数允许参数产生结果流。
# # 函数参数可使用逗号或分号分隔。
# # 求值采用值语义。越界读取不会扩展源数组,右侧的 flatten/map_values 也不会隐式修改源路径。
# # 需要修改源路径时请使用 |=。右侧没有结果时保留目标原值,不会自动创建 null。
# # mapping 流、keys 和 entries 转换按 key 排序,因为 map[string]any 不保留 YAML key 顺序。
# # 不支持的语言功能:变量(as/$x)、reduce、动态路径(.[$key])、递归下降(..)。
# # 不支持的外部功能:多文档、文件/环境访问、YAML tag/样式/注释处理、yq CLI 参数。
# # 未在上面列出的 yq 语法、运算符和函数也不受支持。条件分支可改用 select 后串联多个赋值。
provider2:
type: inline
@@ -1842,6 +2039,16 @@ listeners:
# restls-script: ""
# min-record-len: 0
# proxy: ""
# jls-config: # 仅封装 TCP;JLS 认证失败或普通 TLS 连接会透明回落到 dest
# enable: false
# users:
# - username: jls-user
# password: jls-password
# dest: www.example.com:443
# # sni: www.example.com # 留空时从 dest 推导
# # alpn: [h2, http/1.1]
# # proxy: ""
# # rate-limit: 0 # 转发限速,单位 bit/s,0 表示不限速
# kcp-tun:
# enable: false
# key: it's a secrect # pre-shared secret between client and server
@@ -1889,6 +2096,17 @@ listeners:
# password: password
# handshake:
# dest: test.com:443
# res-tls:
# enable: false
# dest: test.com:443
# password: restls-password
# jls-config:
# enable: false
# users:
# - username: jls-user
# password: jls-password
# dest: test.com:443
## shadow-tls, res-tls and jls-config are mutually exclusive
# rule: sub-rule-name1
# proxy: proxy
@@ -1947,6 +2165,33 @@ listeners:
# madSJjYQIf9o1N5GXjkW4DEEeb17qMxHdwMdNnwADAABAAEAAQACAAEAAwAIdGVz
# dC5jb20AAA==
# -----END ECH KEYS-----
# jls-config: # JLS 替代普通 TLS;未认证连接回落到 dest
# enable: true
# users:
# - username: jls-user
# password: jls-password
# dest: www.example.com:443
# # sni: www.example.com # 留空时从 dest 推导
# # alpn: [h2, http/1.1]
# # proxy: ""
# # rate-limit: 0 # fallback 转发限速,单位 bit/s;0 表示不限速
# shadow-tls:
# enable: true
# version: 3 # 支持 v1/v2/v3
# # password: shadow-tls-password # v2 配置项
# users: # v3 配置项
# - name: shadow-tls-user
# password: shadow-tls-password
# handshake:
# dest: www.example.com:443
# # proxy: ""
# res-tls:
# enable: true
# dest: www.example.com:443
# password: restls-password
# # restls-script: ""
# # min-record-len: 0
# # proxy: ""
# 如果填写reality-config则开启reality(注意不可与certificate和private-key同时填写)
# reality-config:
# dest: test.com:443
@@ -2012,6 +2257,38 @@ listeners:
# - h3
# max-udp-relay-packet-size: 1500
- name: shadowquic-in-1
type: shadowquic
port: 10822 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
users:
- username: username
password: password
jls-upstream:
addr: www.example.com:443 # 未通过 JLS 认证的连接将转发到该 QUIC 伪装上游
# sni: example.com # JLS 伪装目标 SNI,留空时从 addr 推导
# proxy: proxy # 伪装上游使用的代理
# rate-limit: 0 # 转发限速,单位 bit/s,0 表示不限速
# quic-version-probe: false # 在首次连接时探测伪装上游版本
# alpn:
# - h3
# quic-versions: [v1] # 本机手动配置及探测失败时的版本;支持 v1/v2
# zero-rtt: true
# congestion-controller: bbr # Available: "cubic", "new_reno", "bbr". Default: "cubic"
# up: 100 Mbps # enables brutal negotiation via a mihomo private extension; server upload/client download speed cap; falls back to congestion-controller when unsupported
# down: 100 Mbps # enables brutal negotiation via a mihomo private extension; requested server download/client upload speed; falls back to congestion-controller when unsupported
# ignore-client-bandwidth: false # for brutal; ignore outbound down and use listener down/auto instead
# cwnd: 10 # default: 32
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
# max-idle-time: 30000
# max-datagram-frame-size: 1400
# recv-window-conn: 0
# recv-window: 0
# disable-mtu-discovery: false
- name: tunnel-in-1
type: tunnel
port: 10816 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
@@ -2085,6 +2362,16 @@ listeners:
# madSJjYQIf9o1N5GXjkW4DEEeb17qMxHdwMdNnwADAABAAEAAQACAAEAAwAIdGVz
# dC5jb20AAA==
# -----END ECH KEYS-----
# jls-config: # JLS 替代普通 TLS;未认证连接回落到 dest
# enable: true
# users:
# - username: jls-user
# password: jls-password
# dest: www.example.com:443
# # sni: www.example.com # 留空时从 dest 推导
# # alpn: [h2, http/1.1]
# # proxy: ""
# # rate-limit: 0 # fallback 转发限速,单位 bit/s;0 表示不限速
# 如果填写reality-config则开启reality(注意不可与certificate和private-key同时填写)
reality-config:
dest: test.com:443
@@ -2103,7 +2390,24 @@ listeners:
after-bytes: 0 # 传输指定字节后开始限速
bytes-per-sec: 0 # 基准速率(字节/秒)
burst-bytes-per-sec: 0 # 突发速率(字节/秒),大于 bytesPerSec 时生效
### 注意,对于vless listener, 如果 "allow-insecure" 不为 true, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “decryption” 的其中一项 ###
# shadow-tls:
# enable: true
# version: 3 # 支持 v1/v2/v3
# # password: shadow-tls-password # v2 配置项
# users: # v3 配置项
# - name: shadow-tls-user
# password: shadow-tls-password
# handshake:
# dest: www.example.com:443
# # proxy: ""
# res-tls:
# enable: true
# dest: www.example.com:443
# password: restls-password
# # restls-script: ""
# # min-record-len: 0
# # proxy: ""
### 注意,对于vless listener, 如果 "allow-insecure" 不为 true, 至少需要填写 “certificate和private-key” 或 “shadow-tls” 或 “res-tls” 或 “jls-config” 或 “reality-config” 或 “decryption” 的其中一项 ###
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
- name: anytls-in-1
@@ -2114,7 +2418,7 @@ listeners:
users:
username1: password1
username2: password2
# "certificate" and "private-key" are required
# "shadow-tls"、"res-tls" 和 "jls-config" 均未启用且 "allow-insecure" 不为 true 时,必须填写 "certificate" 和 "private-key";启用 ShadowTLS、ResTLS 或 JLS 时不要填写
certificate: ./server.crt # 证书 PEM 格式,或者 证书的路径
private-key: ./server.key
# 下面两项为mTLS配置项,如果client-auth-type设置为 "verify-if-given" 或 "require-and-verify" 则client-auth-cert必须不为空
@@ -2127,7 +2431,34 @@ listeners:
# madSJjYQIf9o1N5GXjkW4DEEeb17qMxHdwMdNnwADAABAAEAAQACAAEAAwAIdGVz
# dC5jb20AAA==
# -----END ECH KEYS-----
### 注意,anytls listener, 如果 "allow-insecure" 不为 true, 必须填写 “certificate和private-key” ###
# shadow-tls:
# enable: true
# version: 3 # 支持 v1/v2/v3
# # password: shadow-tls-password # v2 配置项
# users: # v3 配置项
# - name: shadow-tls-user
# password: shadow-tls-password
# handshake:
# dest: www.example.com:443
# # proxy: ""
# res-tls:
# enable: true
# dest: www.example.com:443
# password: restls-password
# # restls-script: ""
# # min-record-len: 0
# # proxy: ""
# jls-config: # JLS 替代普通 TLS;未认证连接回落到 dest
# enable: true
# users:
# - username: jls-user
# password: jls-password
# dest: www.example.com:443
# # sni: www.example.com # 留空时从 dest 推导
# # alpn: [h2, http/1.1]
# # proxy: ""
# # rate-limit: 0 # fallback 转发限速,单位 bit/s;0 表示不限速
### 注意,anytls listener, 如果 "allow-insecure" 不为 true, 至少需要填写 “certificate和private-key” 或 “shadow-tls” 或 “res-tls” 或 “jls-config” 的其中一项 ###
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
# padding-scheme: "" # https://github.com/anytls/anytls-go/blob/main/docs/protocol.md#cmdupdatepaddingscheme
@@ -2194,6 +2525,33 @@ listeners:
# madSJjYQIf9o1N5GXjkW4DEEeb17qMxHdwMdNnwADAABAAEAAQACAAEAAwAIdGVz
# dC5jb20AAA==
# -----END ECH KEYS-----
# shadow-tls:
# enable: true
# version: 3 # 支持 v1/v2/v3
# # password: shadow-tls-password # v2 配置项
# users: # v3 配置项
# - name: shadow-tls-user
# password: shadow-tls-password
# handshake:
# dest: www.example.com:443
# # proxy: ""
# res-tls:
# enable: true
# dest: www.example.com:443
# password: restls-password
# # restls-script: ""
# # min-record-len: 0
# # proxy: ""
# jls-config: # JLS 替代普通 TLS;未认证连接回落到 dest
# enable: true
# users:
# - username: jls-user
# password: jls-password
# dest: www.example.com:443
# # sni: www.example.com # 留空时从 dest 推导
# # alpn: [h2, http/1.1]
# # proxy: ""
# # rate-limit: 0 # fallback 转发限速,单位 bit/s;0 表示不限速
# 如果填写reality-config则开启reality(注意不可与certificate和private-key同时填写)
# reality-config:
# dest: test.com:443
@@ -2216,7 +2574,7 @@ listeners:
# enabled: false
# method: aes-128-gcm # aes-128-gcm/aes-256-gcm/chacha20-ietf-poly1305
# password: "example"
### 注意,对于trojan listener, 如果 "allow-insecure" 不为 true, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “ss-option” 的其中一项 ###
### 注意,对于trojan listener, 如果 "allow-insecure" 不为 true, 至少需要填写 “certificate和private-key” 或 “shadow-tls” 或 “res-tls” 或 “jls-config” 或 “reality-config” 或 “ss-option” 的其中一项 ###
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
- name: hysteria2-in-1
@@ -2267,8 +2625,9 @@ listeners:
# - stun.sip.us:3478
# - global.stun.twilio.com:3478
# # proxy: DIRECT # 设置server-url通过哪个代理进行连接
# # 下面支持填写针对server-url的TLS配置(sni, skip-cert-verify, fingerprint, certificate, private-key, alpn)
# # 下面支持填写针对server-url的TLS配置(sni, skip-cert-verify, name-cert-verify, fingerprint, certificate, private-key, alpn)
# # skip-cert-verify: false
# # name-cert-verify: example.com # 仅修改证书 DNSName 校验目标,不修改 SNI
# # ......
# 注意,这是用于自建hysteria2入站和出站中realm-opts中server-url的HTTP/HTTPS服务器,请勿混淆
+3 -2
View File
@@ -23,6 +23,8 @@ require (
github.com/metacubex/fswatch v0.1.1
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759
github.com/metacubex/http v0.1.6
github.com/metacubex/jls-quic-go v0.0.0-20260717074316-85a8decdd355
github.com/metacubex/jls-tls v0.0.0-20260716145614-4bf88db633e2
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604
github.com/metacubex/mhurl v0.1.0
github.com/metacubex/mlkem v0.1.0
@@ -35,13 +37,12 @@ require (
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3
github.com/metacubex/sing-shadowsocks v0.2.12
github.com/metacubex/sing-shadowsocks2 v0.2.7
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc
github.com/metacubex/sing-tun v0.4.21
github.com/metacubex/sing-vmess v0.2.5
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141
github.com/metacubex/ssh v0.1.0
github.com/metacubex/tailscale v0.0.0-20260623094802-1ab893d4162c
github.com/metacubex/tailscale v0.0.0-20260711142031-e2257fe61058
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c
github.com/metacubex/tls v0.1.7
github.com/metacubex/utls v1.8.7
+6 -4
View File
@@ -131,6 +131,10 @@ github.com/metacubex/hpke v0.1.0 h1:gu2jUNhraehWi0P/z5HX2md3d7L1FhPQE6/Q0E9r9xQ=
github.com/metacubex/hpke v0.1.0/go.mod h1:vfDm6gfgrwlXUxKDkWbcE44hXtmc1uxLDm2BcR11b3U=
github.com/metacubex/http v0.1.6 h1:xvXuvXMCMxCWMF5nEJF4yiKvXL+p2atWMzs37e80m1I=
github.com/metacubex/http v0.1.6/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
github.com/metacubex/jls-quic-go v0.0.0-20260717074316-85a8decdd355 h1:DD4qraoIY3IbkHxaBbpJR68sWNzrdKHfFRfFhT6m1W8=
github.com/metacubex/jls-quic-go v0.0.0-20260717074316-85a8decdd355/go.mod h1:dbfkDUKqohALRmgUrVIOLirCNfKjgaos9nfTnBRTpS8=
github.com/metacubex/jls-tls v0.0.0-20260716145614-4bf88db633e2 h1:n+qiR8opOJEerewq/S92zGoHBDXZb+dKmyYq0aKJtis=
github.com/metacubex/jls-tls v0.0.0-20260716145614-4bf88db633e2/go.mod h1:mmqs889W/TqPlfNRDa2UyJvRiLyiTJIEnWHkcj3SKB8=
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df h1:S0vBzqjXok24VopstOgPd1JdgglW9tXehrqvwpQWbQ8=
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df/go.mod h1:F4sVXat6QjPXkNsKRDyyG3BhSkxPFFnRPEIwmmyCgbg=
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604 h1:hJwCVlE3ojViC35MGHB+FBr8TuIf3BUFn2EQ1VIamsI=
@@ -163,8 +167,6 @@ github.com/metacubex/sing-shadowsocks v0.2.12 h1:Wqzo8bYXrK5aWqxu/TjlTnYZzAKtKsa
github.com/metacubex/sing-shadowsocks v0.2.12/go.mod h1:2e5EIaw0rxKrm1YTRmiMnDulwbGxH9hAFlrwQLQMQkU=
github.com/metacubex/sing-shadowsocks2 v0.2.7 h1:hSuuc0YpsfiqYqt1o+fP4m34BQz4e6wVj3PPBVhor3A=
github.com/metacubex/sing-shadowsocks2 v0.2.7/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE=
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc h1:8wLoFfYQ88iGPL+krQ5tJsI8IAmkFjKpQL2q+y3pvss=
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc/go.mod h1:mbfboaXauKJNIHJYxQRa+NJs4JU9NZfkA+I33dS2+9E=
github.com/metacubex/sing-tun v0.4.21 h1:MjbPYytM240VH70lO182v2Sg/JthMmx6R6z6E2fCR2I=
github.com/metacubex/sing-tun v0.4.21/go.mod h1:g4I/JNplDBhXLF+aQWgFbhNeJPSXQOWS9HvLeNvkgeA=
github.com/metacubex/sing-vmess v0.2.5 h1:m9Zt5I27lB9fmLMZfism9sH2LcnAfShZfwSkf6/KJoE=
@@ -175,8 +177,8 @@ github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141 h1:DK2l6m2Fc85H2Bhi
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141/go.mod h1:/yI4OiGOSn0SURhZdJF3CbtPg3nwK700bG8TZLMBvAg=
github.com/metacubex/ssh v0.1.0 h1:iGfr99qk/eMHzUnQ/0bTxXT8+8SWqLSHBWDHoAhngzw=
github.com/metacubex/ssh v0.1.0/go.mod h1:NUtl0d+/f2cG9ECEpMM8iCVOpmggQlC13oLeDUONDlU=
github.com/metacubex/tailscale v0.0.0-20260623094802-1ab893d4162c h1:ACfYexFGGaObb80aq0IiG3oRjv4I1lCxf104cUsI0W8=
github.com/metacubex/tailscale v0.0.0-20260623094802-1ab893d4162c/go.mod h1:rDpd7cy7itpPi3Kgb90fUgSnKwMXHYBk0R5DuNRiNNA=
github.com/metacubex/tailscale v0.0.0-20260711142031-e2257fe61058 h1:TFM/yl2XvyMDQY16GHDxXtuJMa8DGz7roRpY6plxLMk=
github.com/metacubex/tailscale v0.0.0-20260711142031-e2257fe61058/go.mod h1:rDpd7cy7itpPi3Kgb90fUgSnKwMXHYBk0R5DuNRiNNA=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260623093519-06ea214022e4 h1:ui12xOUPsCAYwzI7+7Hw2mVhrAbWDGNQZcrBiELhGk0=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260623093519-06ea214022e4/go.mod h1:W00EeoPdd2jbV3+ZUa0m2b7FdKx5B1LFsXvEpy7cToQ=
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c h1:+2C1UshSLzaogLY/IDz1XhOLxjhs3rkhVHB4eCN9Zto=
+48 -2
View File
@@ -15,6 +15,9 @@ import (
"github.com/metacubex/mihomo/component/ech"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/jls"
"github.com/metacubex/mihomo/listener/restls"
"github.com/metacubex/mihomo/listener/shadowtls"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/transport/anytls/padding"
@@ -43,6 +46,9 @@ func New(config LC.AnyTLSServer, lc C.InboundListenConfig, tunnel C.Tunnel, addi
}
}
var shadowTLSBuilder *shadowtls.Builder
var restlsBuilder *restls.Builder
var jlsBuilder *jls.Builder
tlsConfig := &tls.Config{Time: ntp.Now}
if config.Certificate != "" && config.PrivateKey != "" {
certLoader, err := ca.NewTLSKeyPairLoader(config.Certificate, config.PrivateKey)
@@ -73,6 +79,40 @@ func New(config LC.AnyTLSServer, lc C.InboundListenConfig, tunnel C.Tunnel, addi
}
tlsConfig.ClientCAs = pool
}
if tlsConfig.ClientAuth != tls.NoClientCert && tlsConfig.GetCertificate == nil {
return nil, errors.New("client-auth requires certificate")
}
securityModes := make([]string, 0, 4)
if tlsConfig.GetCertificate != nil {
securityModes = append(securityModes, "certificate")
}
if config.ShadowTLS.Enable {
securityModes = append(securityModes, "shadow-tls")
}
if config.ResTLS.Enable {
securityModes = append(securityModes, "res-tls")
}
if config.JLSConfig.Enable {
securityModes = append(securityModes, "jls")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
if config.ShadowTLS.Enable {
shadowTLSBuilder, err = shadowtls.New(config.ShadowTLS, tunnel)
if err != nil {
return nil, err
}
}
if config.ResTLS.Enable {
restlsBuilder = restls.New(config.ResTLS, tunnel)
}
if config.JLSConfig.Enable {
jlsBuilder, err = jls.New(config.JLSConfig, tunnel)
if err != nil {
return nil, err
}
}
sl = &Listener{
config: config,
@@ -110,10 +150,16 @@ func New(config LC.AnyTLSServer, lc C.InboundListenConfig, tunnel C.Tunnel, addi
if err != nil {
return nil, err
}
if tlsConfig.GetCertificate != nil {
if shadowTLSBuilder != nil {
l = shadowTLSBuilder.NewListener(l)
} else if restlsBuilder != nil {
l = restlsBuilder.NewListener(l)
} else if jlsBuilder != nil {
l = jlsBuilder.NewListener(l)
} else if tlsConfig.GetCertificate != nil {
l = tls.NewListener(l, tlsConfig)
} else if !config.AllowInsecure {
return nil, errors.New("disallow using AnyTLS without certificates/allow-insecure config")
return nil, errors.New("disallow using AnyTLS without certificates/shadow-tls/res-tls/jls/allow-insecure config")
}
sl.listeners = append(sl.listeners, l)
+5 -2
View File
@@ -8,11 +8,14 @@ type AnyTLSServer struct {
Enable bool `yaml:"enable" json:"enable"`
Listen string `yaml:"listen" json:"listen"`
Users map[string]string `yaml:"users" json:"users,omitempty"`
Certificate string `yaml:"certificate" json:"certificate"`
PrivateKey string `yaml:"private-key" json:"private-key"`
Certificate string `yaml:"certificate,omitempty" json:"certificate,omitempty"`
PrivateKey string `yaml:"private-key,omitempty" json:"private-key,omitempty"`
ClientAuthType string `yaml:"client-auth-type" json:"client-auth-type,omitempty"`
ClientAuthCert string `yaml:"client-auth-cert" json:"client-auth-cert,omitempty"`
EchKey string `yaml:"ech-key" json:"ech-key,omitempty"`
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
AllowInsecure bool `yaml:"allow-insecure" json:"allow-insecure,omitempty"`
PaddingScheme string `yaml:"padding-scheme" json:"padding-scheme,omitempty"`
}
+1
View File
@@ -49,6 +49,7 @@ type Hysteria2RealmOption struct {
// for ServerURL
SNI string `yaml:"sni" json:"sni,omitempty"`
SkipCertVerify bool `yaml:"skip-cert-verify" json:"skip-cert-verify,omitempty"`
NameCertVerify string `yaml:"name-cert-verify" json:"name-cert-verify,omitempty"`
Fingerprint string `yaml:"fingerprint" json:"fingerprint,omitempty"`
Certificate string `yaml:"certificate" json:"certificate,omitempty"`
PrivateKey string `yaml:"private-key" json:"private-key,omitempty"`
+16
View File
@@ -0,0 +1,16 @@
package config
type JLSConfig struct {
Enable bool
Users []JLSUser
SNI string
Dest string
ALPN []string
Proxy string
RateLimit uint64
}
type JLSUser struct {
Username string
Password string
}
+47
View File
@@ -0,0 +1,47 @@
package config
import (
"encoding/json"
"github.com/metacubex/mihomo/listener/sing"
)
type ShadowQuicUser struct {
Username string `yaml:"username" json:"username"`
Password string `yaml:"password" json:"password"`
}
type ShadowQuicJLSUpstream struct {
Addr string `yaml:"addr" json:"addr"`
SNI string `yaml:"sni" json:"sni,omitempty"`
Proxy string `yaml:"proxy" json:"proxy,omitempty"`
RateLimit uint64 `yaml:"rate-limit" json:"rate-limit,omitempty"`
QUICVersionProbe bool `yaml:"quic-version-probe" json:"quic-version-probe,omitempty"`
}
type ShadowQuicServer struct {
Enable bool `yaml:"enable" json:"enable"`
Listen string `yaml:"listen" json:"listen"`
Users []ShadowQuicUser `yaml:"users" json:"users,omitempty"`
JLSUpstream ShadowQuicJLSUpstream `yaml:"jls-upstream" json:"jls-upstream"`
ALPN []string `yaml:"alpn" json:"alpn,omitempty"`
QUICVersions []string `yaml:"quic-versions" json:"quic-versions,omitempty"`
ZeroRTT bool `yaml:"zero-rtt" json:"zero-rtt,omitempty"`
CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
Up string `yaml:"up" json:"up,omitempty"`
Down string `yaml:"down" json:"down,omitempty"`
IgnoreClientBandwidth bool `yaml:"ignore-client-bandwidth" json:"ignore-client-bandwidth,omitempty"`
MaxIdleTime int `yaml:"max-idle-time" json:"max-idle-time,omitempty"`
MaxDatagramFrameSize int `yaml:"max-datagram-frame-size" json:"max-datagram-frame-size,omitempty"`
ReceiveWindowConn int `yaml:"recv-window-conn" json:"recv-window-conn,omitempty"`
ReceiveWindow int `yaml:"recv-window" json:"recv-window,omitempty"`
DisableMTUDiscovery bool `yaml:"disable-mtu-discovery" json:"disable-mtu-discovery,omitempty"`
CWND int `yaml:"cwnd" json:"cwnd,omitempty"`
BBRProfile string `yaml:"bbr-profile" json:"bbr-profile,omitempty"`
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
}
func (s ShadowQuicServer) String() string {
b, _ := json.Marshal(s)
return string(b)
}
+1
View File
@@ -15,6 +15,7 @@ type ShadowsocksServer struct {
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
KcpTun KcpTun `yaml:"kcp-tun" json:"kcp-tun,omitempty"`
SimpleObfs SimpleObfs `yaml:"simple-obfs" json:"simple-obfs,omitempty"`
}
+2
View File
@@ -10,6 +10,8 @@ type SnellServer struct {
ObfsMode string
ObfsHost string
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
}
func (c SnellServer) String() string {
+4 -1
View File
@@ -24,7 +24,10 @@ type TrojanServer struct {
ClientAuthCert string
EchKey string
AllowInsecure bool
RealityConfig reality.Config
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
RealityConfig reality.Config `yaml:"reality-config" json:"reality-config,omitempty"`
MuxOption sing.MuxOption
TrojanSSOption TrojanSSOption
}
+4 -1
View File
@@ -27,7 +27,10 @@ type VlessServer struct {
ClientAuthCert string
EchKey string
AllowInsecure bool
RealityConfig reality.Config
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
RealityConfig reality.Config `yaml:"reality-config" json:"reality-config,omitempty"`
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
}
+4 -1
View File
@@ -25,7 +25,10 @@ type VmessServer struct {
ClientAuthType string
ClientAuthCert string
EchKey string
RealityConfig reality.Config
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
RealityConfig reality.Config `yaml:"reality-config" json:"reality-config,omitempty"`
TLSMirrorConfig TLSMirrorConfig `yaml:"tlsmirror-config" json:"tlsmirror-config,omitempty"`
MekyaConfig MekyaConfig `yaml:"mekya-config" json:"mekya-config,omitempty"`
MKCPConfig MKCPConfig `yaml:"mkcp-config" json:"mkcp-config,omitempty"`
+1 -1
View File
@@ -191,7 +191,7 @@ func (s *server) reaper(ctx context.Context) {
for {
select {
case <-ctx.Done():
break
return
case <-t.C:
s.mu.Lock()
now := time.Now()
+8 -2
View File
@@ -12,11 +12,14 @@ import (
type AnyTLSOption struct {
BaseOption
Users map[string]string `inbound:"users,omitempty"`
Certificate string `inbound:"certificate"`
PrivateKey string `inbound:"private-key"`
Certificate string `inbound:"certificate,omitempty"`
PrivateKey string `inbound:"private-key,omitempty"`
ClientAuthType string `inbound:"client-auth-type,omitempty"`
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
EchKey string `inbound:"ech-key,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
ResTLS ResTLS `inbound:"res-tls,omitempty"`
JLSConfig JLSConfig `inbound:"jls-config,omitempty"`
AllowInsecure bool `inbound:"allow-insecure,omitempty"`
PaddingScheme string `inbound:"padding-scheme,omitempty"`
}
@@ -49,6 +52,9 @@ func NewAnyTLS(options *AnyTLSOption) (*AnyTLS, error) {
ClientAuthType: options.ClientAuthType,
ClientAuthCert: options.ClientAuthCert,
EchKey: options.EchKey,
ShadowTLS: options.ShadowTLS.Build(),
ResTLS: options.ResTLS.Build(),
JLSConfig: options.JLSConfig.Build(),
AllowInsecure: options.AllowInsecure,
PaddingScheme: options.PaddingScheme,
},
+67
View File
@@ -1,6 +1,7 @@
package inbound_test
import (
"net"
"net/netip"
"testing"
@@ -94,3 +95,69 @@ func TestInboundAnyTLS_TLS(t *testing.T) {
testInboundAnyTLS(t, inboundOptions, outboundOptions)
})
}
func testInboundAnyTLSUTLS(t *testing.T, inboundOptions inbound.AnyTLSOption, outboundOptions outbound.AnyTLSOption) {
t.Parallel()
t.Run("Conn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
testInboundAnyTLS(t, inboundOptions, outboundOptions)
})
t.Run("UConn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
outboundOptions.ClientFingerprint = "chrome"
testInboundAnyTLS(t, inboundOptions, outboundOptions)
})
}
func TestInboundAnyTLS_ShadowTLS(t *testing.T) {
const password = "shadow-tls-password"
inboundOptions := inbound.AnyTLSOption{
ShadowTLS: inbound.ShadowTLS{
Enable: true,
Version: 3,
Users: []inbound.ShadowTLSUser{{Name: "test", Password: password}},
Handshake: inbound.ShadowTLSHandshakeOptions{Dest: net.JoinHostPort(realityDest, "443")},
},
}
outboundOptions := outbound.AnyTLSOption{
SNI: realityDest,
Fingerprint: tlsFingerprint,
ShadowTLSOpts: outbound.ShadowTLSOptions{Password: password, Version: 3},
}
testInboundAnyTLSUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundAnyTLS_Restls(t *testing.T) {
const password = "restls-password"
inboundOptions := inbound.AnyTLSOption{
ResTLS: inbound.ResTLS{
Enable: true,
Dest: net.JoinHostPort(realityDest, "443"),
Password: password,
},
}
outboundOptions := outbound.AnyTLSOption{
SNI: realityDest,
Fingerprint: tlsFingerprint,
RestlsOpts: outbound.RestlsOptions{Password: password, VersionHint: "tls13"},
}
testInboundAnyTLSUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundAnyTLS_JLS(t *testing.T) {
const username = "jls-user"
const password = "jls-password"
inboundOptions := inbound.AnyTLSOption{
JLSConfig: inbound.JLSConfig{
Enable: true,
Users: []inbound.JLSUser{{Username: username, Password: password}},
SNI: realityDest,
Dest: net.JoinHostPort(realityDest, "443"),
},
}
outboundOptions := outbound.AnyTLSOption{
SNI: realityDest,
JLSOpts: outbound.JLSOptions{Username: username, Password: password},
}
testInboundAnyTLSUTLS(t, inboundOptions, outboundOptions)
}
+3
View File
@@ -10,7 +10,9 @@ import (
"net"
"net/netip"
"os"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
@@ -47,6 +49,7 @@ var realityShortid = "10f897e26c4b9478"
var realityRealDial = false
var echPublicSni = "public.sni"
var echConfigBase64, echKeyPem, _ = ech.GenECHConfig(echPublicSni)
var winGo120 = runtime.GOOS == "windows" && strings.HasPrefix(runtime.Version(), "go1.20")
func init() {
rand.Read(httpData)
+2
View File
@@ -51,6 +51,7 @@ type Hysteria2RealmOption struct {
// for ServerURL
SNI string `inbound:"sni,omitempty"`
SkipCertVerify bool `inbound:"skip-cert-verify,omitempty"`
NameCertVerify string `inbound:"name-cert-verify,omitempty"`
Fingerprint string `inbound:"fingerprint,omitempty"`
Certificate string `inbound:"certificate,omitempty"`
PrivateKey string `inbound:"private-key,omitempty"`
@@ -67,6 +68,7 @@ func (o Hysteria2RealmOption) Build() LC.Hysteria2RealmOption {
STUNServers: o.STUNServers,
SNI: o.SNI,
SkipCertVerify: o.SkipCertVerify,
NameCertVerify: o.NameCertVerify,
Fingerprint: o.Fingerprint,
Certificate: o.Certificate,
PrivateKey: o.PrivateKey,
+3
View File
@@ -55,6 +55,9 @@ func testInboundHysteria2(t *testing.T, inboundOptions inbound.Hysteria2Option,
func testInboundHysteria2TLS(t *testing.T, inboundOptions inbound.Hysteria2Option, outboundOptions outbound.Hysteria2Option) {
testInboundHysteria2(t, inboundOptions, outboundOptions)
if winGo120 {
return // subsequent tests frequently fail; skipping them for now.
}
t.Run("ECH", func(t *testing.T) {
inboundOptions := inboundOptions
outboundOptions := outboundOptions
+40
View File
@@ -0,0 +1,40 @@
package inbound
import (
"github.com/metacubex/mihomo/common/utils"
LC "github.com/metacubex/mihomo/listener/config"
)
type JLSConfig struct {
Enable bool `inbound:"enable"`
Users []JLSUser `inbound:"users"`
SNI string `inbound:"sni,omitempty"`
Dest string `inbound:"dest"`
ALPN []string `inbound:"alpn,omitempty"`
Proxy string `inbound:"proxy,omitempty"`
RateLimit uint64 `inbound:"rate-limit,omitempty"`
}
type JLSUser struct {
Username string `inbound:"username"`
Password string `inbound:"password"`
}
func (j JLSConfig) Build() LC.JLSConfig {
return LC.JLSConfig{
Enable: j.Enable,
Users: utils.Map(j.Users, JLSUser.Build),
SNI: j.SNI,
Dest: j.Dest,
ALPN: append([]string(nil), j.ALPN...),
Proxy: j.Proxy,
RateLimit: j.RateLimit,
}
}
func (u JLSUser) Build() LC.JLSUser {
return LC.JLSUser{
Username: u.Username,
Password: u.Password,
}
}
+138
View File
@@ -0,0 +1,138 @@
package inbound
import (
"strings"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/shadowquic"
"github.com/metacubex/mihomo/log"
)
type ShadowQuicOption struct {
BaseOption
Users []ShadowQuicUser `inbound:"users,omitempty"`
JLSUpstream ShadowQuicJLSUpstream `inbound:"jls-upstream"`
ALPN []string `inbound:"alpn,omitempty"`
QUICVersions []string `inbound:"quic-versions,omitempty"`
ZeroRTT bool `inbound:"zero-rtt,omitempty"`
CongestionController string `inbound:"congestion-controller,omitempty"`
Up string `inbound:"up,omitempty"`
Down string `inbound:"down,omitempty"`
IgnoreClientBandwidth bool `inbound:"ignore-client-bandwidth,omitempty"`
MaxIdleTime int `inbound:"max-idle-time,omitempty"`
MaxDatagramFrameSize int `inbound:"max-datagram-frame-size,omitempty"`
ReceiveWindowConn int `inbound:"recv-window-conn,omitempty"`
ReceiveWindow int `inbound:"recv-window,omitempty"`
DisableMTUDiscovery bool `inbound:"disable-mtu-discovery,omitempty"`
CWND int `inbound:"cwnd,omitempty"`
BBRProfile string `inbound:"bbr-profile,omitempty"`
MuxOption MuxOption `inbound:"mux-option,omitempty"`
}
type ShadowQuicUser struct {
Username string `inbound:"username"`
Password string `inbound:"password"`
}
type ShadowQuicJLSUpstream struct {
Addr string `inbound:"addr"`
SNI string `inbound:"sni,omitempty"`
Proxy string `inbound:"proxy,omitempty"`
RateLimit uint64 `inbound:"rate-limit,omitempty"`
QUICVersionProbe bool `inbound:"quic-version-probe,omitempty"`
}
func (u ShadowQuicUser) Build() LC.ShadowQuicUser {
return LC.ShadowQuicUser{
Username: u.Username,
Password: u.Password,
}
}
func (u ShadowQuicJLSUpstream) Build() LC.ShadowQuicJLSUpstream {
return LC.ShadowQuicJLSUpstream{
Addr: u.Addr,
SNI: u.SNI,
Proxy: u.Proxy,
RateLimit: u.RateLimit,
QUICVersionProbe: u.QUICVersionProbe,
}
}
func (o ShadowQuicOption) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
}
type ShadowQuic struct {
*Base
config *ShadowQuicOption
l *shadowquic.Listener
ss LC.ShadowQuicServer
}
func NewShadowQuic(options *ShadowQuicOption) (*ShadowQuic, error) {
base, err := NewBase(&options.BaseOption)
if err != nil {
return nil, err
}
return &ShadowQuic{
Base: base,
config: options,
ss: LC.ShadowQuicServer{
Enable: true,
Listen: base.RawAddress(),
Users: utils.Map(options.Users, ShadowQuicUser.Build),
JLSUpstream: options.JLSUpstream.Build(),
ALPN: options.ALPN,
QUICVersions: options.QUICVersions,
ZeroRTT: options.ZeroRTT,
CongestionController: options.CongestionController,
Up: options.Up,
Down: options.Down,
IgnoreClientBandwidth: options.IgnoreClientBandwidth,
MaxIdleTime: options.MaxIdleTime,
MaxDatagramFrameSize: options.MaxDatagramFrameSize,
ReceiveWindowConn: options.ReceiveWindowConn,
ReceiveWindow: options.ReceiveWindow,
DisableMTUDiscovery: options.DisableMTUDiscovery,
CWND: options.CWND,
BBRProfile: options.BBRProfile,
MuxOption: options.MuxOption.Build(),
},
}, nil
}
func (s *ShadowQuic) Config() C.InboundConfig {
return s.config
}
func (s *ShadowQuic) Address() string {
var addrList []string
if s.l != nil {
for _, addr := range s.l.AddrList() {
addrList = append(addrList, addr.String())
}
}
return strings.Join(addrList, ",")
}
func (s *ShadowQuic) Listen(tunnel C.Tunnel) error {
var err error
s.l, err = shadowquic.New(s.ss, s.ListenConfig(), tunnel, s.Additions()...)
if err != nil {
return err
}
log.Infoln("ShadowQuic[%s] proxy listening at: %s", s.Name(), s.Address())
return nil
}
func (s *ShadowQuic) Close() error {
if s.l != nil {
return s.l.Close()
}
return nil
}
var _ C.InboundListener = (*ShadowQuic)(nil)
+185
View File
@@ -0,0 +1,185 @@
package inbound_test
import (
"encoding/binary"
"errors"
"fmt"
"net"
"net/netip"
"testing"
"time"
"github.com/metacubex/mihomo/adapter/outbound"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/listener/inbound"
"github.com/metacubex/jls-quic-go"
"github.com/stretchr/testify/assert"
)
func TestInboundShadowQuic(t *testing.T) {
for _, test := range []struct {
name string
clientVersion string
serverVersion string
probedVersion quic.Version
}{
{name: "v1", clientVersion: "v1", serverVersion: "v1"},
{name: "v2", clientVersion: "v2", serverVersion: "v2"},
{name: "v1 with server probe", clientVersion: "v1", serverVersion: "v2", probedVersion: quic.Version1},
{name: "v2 with server probe", clientVersion: "v2", serverVersion: "v1", probedVersion: quic.Version2},
} {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
testInboundShadowQuic(t, test.clientVersion, test.serverVersion, test.probedVersion)
})
}
}
func testInboundShadowQuic(t *testing.T, clientVersion, serverVersion string, probedVersion quic.Version) {
const username = "shadowquic-user"
const password = "shadowquic-password"
inboundOptions := inbound.ShadowQuicOption{
BaseOption: inbound.BaseOption{
NameStr: "shadowquic_inbound",
Listen: "127.0.0.1",
Port: "0",
},
ALPN: []string{"h3"},
QUICVersions: []string{serverVersion},
ZeroRTT: true,
MaxIdleTime: 30000,
MaxDatagramFrameSize: 1400,
Users: []inbound.ShadowQuicUser{{Username: username, Password: password}},
JLSUpstream: inbound.ShadowQuicJLSUpstream{Addr: "127.0.0.1:1"},
}
var probeResult <-chan error
var probeHandler func(C.UDPPacket, *C.Metadata)
if probedVersion != 0 {
upstreamAddr, result, handler := newShadowQuicVersionProbeUpstream(probedVersion)
probeResult = result
probeHandler = handler
inboundOptions.JLSUpstream = inbound.ShadowQuicJLSUpstream{
Addr: upstreamAddr,
Proxy: "shadowquic-probe-proxy",
QUICVersionProbe: true,
}
}
in, err := inbound.NewShadowQuic(&inboundOptions)
if !assert.NoError(t, err) {
return
}
tunnel := NewHttpTestTunnel()
defer tunnel.Close()
if probeHandler != nil {
tunnel.HandleUDPPacketFn = probeHandler
} else {
tunnel.HandleUDPPacketFn = func(packet C.UDPPacket, metadata *C.Metadata) {
packet.Drop()
t.Errorf("authenticated ShadowQUIC connection unexpectedly accessed JLS upstream %s", metadata.RemoteAddress())
}
}
if !assert.NoError(t, in.Listen(tunnel)) {
return
}
defer in.Close()
addrPort, err := netip.ParseAddrPort(in.Address())
if !assert.NoError(t, err) {
return
}
outboundOptions := outbound.ShadowQuicOption{
Name: "shadowquic_outbound",
Server: addrPort.Addr().String(),
Port: int(addrPort.Port()),
ALPN: []string{"h3"},
QUICVersions: []string{clientVersion},
ZeroRTT: true,
MaxDatagramFrameSize: 1400,
Username: username,
Password: password,
}
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewShadowQuic(outboundOptions)
if !assert.NoError(t, err) {
return
}
defer out.Close()
tunnel.DoTest(t, out)
if probeResult != nil {
select {
case err := <-probeResult:
assert.NoError(t, err)
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for ShadowQUIC version probe")
}
}
}
func newShadowQuicVersionProbeUpstream(version quic.Version) (string, <-chan error, func(C.UDPPacket, *C.Metadata)) {
result := make(chan error, 1)
handler := func(packet C.UDPPacket, metadata *C.Metadata) {
defer packet.Drop()
var probeErr error
if metadata.Type != C.INNER || metadata.NetWork != C.UDP {
probeErr = fmt.Errorf("version probe type/network = %s/%s, want Inner/udp", metadata.Type, metadata.NetWork)
} else if metadata.RemoteAddress() != "127.0.0.1:443" {
probeErr = fmt.Errorf("version probe destination = %s", metadata.RemoteAddress())
} else if metadata.SpecialProxy != "shadowquic-probe-proxy" {
probeErr = fmt.Errorf("version probe proxy = %q", metadata.SpecialProxy)
}
response, err := composeShadowQuicVersionNegotiation(packet.Data(), version)
if err == nil {
_, err = packet.WriteBack(response, &net.UDPAddr{IP: net.IPv4(192, 0, 2, 1), Port: 443})
}
if probeErr == nil {
probeErr = err
}
select {
case result <- probeErr:
default:
}
}
return "127.0.0.1:443", result, handler
}
func composeShadowQuicVersionNegotiation(probe []byte, version quic.Version) ([]byte, error) {
if len(probe) < 7 {
return nil, errors.New("short QUIC version probe")
}
if probe[0]&0x80 == 0 {
return nil, errors.New("QUIC version probe does not use a long header")
}
probeVersion := quic.Version(binary.BigEndian.Uint32(probe[1:5]))
if probeVersion == 0 || probeVersion == quic.Version1 || probeVersion == quic.Version2 {
return nil, fmt.Errorf("QUIC version probe uses non-probe version %#x", probeVersion)
}
offset := 5
dcidLen := int(probe[offset])
offset++
if offset+dcidLen >= len(probe) {
return nil, errors.New("invalid QUIC version probe destination connection ID")
}
dcid := probe[offset : offset+dcidLen]
offset += dcidLen
scidLen := int(probe[offset])
offset++
if offset+scidLen > len(probe) {
return nil, errors.New("invalid QUIC version probe source connection ID")
}
scid := probe[offset : offset+scidLen]
response := []byte{0x80, 0, 0, 0, 0, byte(len(scid))}
response = append(response, scid...)
response = append(response, byte(len(dcid)))
response = append(response, dcid...)
response = binary.BigEndian.AppendUint32(response, uint32(version))
return response, nil
}
+2
View File
@@ -17,6 +17,7 @@ type ShadowSocksOption struct {
MuxOption MuxOption `inbound:"mux-option,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
ResTLS ResTLS `inbound:"res-tls,omitempty"`
JLSConfig JLSConfig `inbound:"jls-config,omitempty"`
KcpTun KcpTun `inbound:"kcp-tun,omitempty"`
SimpleObfs SimpleObfs `inbound:"simple-obfs,omitempty"`
}
@@ -61,6 +62,7 @@ func NewShadowSocks(options *ShadowSocksOption) (*ShadowSocks, error) {
MuxOption: options.MuxOption.Build(),
ShadowTLS: options.ShadowTLS.Build(),
ResTLS: options.ResTLS.Build(),
JLSConfig: options.JLSConfig.Build(),
KcpTun: options.KcpTun.Build(),
SimpleObfs: options.SimpleObfs.Build(),
},
+31 -9
View File
@@ -5,15 +5,15 @@ import (
"encoding/base64"
"net"
"net/netip"
"runtime"
"strings"
"testing"
"github.com/metacubex/mihomo/adapter/outbound"
"github.com/metacubex/mihomo/listener/inbound"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/kcptun"
"github.com/metacubex/mihomo/transport/restls"
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
"github.com/metacubex/mihomo/transport/shadowtls"
shadowsocks "github.com/metacubex/sing-shadowsocks"
"github.com/metacubex/sing-shadowsocks/shadowaead"
@@ -108,16 +108,16 @@ func TestInboundShadowSocks_Basic(t *testing.T) {
testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherLists, true)
}
func testInboundShadowSocksShadowTls(t *testing.T, inboundOptions inbound.ShadowSocksOption, outboundOptions outbound.ShadowSocksOption) {
func testInboundShadowSocksUTLS(t *testing.T, inboundOptions inbound.ShadowSocksOption, outboundOptions outbound.ShadowSocksOption, enableSingMux bool) {
t.Parallel()
t.Run("Conn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, true)
testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, enableSingMux)
})
t.Run("UConn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
outboundOptions.ClientFingerprint = "chrome"
testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, true)
testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, enableSingMux)
})
}
@@ -133,7 +133,7 @@ func TestInboundShadowSocks_ShadowTlsv1(t *testing.T) {
Plugin: shadowtls.Mode,
PluginOpts: map[string]any{"host": realityDest, "fingerprint": tlsFingerprint, "version": 1},
}
testInboundShadowSocksShadowTls(t, inboundOptions, outboundOptions)
testInboundShadowSocksUTLS(t, inboundOptions, outboundOptions, true)
}
func TestInboundShadowSocks_ShadowTlsv2(t *testing.T) {
@@ -150,7 +150,7 @@ func TestInboundShadowSocks_ShadowTlsv2(t *testing.T) {
PluginOpts: map[string]any{"host": realityDest, "password": shadowsocksPassword16, "fingerprint": tlsFingerprint, "version": 2},
}
outboundOptions.PluginOpts["alpn"] = []string{"http/1.1"} // shadowtls v2 work confuse with http/2 server, so we set alpn to http/1.1 to pass the test
testInboundShadowSocksShadowTls(t, inboundOptions, outboundOptions)
testInboundShadowSocksUTLS(t, inboundOptions, outboundOptions, true)
}
func TestInboundShadowSocks_ShadowTlsv3(t *testing.T) {
@@ -166,7 +166,7 @@ func TestInboundShadowSocks_ShadowTlsv3(t *testing.T) {
Plugin: shadowtls.Mode,
PluginOpts: map[string]any{"host": realityDest, "password": shadowsocksPassword16, "fingerprint": tlsFingerprint, "version": 3},
}
testInboundShadowSocksShadowTls(t, inboundOptions, outboundOptions)
testInboundShadowSocksUTLS(t, inboundOptions, outboundOptions, true)
}
func TestInboundShadowSocks_Restls_tls12(t *testing.T) {
@@ -199,6 +199,28 @@ func TestInboundShadowSocks_Restls_tls13(t *testing.T) {
testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, false)
}
func TestInboundShadowSocks_JLS(t *testing.T) {
username := "jls-user"
password := "jls-password"
inboundOptions := inbound.ShadowSocksOption{
JLSConfig: inbound.JLSConfig{
Enable: true,
Users: []inbound.JLSUser{{Username: username, Password: password}},
SNI: realityDest,
Dest: net.JoinHostPort(realityDest, "443"),
},
}
outboundOptions := outbound.ShadowSocksOption{
Plugin: jls.Mode,
PluginOpts: map[string]any{
"host": realityDest,
"username": username,
"password": password,
},
}
testInboundShadowSocksUTLS(t, inboundOptions, outboundOptions, false)
}
func TestInboundShadowSocks_SimpleObfs_Http(t *testing.T) {
inboundOptions := inbound.ShadowSocksOption{
SimpleObfs: inbound.SimpleObfs{
@@ -228,7 +250,7 @@ func TestInboundShadowSocks_SimpleObfs_Tls(t *testing.T) {
}
func TestInboundShadowSocks_KcpTun(t *testing.T) {
if runtime.GOOS == "windows" && strings.HasPrefix(runtime.Version(), "go1.20") {
if winGo120 {
t.Skip("skip kcptun test on windows go1.20")
}
inboundOptions := inbound.ShadowSocksOption{
+4
View File
@@ -17,6 +17,8 @@ type SnellOption struct {
UDP bool `inbound:"udp,omitempty"`
ObfsOpts SnellObfsOption `inbound:"obfs-opts,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
ResTLS ResTLS `inbound:"res-tls,omitempty"`
JLSConfig JLSConfig `inbound:"jls-config,omitempty"`
}
func (o SnellOption) Equal(config C.InboundConfig) bool {
@@ -58,6 +60,8 @@ func NewSnell(options *SnellOption) (*Snell, error) {
ObfsMode: options.ObfsOpts.Mode,
ObfsHost: options.ObfsOpts.Host,
ShadowTLS: options.ShadowTLS.Build(),
ResTLS: options.ResTLS.Build(),
JLSConfig: options.JLSConfig.Build(),
},
}, nil
}
+40 -4
View File
@@ -7,7 +7,9 @@ import (
"github.com/metacubex/mihomo/adapter/outbound"
"github.com/metacubex/mihomo/listener/inbound"
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowtls"
"github.com/stretchr/testify/assert"
)
@@ -76,7 +78,7 @@ func TestInboundSnell(t *testing.T) {
}
}
func testInboundSnellShadowTls(t *testing.T, inboundOptions inbound.SnellOption, outboundOptions outbound.SnellOption) {
func testInboundSnellUTLS(t *testing.T, inboundOptions inbound.SnellOption, outboundOptions outbound.SnellOption) {
t.Parallel()
t.Run("Conn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
@@ -103,7 +105,7 @@ func TestInboundSnell_ShadowTlsv2(t *testing.T) {
ObfsOpts: map[string]any{"mode": shadowtls.Mode, "host": realityDest, "password": shadowsocksPassword16, "fingerprint": tlsFingerprint, "version": 2},
}
outboundOptions.ObfsOpts["alpn"] = []string{"http/1.1"} // shadowtls v2 work confuse with http/2 server, so we set alpn to http/1.1 to pass the test
testInboundSnellShadowTls(t, inboundOptions, outboundOptions)
testInboundSnellUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundSnell_ShadowTlsv3(t *testing.T) {
@@ -119,5 +121,39 @@ func TestInboundSnell_ShadowTlsv3(t *testing.T) {
Version: 5,
ObfsOpts: map[string]any{"mode": shadowtls.Mode, "host": realityDest, "password": shadowsocksPassword16, "fingerprint": tlsFingerprint, "version": 3},
}
testInboundSnellShadowTls(t, inboundOptions, outboundOptions)
testInboundSnellUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundSnell_Restls(t *testing.T) {
const password = "restls-password"
inboundOptions := inbound.SnellOption{
ResTLS: inbound.ResTLS{
Enable: true,
Dest: net.JoinHostPort(realityDest, "443"),
Password: password,
},
}
outboundOptions := outbound.SnellOption{
Version: 5,
ObfsOpts: map[string]any{"mode": restls.Mode, "host": realityDest, "password": password, "fingerprint": tlsFingerprint, "version-hint": "tls13"},
}
testInboundSnellUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundSnell_JLS(t *testing.T) {
const username = "jls-user"
const password = "jls-password"
inboundOptions := inbound.SnellOption{
JLSConfig: inbound.JLSConfig{
Enable: true,
Users: []inbound.JLSUser{{Username: username, Password: password}},
SNI: realityDest,
Dest: net.JoinHostPort(realityDest, "443"),
},
}
outboundOptions := outbound.SnellOption{
Version: 5,
ObfsOpts: map[string]any{"mode": jls.Mode, "host": realityDest, "username": username, "password": password},
}
testInboundSnellUTLS(t, inboundOptions, outboundOptions)
}
+6
View File
@@ -20,6 +20,9 @@ type TrojanOption struct {
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
EchKey string `inbound:"ech-key,omitempty"`
AllowInsecure bool `inbound:"allow-insecure,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
ResTLS ResTLS `inbound:"res-tls,omitempty"`
JLSConfig JLSConfig `inbound:"jls-config,omitempty"`
RealityConfig RealityConfig `inbound:"reality-config,omitempty"`
MuxOption MuxOption `inbound:"mux-option,omitempty"`
SSOption TrojanSSOption `inbound:"ss-option,omitempty"`
@@ -75,6 +78,9 @@ func NewTrojan(options *TrojanOption) (*Trojan, error) {
ClientAuthCert: options.ClientAuthCert,
EchKey: options.EchKey,
AllowInsecure: options.AllowInsecure,
ShadowTLS: options.ShadowTLS.Build(),
ResTLS: options.ResTLS.Build(),
JLSConfig: options.JLSConfig.Build(),
RealityConfig: options.RealityConfig.Build(),
MuxOption: options.MuxOption.Build(),
TrojanSSOption: LC.TrojanSSOption{
+66
View File
@@ -168,6 +168,72 @@ func TestInboundTrojan_Grpc2(t *testing.T) {
testInboundTrojanTLS(t, inboundOptions, outboundOptions)
}
func testInboundTrojanUTLS(t *testing.T, inboundOptions inbound.TrojanOption, outboundOptions outbound.TrojanOption) {
t.Parallel()
t.Run("Conn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
testInboundTrojan(t, inboundOptions, outboundOptions)
})
t.Run("UConn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
outboundOptions.ClientFingerprint = "chrome"
testInboundTrojan(t, inboundOptions, outboundOptions)
})
}
func TestInboundTrojan_ShadowTLS(t *testing.T) {
const password = "shadow-tls-password"
inboundOptions := inbound.TrojanOption{
ShadowTLS: inbound.ShadowTLS{
Enable: true,
Version: 3,
Users: []inbound.ShadowTLSUser{{Name: "test", Password: password}},
Handshake: inbound.ShadowTLSHandshakeOptions{Dest: net.JoinHostPort(realityDest, "443")},
},
}
outboundOptions := outbound.TrojanOption{
SNI: realityDest,
Fingerprint: tlsFingerprint,
ShadowTLSOpts: outbound.ShadowTLSOptions{Password: password, Version: 3},
}
testInboundTrojanUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundTrojan_Restls(t *testing.T) {
const password = "restls-password"
inboundOptions := inbound.TrojanOption{
ResTLS: inbound.ResTLS{
Enable: true,
Dest: net.JoinHostPort(realityDest, "443"),
Password: password,
},
}
outboundOptions := outbound.TrojanOption{
SNI: realityDest,
Fingerprint: tlsFingerprint,
RestlsOpts: outbound.RestlsOptions{Password: password, VersionHint: "tls13"},
}
testInboundTrojanUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundTrojan_JLS(t *testing.T) {
const username = "jls-user"
const password = "jls-password"
inboundOptions := inbound.TrojanOption{
JLSConfig: inbound.JLSConfig{
Enable: true,
Users: []inbound.JLSUser{{Username: username, Password: password}},
SNI: realityDest,
Dest: net.JoinHostPort(realityDest, "443"),
},
}
outboundOptions := outbound.TrojanOption{
SNI: realityDest,
JLSOpts: outbound.JLSOptions{Username: username, Password: password},
}
testInboundTrojanUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundTrojan_Reality(t *testing.T) {
inboundOptions := inbound.TrojanOption{
RealityConfig: inbound.RealityConfig{
+3
View File
@@ -69,6 +69,9 @@ func testInboundTrustTunnelTLS(t *testing.T, quic bool) {
outboundOptions.Quic = true
}
testInboundTrustTunnel(t, inboundOptions, outboundOptions)
if quic && winGo120 {
return // subsequent tests frequently fail; skipping them for now.
}
t.Run("ECH", func(t *testing.T) {
inboundOptions := inboundOptions
outboundOptions := outboundOptions
+3
View File
@@ -91,6 +91,9 @@ func TestInboundTuic_TLS(t *testing.T) {
Fingerprint: tlsFingerprint,
}
testInboundTuic(t, inboundOptions, outboundOptions)
if winGo120 {
return // subsequent tests frequently fail; skipping them for now.
}
t.Run("ECH", func(t *testing.T) {
inboundOptions := inboundOptions
outboundOptions := outboundOptions
+6
View File
@@ -22,6 +22,9 @@ type VlessOption struct {
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
EchKey string `inbound:"ech-key,omitempty"`
AllowInsecure bool `inbound:"allow-insecure,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
ResTLS ResTLS `inbound:"res-tls,omitempty"`
JLSConfig JLSConfig `inbound:"jls-config,omitempty"`
RealityConfig RealityConfig `inbound:"reality-config,omitempty"`
MuxOption MuxOption `inbound:"mux-option,omitempty"`
}
@@ -123,6 +126,9 @@ func NewVless(options *VlessOption) (*Vless, error) {
ClientAuthCert: options.ClientAuthCert,
EchKey: options.EchKey,
AllowInsecure: options.AllowInsecure,
ShadowTLS: options.ShadowTLS.Build(),
ResTLS: options.ResTLS.Build(),
JLSConfig: options.JLSConfig.Build(),
RealityConfig: options.RealityConfig.Build(),
MuxOption: options.MuxOption.Build(),
},
+69
View File
@@ -278,6 +278,75 @@ func TestInboundVless_Grpc2(t *testing.T) {
testInboundVlessTLS(t, inboundOptions, outboundOptions, false)
}
func testInboundVlessUTLS(t *testing.T, inboundOptions inbound.VlessOption, outboundOptions outbound.VlessOption) {
t.Parallel()
t.Run("Conn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
testInboundVless(t, inboundOptions, outboundOptions)
})
t.Run("UConn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
outboundOptions.ClientFingerprint = "chrome"
testInboundVless(t, inboundOptions, outboundOptions)
})
}
func TestInboundVless_ShadowTLS(t *testing.T) {
const password = "shadow-tls-password"
inboundOptions := inbound.VlessOption{
ShadowTLS: inbound.ShadowTLS{
Enable: true,
Version: 3,
Users: []inbound.ShadowTLSUser{{Name: "test", Password: password}},
Handshake: inbound.ShadowTLSHandshakeOptions{Dest: net.JoinHostPort(realityDest, "443")},
},
}
outboundOptions := outbound.VlessOption{
TLS: true,
ServerName: realityDest,
Fingerprint: tlsFingerprint,
ShadowTLSOpts: outbound.ShadowTLSOptions{Password: password, Version: 3},
}
testInboundVlessUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundVless_Restls(t *testing.T) {
const password = "restls-password"
inboundOptions := inbound.VlessOption{
ResTLS: inbound.ResTLS{
Enable: true,
Dest: net.JoinHostPort(realityDest, "443"),
Password: password,
},
}
outboundOptions := outbound.VlessOption{
TLS: true,
ServerName: realityDest,
Fingerprint: tlsFingerprint,
RestlsOpts: outbound.RestlsOptions{Password: password, VersionHint: "tls13"},
}
testInboundVlessUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundVless_JLS(t *testing.T) {
const username = "jls-user"
const password = "jls-password"
inboundOptions := inbound.VlessOption{
JLSConfig: inbound.JLSConfig{
Enable: true,
Users: []inbound.JLSUser{{Username: username, Password: password}},
SNI: realityDest,
Dest: net.JoinHostPort(realityDest, "443"),
},
}
outboundOptions := outbound.VlessOption{
TLS: true,
ServerName: realityDest,
JLSOpts: outbound.JLSOptions{Username: username, Password: password},
}
testInboundVlessUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundVless_Reality(t *testing.T) {
inboundOptions := inbound.VlessOption{
RealityConfig: inbound.RealityConfig{
+6
View File
@@ -19,6 +19,9 @@ type VmessOption struct {
ClientAuthType string `inbound:"client-auth-type,omitempty"`
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
EchKey string `inbound:"ech-key,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
ResTLS ResTLS `inbound:"res-tls,omitempty"`
JLSConfig JLSConfig `inbound:"jls-config,omitempty"`
RealityConfig RealityConfig `inbound:"reality-config,omitempty"`
TLSMirrorConfig TLSMirrorConfig `inbound:"tlsmirror-config,omitempty"`
MekyaConfig MekyaConfig `inbound:"mekya-config,omitempty"`
@@ -70,6 +73,9 @@ func NewVmess(options *VmessOption) (*Vmess, error) {
ClientAuthType: options.ClientAuthType,
ClientAuthCert: options.ClientAuthCert,
EchKey: options.EchKey,
ShadowTLS: options.ShadowTLS.Build(),
ResTLS: options.ResTLS.Build(),
JLSConfig: options.JLSConfig.Build(),
RealityConfig: options.RealityConfig.Build(),
TLSMirrorConfig: options.TLSMirrorConfig.Build(),
MekyaConfig: options.MekyaConfig.Build(),
+59 -10
View File
@@ -323,18 +323,67 @@ func vmessInteropRoundTripConn(conn net.Conn, payloadSize int) error {
if payloadSize == 0 {
payloadSize = len("vmess-interop-") * 256
}
payload := bytes.Repeat([]byte("x"), payloadSize)
_, err := conn.Write(payload)
if err != nil {
return fmt.Errorf("write: %w", err)
for round, payload := range vmessInteropRoundTripPayloads(payloadSize) {
if err := vmessInteropWritePayload(conn, payload, round); err != nil {
return fmt.Errorf("write round %d size %d: %w", round, len(payload), err)
}
got := make([]byte, len(payload))
if _, err := io.ReadFull(conn, got); err != nil {
return fmt.Errorf("read full round %d size %d: %w", round, len(payload), err)
}
if !bytes.Equal(payload, got) {
return fmt.Errorf("unexpected payload round %d size %d", round, len(payload))
}
}
got := make([]byte, len(payload))
_, err = io.ReadFull(conn, got)
if err != nil {
return fmt.Errorf("read full: %w", err)
return nil
}
func vmessInteropRoundTripPayloads(payloadSize int) [][]byte {
sizes := []int{1, 7, 64, 1024, payloadSize / 2, payloadSize}
payloads := make([][]byte, 0, len(sizes))
seen := make(map[int]struct{}, len(sizes))
for round, size := range sizes {
if size > payloadSize {
size = payloadSize
}
if size <= 0 {
continue
}
if _, ok := seen[size]; ok {
continue
}
seen[size] = struct{}{}
payloads = append(payloads, vmessInteropPayload(size, round))
}
if !bytes.Equal(payload, got) {
return fmt.Errorf("unexpected payload: got %d bytes", len(got))
return payloads
}
func vmessInteropPayload(size, round int) []byte {
payload := make([]byte, size)
for i := range payload {
payload[i] = byte((i*31 + round*17 + i>>8) % 251)
}
return payload
}
func vmessInteropWritePayload(conn net.Conn, payload []byte, round int) error {
if len(payload) <= 1 {
return vmessInteropWrite(conn, payload)
}
split := 1 + (round*37)%(len(payload)-1)
if err := vmessInteropWrite(conn, payload[:split]); err != nil {
return err
}
return vmessInteropWrite(conn, payload[split:])
}
func vmessInteropWrite(conn net.Conn, payload []byte) error {
n, err := conn.Write(payload)
if err != nil {
return err
}
if n != len(payload) {
return io.ErrShortWrite
}
return nil
}
+70
View File
@@ -210,6 +210,7 @@ func TestInboundVMess_Mekya(t *testing.T) {
MaxWriteDelay: 20,
MaxRequestSize: 96000,
PollingIntervalInitial: 20,
H2PoolSize: 8,
KCP: outbound.MKCPOptions{
TTI: 15,
},
@@ -501,6 +502,75 @@ func TestInboundVMess_Grpc2(t *testing.T) {
testInboundVMessTLS(t, inboundOptions, outboundOptions)
}
func testInboundVMessUTLS(t *testing.T, inboundOptions inbound.VmessOption, outboundOptions outbound.VmessOption) {
t.Parallel()
t.Run("Conn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
testInboundVMess(t, inboundOptions, outboundOptions)
})
t.Run("UConn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
outboundOptions.ClientFingerprint = "chrome"
testInboundVMess(t, inboundOptions, outboundOptions)
})
}
func TestInboundVMess_ShadowTLS(t *testing.T) {
const password = "shadow-tls-password"
inboundOptions := inbound.VmessOption{
ShadowTLS: inbound.ShadowTLS{
Enable: true,
Version: 3,
Users: []inbound.ShadowTLSUser{{Name: "test", Password: password}},
Handshake: inbound.ShadowTLSHandshakeOptions{Dest: net.JoinHostPort(realityDest, "443")},
},
}
outboundOptions := outbound.VmessOption{
TLS: true,
ServerName: realityDest,
Fingerprint: tlsFingerprint,
ShadowTLSOpts: outbound.ShadowTLSOptions{Password: password, Version: 3},
}
testInboundVMessUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundVMess_Restls(t *testing.T) {
const password = "restls-password"
inboundOptions := inbound.VmessOption{
ResTLS: inbound.ResTLS{
Enable: true,
Dest: net.JoinHostPort(realityDest, "443"),
Password: password,
},
}
outboundOptions := outbound.VmessOption{
TLS: true,
ServerName: realityDest,
Fingerprint: tlsFingerprint,
RestlsOpts: outbound.RestlsOptions{Password: password, VersionHint: "tls13"},
}
testInboundVMessUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundVMess_JLS(t *testing.T) {
const username = "jls-user"
const password = "jls-password"
inboundOptions := inbound.VmessOption{
JLSConfig: inbound.JLSConfig{
Enable: true,
Users: []inbound.JLSUser{{Username: username, Password: password}},
SNI: realityDest,
Dest: net.JoinHostPort(realityDest, "443"),
},
}
outboundOptions := outbound.VmessOption{
TLS: true,
ServerName: realityDest,
JLSOpts: outbound.JLSOptions{Username: username, Password: password},
}
testInboundVMessUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundVMess_Reality(t *testing.T) {
inboundOptions := inbound.VmessOption{
RealityConfig: inbound.RealityConfig{
+194
View File
@@ -0,0 +1,194 @@
package inner
import (
"errors"
"fmt"
"io"
"net"
"os"
"sync"
"sync/atomic"
"time"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/common/net/deadline"
"github.com/metacubex/mihomo/common/pool"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/socks5"
)
const innerUDPQueueSize = 128
var innerUDPConnID atomic.Uint64
type innerUDPAddr struct {
network string
address string
}
func (a innerUDPAddr) Network() string { return a.network }
func (a innerUDPAddr) String() string { return a.address }
type innerUDPDatagram struct {
data []byte
addr net.Addr
}
type innerUDPPacketConn struct {
tunnel C.Tunnel
proxy string
localAddr net.Addr
readChan chan innerUDPDatagram
done chan struct{}
closeOnce sync.Once
mu sync.Mutex
closed bool
readDeadline deadline.PipeDeadline
writeDeadline deadline.PipeDeadline
}
func HandleUdp(tunnel C.Tunnel, network, address, proxy string) (net.PacketConn, net.Addr, error) {
if tunnel == nil {
return nil, nil, fmt.Errorf("tunnel uninitialized")
}
switch network {
case "udp", "udp4", "udp6":
default:
return nil, nil, fmt.Errorf("unsupported network %s", network)
}
if socks5.ParseAddr(address) == nil {
return nil, nil, fmt.Errorf("invalid target address %s", address)
}
id := innerUDPConnID.Add(1)
conn := &innerUDPPacketConn{
tunnel: tunnel,
proxy: proxy,
localAddr: innerUDPAddr{network: network, address: fmt.Sprintf("inner-udp-%d", id)},
readChan: make(chan innerUDPDatagram, innerUDPQueueSize),
done: make(chan struct{}),
readDeadline: deadline.MakePipeDeadline(),
writeDeadline: deadline.MakePipeDeadline(),
}
return conn, innerUDPAddr{network: network, address: address}, nil
}
func (c *innerUDPPacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
select {
case <-c.done:
return 0, nil, net.ErrClosed
case <-c.readDeadline.Wait():
return 0, nil, os.ErrDeadlineExceeded
case datagram := <-c.readChan:
n := copy(p, datagram.data)
_ = pool.Put(datagram.data)
if n < len(datagram.data) {
return n, datagram.addr, io.ErrShortBuffer
}
return n, datagram.addr, nil
}
}
func (c *innerUDPPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) {
if addr == nil {
return 0, errors.New("missing target address")
}
select {
case <-c.done:
return 0, net.ErrClosed
case <-c.writeDeadline.Wait():
return 0, os.ErrDeadlineExceeded
default:
}
target := socks5.ParseAddr(addr.String())
if target == nil {
return 0, fmt.Errorf("invalid target address %s", addr)
}
data := pool.Get(len(p))
copy(data, p)
udpPacket := &innerUDPPacket{conn: c, data: data}
packet, metadata := inbound.NewPacket(target, udpPacket, C.INNER)
metadata.DNSMode = C.DNSNormal
metadata.Process = C.MihomoName
metadata.SpecialProxy = c.proxy
c.tunnel.HandleUDPPacket(packet, metadata)
return len(p), nil
}
func (c *innerUDPPacketConn) Close() error {
c.closeOnce.Do(func() {
c.mu.Lock()
c.closed = true
close(c.done)
for {
select {
case datagram := <-c.readChan:
_ = pool.Put(datagram.data)
default:
c.mu.Unlock()
return
}
}
})
return nil
}
func (c *innerUDPPacketConn) LocalAddr() net.Addr { return c.localAddr }
func (c *innerUDPPacketConn) SetDeadline(t time.Time) error {
c.readDeadline.Set(t)
c.writeDeadline.Set(t)
return nil
}
func (c *innerUDPPacketConn) SetReadDeadline(t time.Time) error {
c.readDeadline.Set(t)
return nil
}
func (c *innerUDPPacketConn) SetWriteDeadline(t time.Time) error {
c.writeDeadline.Set(t)
return nil
}
func (c *innerUDPPacketConn) writeBack(data []byte, addr net.Addr) (int, error) {
payload := pool.Get(len(data))
copy(payload, data)
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
_ = pool.Put(payload)
return 0, net.ErrClosed
}
select {
case c.readChan <- innerUDPDatagram{data: payload, addr: addr}:
default:
_ = pool.Put(payload)
}
return len(data), nil
}
type innerUDPPacket struct {
conn *innerUDPPacketConn
data []byte
}
func (p *innerUDPPacket) Data() []byte { return p.data }
func (p *innerUDPPacket) WriteBack(data []byte, addr net.Addr) (int, error) {
return p.conn.writeBack(data, addr)
}
func (p *innerUDPPacket) LocalAddr() net.Addr { return p.conn.localAddr }
func (p *innerUDPPacket) InAddr() net.Addr { return p.conn.localAddr }
func (p *innerUDPPacket) Drop() {
_ = pool.Put(p.data)
p.data = nil
}
var _ net.PacketConn = (*innerUDPPacketConn)(nil)
var _ C.UDPPacketInAddr = (*innerUDPPacket)(nil)
+47
View File
@@ -0,0 +1,47 @@
package jls
import (
"context"
"net"
N "github.com/metacubex/mihomo/common/net"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/inner"
"github.com/metacubex/mihomo/transport/jls"
)
type Builder struct {
config *jls.ServerConfig
}
func New(config LC.JLSConfig, tunnel C.Tunnel) (*Builder, error) {
users := make([]jls.User, len(config.Users))
for i, user := range config.Users {
users[i] = jls.User{Username: user.Username, Password: user.Password}
}
serverConfig, err := jls.NewServerConfig(
config.SNI,
config.Dest,
users,
config.ALPN,
config.RateLimit,
func(ctx context.Context, network, address string) (net.Conn, error) {
return inner.HandleTcp(tunnel, address, config.Proxy)
},
)
if err != nil {
return nil, err
}
return &Builder{config: serverConfig}, nil
}
func (b Builder) NewListener(listener net.Listener) net.Listener {
return N.NewHandleContextListener(context.Background(), listener, func(ctx context.Context, conn net.Conn) (net.Conn, error) {
return jls.Server(ctx, conn, b.config)
}, nil)
}
func UserFromConn(conn net.Conn) (string, bool) {
return jls.UserFromConn(conn)
}
+13
View File
@@ -134,6 +134,19 @@ func ParseListener(mapping map[string]any) (C.InboundListener, error) {
return nil, err
}
listener, err = IN.NewTuic(tuicOption)
case "shadowquic":
shadowQuicOption := &IN.ShadowQuicOption{
MaxIdleTime: 30000,
ALPN: []string{"h3"},
MaxDatagramFrameSize: 1400,
CongestionController: "bbr",
ZeroRTT: true,
}
err = decoder.Decode(mapping, shadowQuicOption)
if err != nil {
return nil, err
}
listener, err = IN.NewShadowQuic(shadowQuicOption)
case "anytls":
anytlsOption := &IN.AnyTLSOption{}
err = decoder.Decode(mapping, anytlsOption)
+39
View File
@@ -0,0 +1,39 @@
package restls
import (
"context"
"net"
"runtime/debug"
N "github.com/metacubex/mihomo/common/net"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/inner"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/transport/restls"
)
type Builder struct {
config *restls.ServerConfig
}
func New(config LC.ResTLS, tunnel C.Tunnel) *Builder {
return &Builder{config: &restls.ServerConfig{
ServerHostname: config.Dest,
Password: config.Password,
RestlsScript: config.RestlsScript,
MinRecordLen: config.MinRecordLen,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
return inner.HandleTcp(tunnel, address, config.Proxy)
},
}}
}
func (b Builder) NewListener(listener net.Listener) net.Listener {
return N.NewHandleContextListener(context.Background(), listener, func(ctx context.Context, conn net.Conn) (net.Conn, error) {
return restls.Server(ctx, conn, b.config)
}, func(a any) {
stack := debug.Stack()
log.Errorln("restls server panic: %s\n%s", a, stack)
})
}
+242
View File
@@ -0,0 +1,242 @@
package shadowquic
import (
"context"
"errors"
"net"
"net/netip"
"strings"
"time"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/common/sockopt"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/ca"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/inner"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/transport/shadowquic"
"github.com/metacubex/mihomo/transport/socks5"
"github.com/metacubex/mihomo/transport/tuic"
"github.com/metacubex/jls-quic-go"
"github.com/metacubex/jls-tls"
)
const ServerMaxIncomingStreams = (1 << 32) - 1
type Listener struct {
closed bool
config LC.ShadowQuicServer
udpListeners []net.PacketConn
servers []*shadowquic.Server
}
func New(config LC.ShadowQuicServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
if strings.TrimSpace(config.JLSUpstream.Addr) == "" {
return nil, errors.New("shadowquic: jls-upstream.addr is required")
}
if len(additions) == 0 {
additions = []inbound.Addition{
inbound.WithInName("DEFAULT-SHADOWQUIC"),
inbound.WithSpecialRules(""),
}
}
h, err := sing.NewListenerHandler(sing.ListenerConfig{
Tunnel: tunnel,
Type: C.SHADOWQUIC,
Additions: additions,
MuxOption: config.MuxOption,
})
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{
Time: ntp.Now,
MinVersion: tls.VersionTLS13,
}
// JLS authenticates the peer, so this generated certificate only carries the TLS handshake.
certificate, privateKey, _, err := ca.NewRandomTLSKeyPair(ca.KeyPairTypeP256)
if err != nil {
return nil, err
}
cert, err := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
if err != nil {
return nil, err
}
tlsConfig.Certificates = []tls.Certificate{cert}
if len(config.ALPN) > 0 {
tlsConfig.NextProtos = config.ALPN
} else {
tlsConfig.NextProtos = []string{"h3"}
}
users := make([]tls.JLSUser, 0, len(config.Users))
for _, user := range config.Users {
users = append(users, tls.JLSUser{
Username: user.Username,
Password: user.Password,
})
}
serverName := config.JLSUpstream.SNI
if serverName == "" {
serverName = defaultJLSServerName(config.JLSUpstream.Addr)
}
tlsConfig.JLSConfig = &tls.JLSConfig{
Enable: true,
Users: users,
ServerName: serverName,
}
if config.MaxIdleTime == 0 {
config.MaxIdleTime = 30000
}
if config.MaxDatagramFrameSize == 0 {
config.MaxDatagramFrameSize = 1400
}
if config.CWND == 0 {
config.CWND = 32
}
jlsPacketDialer := func(_ context.Context, network, address string) (net.PacketConn, net.Addr, error) {
return inner.HandleUdp(tunnel, network, address, config.JLSUpstream.Proxy)
}
quicVersions, versionNegotiationVersions, getVersionNegotiationProfile, err := shadowquic.ResolveQUICVersionProfile(
config.QUICVersions,
config.JLSUpstream.Addr,
config.JLSUpstream.QUICVersionProbe,
jlsPacketDialer,
log.Warnln,
)
if err != nil {
return nil, err
}
quicConfig := &quic.Config{
Versions: quicVersions,
JLSConfig: &quic.JLSConfig{
UpstreamAddr: config.JLSUpstream.Addr,
RateLimit: config.JLSUpstream.RateLimit,
PacketDialer: jlsPacketDialer,
VersionNegotiationVersions: versionNegotiationVersions,
GetVersionNegotiationProfile: getVersionNegotiationProfile,
},
MaxIdleTimeout: time.Duration(config.MaxIdleTime) * time.Millisecond,
MaxIncomingStreams: ServerMaxIncomingStreams,
MaxIncomingUniStreams: ServerMaxIncomingStreams,
InitialStreamReceiveWindow: uint64(config.ReceiveWindowConn),
MaxStreamReceiveWindow: uint64(config.ReceiveWindowConn),
InitialConnectionReceiveWindow: uint64(config.ReceiveWindow),
MaxConnectionReceiveWindow: uint64(config.ReceiveWindow),
MaxDatagramFrameSize: int64(config.MaxDatagramFrameSize),
EnableDatagrams: true,
Allow0RTT: config.ZeroRTT,
DisablePathMTUDiscovery: config.DisableMTUDiscovery,
}
if config.ReceiveWindowConn == 0 {
quicConfig.InitialStreamReceiveWindow = tuic.DefaultStreamReceiveWindow / 10
quicConfig.MaxStreamReceiveWindow = tuic.DefaultStreamReceiveWindow
}
if config.ReceiveWindow == 0 {
quicConfig.InitialConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow / 10
quicConfig.MaxConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow
}
handleTcpFn := func(conn net.Conn, addr socks5.Addr, _additions ...inbound.Addition) error {
go h.HandleSocket(addr, conn, _additions...)
return nil
}
handleUdpFn := func(addr socks5.Addr, packet C.UDPPacket, _additions ...inbound.Addition) error {
newAdditions := additions
if len(_additions) > 0 {
newAdditions = append(append([]inbound.Addition{}, additions...), _additions...)
}
tunnel.HandleUDPPacket(inbound.NewPacket(addr, packet, C.SHADOWQUIC, newAdditions...))
return nil
}
option := &shadowquic.ServerOption{
HandleTcpFn: handleTcpFn,
HandleUdpFn: handleUdpFn,
TLSConfig: tlsConfig,
QUICConfig: quicConfig,
CongestionController: config.CongestionController,
SendBPS: utils.StringToBps(config.Up),
ReceiveBPS: utils.StringToBps(config.Down),
IgnoreClientBandwidth: config.IgnoreClientBandwidth,
CWND: config.CWND,
BBRProfile: config.BBRProfile,
}
sl := &Listener{config: config}
for _, addr := range strings.Split(config.Listen, ",") {
addr = strings.TrimSpace(addr)
if addr == "" {
continue
}
ul, err := lc.ListenPacket(context.Background(), "udp", addr)
if err != nil {
return nil, err
}
if err := sockopt.UDPReuseaddr(ul); err != nil {
log.Warnln("Failed to Reuse UDP Address: %s", err)
}
sl.udpListeners = append(sl.udpListeners, ul)
server, err := shadowquic.NewServer(option, ul)
if err != nil {
return nil, err
}
sl.servers = append(sl.servers, server)
go func() {
err := server.Serve()
if err != nil && !sl.closed {
log.Warnln("ShadowQuic server closed: %s", err)
}
}()
}
return sl, nil
}
func defaultJLSServerName(upstreamAddr string) string {
host, _, err := net.SplitHostPort(upstreamAddr)
if err != nil {
host = upstreamAddr
}
if _, err := netip.ParseAddr(host); err == nil {
return ""
}
if strings.Contains(host, ":") {
return ""
}
return host
}
func (l *Listener) Close() error {
l.closed = true
var retErr error
for _, server := range l.servers {
if err := server.Close(); err != nil {
retErr = err
}
}
for _, lis := range l.udpListeners {
if err := lis.Close(); err != nil {
retErr = err
}
}
return retErr
}
func (l *Listener) Config() LC.ShadowQuicServer {
return l.config
}
func (l *Listener) AddrList() (addrList []net.Addr) {
for _, lis := range l.udpListeners {
addrList = append(addrList, lis.LocalAddr())
}
return
}
+47 -18
View File
@@ -10,9 +10,10 @@ import (
N "github.com/metacubex/mihomo/common/net"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/inner"
"github.com/metacubex/mihomo/listener/jls"
"github.com/metacubex/mihomo/listener/restls"
"github.com/metacubex/mihomo/listener/shadowtls"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowsocks/core"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
"github.com/metacubex/mihomo/transport/socks5"
@@ -25,7 +26,6 @@ type Listener struct {
udpListeners []*UDPListener
pickCipher core.Cipher
handler *sing.ListenerHandler
resTLS *restls.ServerConfig
simpleObfs func(net.Conn) net.Conn
}
@@ -50,15 +50,38 @@ func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel,
sl := &Listener{config: config, pickCipher: pickCipher, handler: h}
_listener = sl
securityModes := make([]string, 0, 3)
if config.ShadowTLS.Enable {
securityModes = append(securityModes, "shadow-tls")
}
if config.ResTLS.Enable {
sl.resTLS = &restls.ServerConfig{
ServerHostname: config.ResTLS.Dest,
Password: config.ResTLS.Password,
RestlsScript: config.ResTLS.RestlsScript,
MinRecordLen: config.ResTLS.MinRecordLen,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
return inner.HandleTcp(tunnel, address, config.ResTLS.Proxy)
},
securityModes = append(securityModes, "res-tls")
}
if config.JLSConfig.Enable {
securityModes = append(securityModes, "jls")
}
if len(securityModes) > 1 {
return nil, fmt.Errorf("security modes are mutually exclusive: %s", strings.Join(securityModes, ", "))
}
var shadowTLSBuilder *shadowtls.Builder
if config.ShadowTLS.Enable {
shadowTLSBuilder, err = shadowtls.New(config.ShadowTLS, tunnel)
if err != nil {
return nil, err
}
}
var restlsBuilder *restls.Builder
if config.ResTLS.Enable {
restlsBuilder = restls.New(config.ResTLS, tunnel)
}
var jlsBuilder *jls.Builder
if config.JLSConfig.Enable {
jlsBuilder, err = jls.New(config.JLSConfig, tunnel)
if err != nil {
return nil, err
}
}
@@ -90,6 +113,13 @@ func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel,
if err != nil {
return nil, err
}
if shadowTLSBuilder != nil {
l = shadowTLSBuilder.NewListener(l)
} else if restlsBuilder != nil {
l = restlsBuilder.NewListener(l)
} else if jlsBuilder != nil {
l = jlsBuilder.NewListener(l)
}
sl.listeners = append(sl.listeners, l)
go func() {
@@ -141,13 +171,12 @@ func (l *Listener) AddrList() (addrList []net.Addr) {
}
func (l *Listener) HandleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
if l.resTLS != nil {
c, err := restls.Server(context.TODO(), conn, l.resTLS)
if err != nil {
_ = conn.Close()
return
}
conn = c
user, loaded := shadowtls.UserFromConn(conn)
if jlsUser, jlsLoaded := jls.UserFromConn(conn); jlsLoaded {
user, loaded = jlsUser, true
}
if loaded {
additions = append(append([]inbound.Addition(nil), additions...), inbound.WithInUser(user))
}
if l.simpleObfs != nil {
conn = l.simpleObfs(conn)
+75
View File
@@ -0,0 +1,75 @@
package shadowtls
import (
"context"
"net"
"runtime/debug"
N "github.com/metacubex/mihomo/common/net"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/inner"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/transport/shadowtls"
)
type Builder struct {
config *shadowtls.ServerConfig
}
func New(config LC.ShadowTLS, tunnel C.Tunnel) (*Builder, error) {
buildHandshake := func(handshake LC.ShadowTLSHandshakeOptions) shadowtls.HandshakeConfig {
return shadowtls.HandshakeConfig{
Server: handshake.Dest,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
return inner.HandleTcp(tunnel, address, handshake.Proxy)
},
}
}
var handshakeForServerName map[string]shadowtls.HandshakeConfig
if config.Version > 1 {
handshakeForServerName = make(map[string]shadowtls.HandshakeConfig, len(config.HandshakeForServerName))
for serverName, serverOptions := range config.HandshakeForServerName {
handshakeForServerName[serverName] = buildHandshake(serverOptions)
}
}
users := make([]shadowtls.User, len(config.Users))
for i, user := range config.Users {
users[i] = shadowtls.User{Name: user.Name, Password: user.Password}
}
var wildcardSNI shadowtls.WildcardSNI
switch config.WildcardSNI {
case "authed":
wildcardSNI = shadowtls.WildcardSNIAuthed
case "all":
wildcardSNI = shadowtls.WildcardSNIAll
default:
wildcardSNI = shadowtls.WildcardSNIOff
}
serverConfig, err := shadowtls.NewServerConfig(
config.Version,
config.Password,
users,
buildHandshake(config.Handshake),
handshakeForServerName,
config.StrictMode,
wildcardSNI,
)
if err != nil {
return nil, err
}
return &Builder{config: serverConfig}, nil
}
func (b Builder) NewListener(listener net.Listener) net.Listener {
return N.NewHandleContextListener(context.Background(), listener, func(ctx context.Context, conn net.Conn) (net.Conn, error) {
return shadowtls.Server(ctx, conn, b.config)
}, func(a any) {
stack := debug.Stack()
log.Errorln("shadowtls server panic: %s\n%s", a, stack)
})
}
func UserFromConn(conn net.Conn) (string, bool) {
return shadowtls.UserFromConn(conn)
}
+4 -3
View File
@@ -163,9 +163,10 @@ func New(config LC.Hysteria2Server, lc C.InboundListenConfig, tunnel C.Tunnel, a
InsecureSkipVerify: config.RealmOpts.SkipCertVerify,
NextProtos: config.RealmOpts.ALPN,
},
Fingerprint: config.RealmOpts.Fingerprint,
Certificate: config.RealmOpts.Certificate,
PrivateKey: config.RealmOpts.PrivateKey,
Fingerprint: config.RealmOpts.Fingerprint,
NameCertVerify: config.RealmOpts.NameCertVerify,
Certificate: config.RealmOpts.Certificate,
PrivateKey: config.RealmOpts.PrivateKey,
})
if err != nil {
return nil, err
+43 -73
View File
@@ -10,20 +10,21 @@ import (
"github.com/metacubex/mihomo/common/sockopt"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/inner"
"github.com/metacubex/mihomo/listener/jls"
"github.com/metacubex/mihomo/listener/restls"
embedSS "github.com/metacubex/mihomo/listener/shadowsocks"
"github.com/metacubex/mihomo/listener/shadowtls"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/transport/kcptun"
"github.com/metacubex/mihomo/transport/restls"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
shadowsocks "github.com/metacubex/sing-shadowsocks"
"github.com/metacubex/sing-shadowsocks/shadowaead"
"github.com/metacubex/sing-shadowsocks/shadowaead_2022"
shadowtls "github.com/metacubex/sing-shadowtls"
"github.com/metacubex/sing/common"
"github.com/metacubex/sing/common/auth"
"github.com/metacubex/sing/common/buf"
"github.com/metacubex/sing/common/bufio"
M "github.com/metacubex/sing/common/metadata"
@@ -36,26 +37,11 @@ type Listener struct {
listeners []net.Listener
udpListeners []net.PacketConn
service shadowsocks.Service
shadowTLS *shadowtls.Service
resTLS *restls.ServerConfig
simpleObfs func(net.Conn) net.Conn
}
var _listener *Listener
// shadowTLSService is a wrapper for shadowsocks.Service to support shadowTLS.
type shadowTLSService struct {
shadowsocks.Service
shadowTLS *shadowtls.Service
}
func (s *shadowTLSService) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
if s.shadowTLS != nil {
return s.shadowTLS.NewConnection(ctx, conn, metadata)
}
return s.Service.NewConnection(ctx, conn, metadata)
}
func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (C.MultiAddrListener, error) {
var sl *Listener
var err error
@@ -99,60 +85,38 @@ func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel,
return nil, err
}
securityModes := make([]string, 0, 3)
if config.ShadowTLS.Enable {
buildHandshake := func(handshake LC.ShadowTLSHandshakeOptions) (handshakeConfig shadowtls.HandshakeConfig) {
handshakeConfig.Server = M.ParseSocksaddr(handshake.Dest)
handshakeConfig.Dialer = sing.NewDialer(tunnel, handshake.Proxy)
return
}
var handshakeForServerName map[string]shadowtls.HandshakeConfig
if config.ShadowTLS.Version > 1 {
handshakeForServerName = make(map[string]shadowtls.HandshakeConfig)
for serverName, serverOptions := range config.ShadowTLS.HandshakeForServerName {
handshakeForServerName[serverName] = buildHandshake(serverOptions)
}
}
var wildcardSNI shadowtls.WildcardSNI
switch config.ShadowTLS.WildcardSNI {
case "authed":
wildcardSNI = shadowtls.WildcardSNIAuthed
case "all":
wildcardSNI = shadowtls.WildcardSNIAll
default:
wildcardSNI = shadowtls.WildcardSNIOff
}
var shadowTLS *shadowtls.Service
shadowTLS, err = shadowtls.NewService(shadowtls.ServiceConfig{
Version: config.ShadowTLS.Version,
Password: config.ShadowTLS.Password,
Users: common.Map(config.ShadowTLS.Users, func(it LC.ShadowTLSUser) shadowtls.User {
return shadowtls.User{Name: it.Name, Password: it.Password}
}),
Handshake: buildHandshake(config.ShadowTLS.Handshake),
HandshakeForServerName: handshakeForServerName,
StrictMode: config.ShadowTLS.StrictMode,
WildcardSNI: wildcardSNI,
Handler: sl.service,
Logger: log.SingLogger,
})
securityModes = append(securityModes, "shadow-tls")
}
if config.ResTLS.Enable {
securityModes = append(securityModes, "res-tls")
}
if config.JLSConfig.Enable {
securityModes = append(securityModes, "jls")
}
if len(securityModes) > 1 {
return nil, fmt.Errorf("security modes are mutually exclusive: %s", strings.Join(securityModes, ", "))
}
var shadowTLSBuilder *shadowtls.Builder
if config.ShadowTLS.Enable {
shadowTLSBuilder, err = shadowtls.New(config.ShadowTLS, tunnel)
if err != nil {
return nil, err
}
sl.service = &shadowTLSService{
Service: sl.service,
shadowTLS: shadowTLS,
}
}
var restlsBuilder *restls.Builder
if config.ResTLS.Enable {
sl.resTLS = &restls.ServerConfig{
ServerHostname: config.ResTLS.Dest,
Password: config.ResTLS.Password,
RestlsScript: config.ResTLS.RestlsScript,
MinRecordLen: config.ResTLS.MinRecordLen,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
return inner.HandleTcp(tunnel, address, config.ResTLS.Proxy)
},
restlsBuilder = restls.New(config.ResTLS, tunnel)
}
var jlsBuilder *jls.Builder
if config.JLSConfig.Enable {
jlsBuilder, err = jls.New(config.JLSConfig, tunnel)
if err != nil {
return nil, err
}
}
@@ -242,6 +206,13 @@ func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel,
if err != nil {
return nil, err
}
if shadowTLSBuilder != nil {
l = shadowTLSBuilder.NewListener(l)
} else if restlsBuilder != nil {
l = restlsBuilder.NewListener(l)
} else if jlsBuilder != nil {
l = jlsBuilder.NewListener(l)
}
sl.listeners = append(sl.listeners, l)
go func() {
@@ -295,18 +266,17 @@ func (l *Listener) AddrList() (addrList []net.Addr) {
}
func (l *Listener) HandleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
ctx := sing.WithAdditions(context.TODO(), additions...)
if l.resTLS != nil {
c, err := restls.Server(context.TODO(), conn, l.resTLS)
if err != nil {
_ = conn.Close()
return
}
conn = c
user, loaded := shadowtls.UserFromConn(conn)
if jlsUser, jlsLoaded := jls.UserFromConn(conn); jlsLoaded {
user, loaded = jlsUser, true
}
if l.simpleObfs != nil {
conn = l.simpleObfs(conn)
}
ctx := sing.WithAdditions(context.TODO(), additions...)
if loaded {
ctx = auth.ContextWithUser(ctx, user)
}
err := l.service.NewConnection(ctx, conn, M.Metadata{
Protocol: "shadowsocks",
Source: M.SocksaddrFromNet(conn.RemoteAddr()),
+51 -8
View File
@@ -12,7 +12,10 @@ import (
"github.com/metacubex/mihomo/component/ech"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/jls"
"github.com/metacubex/mihomo/listener/reality"
"github.com/metacubex/mihomo/listener/restls"
"github.com/metacubex/mihomo/listener/shadowtls"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/transport/gun"
@@ -84,6 +87,9 @@ func New(config LC.VlessServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
Protocols: new(http.Protocols),
}
tlsConfig := &tls.Config{Time: ntp.Now}
var shadowTLSBuilder *shadowtls.Builder
var restlsBuilder *restls.Builder
var jlsBuilder *jls.Builder
var realityBuilder *reality.Builder
if config.Certificate != "" && config.PrivateKey != "" {
@@ -115,18 +121,49 @@ func New(config LC.VlessServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
}
tlsConfig.ClientCAs = pool
}
if tlsConfig.ClientAuth != tls.NoClientCert && tlsConfig.GetCertificate == nil {
return nil, errors.New("client-auth requires certificate")
}
securityModes := make([]string, 0, 5)
if tlsConfig.GetCertificate != nil {
securityModes = append(securityModes, "certificate")
}
if config.RealityConfig.PrivateKey != "" {
securityModes = append(securityModes, "reality")
}
if config.ShadowTLS.Enable {
securityModes = append(securityModes, "shadow-tls")
}
if config.ResTLS.Enable {
securityModes = append(securityModes, "res-tls")
}
if config.JLSConfig.Enable {
securityModes = append(securityModes, "jls")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
if config.RealityConfig.PrivateKey != "" {
if tlsConfig.GetCertificate != nil {
return nil, errors.New("certificate is unavailable in reality")
}
if tlsConfig.ClientAuth != tls.NoClientCert {
return nil, errors.New("client-auth is unavailable in reality")
}
realityBuilder, err = config.RealityConfig.Build(tunnel)
if err != nil {
return nil, err
}
}
if config.ShadowTLS.Enable {
shadowTLSBuilder, err = shadowtls.New(config.ShadowTLS, tunnel)
if err != nil {
return nil, err
}
}
if config.ResTLS.Enable {
restlsBuilder = restls.New(config.ResTLS, tunnel)
}
if config.JLSConfig.Enable {
jlsBuilder, err = jls.New(config.JLSConfig, tunnel)
if err != nil {
return nil, err
}
}
if config.WsPath != "" {
httpMux := http.NewServeMux()
httpMux.HandleFunc(config.WsPath, func(w http.ResponseWriter, r *http.Request) {
@@ -225,12 +262,18 @@ func New(config LC.VlessServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
if err != nil {
return nil, err
}
if realityBuilder != nil {
if shadowTLSBuilder != nil {
l = shadowTLSBuilder.NewListener(l)
} else if restlsBuilder != nil {
l = restlsBuilder.NewListener(l)
} else if jlsBuilder != nil {
l = jlsBuilder.NewListener(l)
} else if realityBuilder != nil {
l = realityBuilder.NewListener(l)
} else if tlsConfig.GetCertificate != nil {
l = tls.NewListener(l, tlsConfig)
} else if sl.decryption == nil && !config.AllowInsecure {
return nil, errors.New("disallow using Vless without any certificates/reality/decryption/allow-insecure config")
return nil, errors.New("disallow using Vless without any certificates/shadow-tls/res-tls/jls/reality/decryption/allow-insecure config")
}
sl.listeners = append(sl.listeners, l)
+60 -7
View File
@@ -12,7 +12,10 @@ import (
"github.com/metacubex/mihomo/component/ech"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/jls"
"github.com/metacubex/mihomo/listener/reality"
"github.com/metacubex/mihomo/listener/restls"
"github.com/metacubex/mihomo/listener/shadowtls"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/listener/tlsmirror"
"github.com/metacubex/mihomo/ntp"
@@ -94,6 +97,9 @@ func New(config LC.VmessServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
Protocols: new(http.Protocols),
}
tlsConfig := &tls.Config{Time: ntp.Now}
var shadowTLSBuilder *shadowtls.Builder
var restlsBuilder *restls.Builder
var jlsBuilder *jls.Builder
var realityBuilder *reality.Builder
var tlsMirrorBuilder *tlsmirror.Builder
@@ -126,13 +132,39 @@ func New(config LC.VmessServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
}
tlsConfig.ClientCAs = pool
}
if tlsConfig.ClientAuth != tls.NoClientCert && tlsConfig.GetCertificate == nil {
return nil, errors.New("client-auth requires certificate")
}
securityModes := make([]string, 0, 6)
if tlsConfig.GetCertificate != nil {
securityModes = append(securityModes, "certificate")
}
if config.RealityConfig.PrivateKey != "" {
securityModes = append(securityModes, "reality")
}
if config.TLSMirrorConfig.PrimaryKey != "" {
securityModes = append(securityModes, "tlsmirror")
}
tcpOnlySecurityMode := ""
if config.ShadowTLS.Enable {
securityModes = append(securityModes, "shadow-tls")
tcpOnlySecurityMode = "ShadowTLS"
}
if config.ResTLS.Enable {
securityModes = append(securityModes, "res-tls")
tcpOnlySecurityMode = "Restls"
}
if config.JLSConfig.Enable {
securityModes = append(securityModes, "jls")
tcpOnlySecurityMode = "JLS"
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
if config.MKCPConfig.Enable && tcpOnlySecurityMode != "" {
return nil, errors.New(tcpOnlySecurityMode + " only supports TCP transports")
}
if config.RealityConfig.PrivateKey != "" {
if tlsConfig.GetCertificate != nil {
return nil, errors.New("certificate is unavailable in reality")
}
if tlsConfig.ClientAuth != tls.NoClientCert {
return nil, errors.New("client-auth is unavailable in reality")
}
realityBuilder, err = config.RealityConfig.Build(tunnel)
if err != nil {
return nil, err
@@ -151,6 +183,21 @@ func New(config LC.VmessServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
}.Build(tunnel)
h.Tunnel = tlsMirrorBuilder.WrapTunnel(tunnel)
}
if config.ShadowTLS.Enable {
shadowTLSBuilder, err = shadowtls.New(config.ShadowTLS, tunnel)
if err != nil {
return nil, err
}
}
if config.ResTLS.Enable {
restlsBuilder = restls.New(config.ResTLS, tunnel)
}
if config.JLSConfig.Enable {
jlsBuilder, err = jls.New(config.JLSConfig, tunnel)
if err != nil {
return nil, err
}
}
if config.WsPath != "" {
httpMux := http.NewServeMux()
httpMux.HandleFunc(config.WsPath, func(w http.ResponseWriter, r *http.Request) {
@@ -214,7 +261,13 @@ func New(config LC.VmessServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
return nil, err
}
}
if tlsMirrorBuilder != nil {
if shadowTLSBuilder != nil {
l = shadowTLSBuilder.NewListener(l)
} else if restlsBuilder != nil {
l = restlsBuilder.NewListener(l)
} else if jlsBuilder != nil {
l = jlsBuilder.NewListener(l)
} else if tlsMirrorBuilder != nil {
l = tlsMirrorBuilder.NewListener(l)
} else if realityBuilder != nil {
l = realityBuilder.NewListener(l)
+44 -57
View File
@@ -17,15 +17,12 @@ import (
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/listener/jls"
"github.com/metacubex/mihomo/listener/restls"
"github.com/metacubex/mihomo/listener/shadowtls"
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
"github.com/metacubex/mihomo/transport/snell"
shadowtls "github.com/metacubex/sing-shadowtls"
"github.com/metacubex/sing/common"
M "github.com/metacubex/sing/common/metadata"
)
const maxPacketLength = 0x3fff
@@ -34,7 +31,6 @@ type Listener struct {
closed bool
config LC.SnellServer
listeners []net.Listener
shadowTLS *shadowtls.Service
}
func New(config LC.SnellServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (C.MultiAddrListener, error) {
@@ -57,46 +53,36 @@ func New(config LC.SnellServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
l := &Listener{config: config}
securityModes := make([]string, 0, 3)
if config.ShadowTLS.Enable {
securityModes = append(securityModes, "shadow-tls")
}
if config.ResTLS.Enable {
securityModes = append(securityModes, "res-tls")
}
if config.JLSConfig.Enable {
securityModes = append(securityModes, "jls")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
var shadowTLSBuilder *shadowtls.Builder
if config.ShadowTLS.Enable {
buildHandshake := func(handshake LC.ShadowTLSHandshakeOptions) (handshakeConfig shadowtls.HandshakeConfig) {
handshakeConfig.Server = M.ParseSocksaddr(handshake.Dest)
handshakeConfig.Dialer = sing.NewDialer(tunnel, handshake.Proxy)
return
}
var handshakeForServerName map[string]shadowtls.HandshakeConfig
if config.ShadowTLS.Version > 1 {
handshakeForServerName = make(map[string]shadowtls.HandshakeConfig)
for serverName, serverOptions := range config.ShadowTLS.HandshakeForServerName {
handshakeForServerName[serverName] = buildHandshake(serverOptions)
}
}
var wildcardSNI shadowtls.WildcardSNI
switch config.ShadowTLS.WildcardSNI {
case "authed":
wildcardSNI = shadowtls.WildcardSNIAuthed
case "all":
wildcardSNI = shadowtls.WildcardSNIAll
default:
wildcardSNI = shadowtls.WildcardSNIOff
}
var err error
l.shadowTLS, err = shadowtls.NewService(shadowtls.ServiceConfig{
Version: config.ShadowTLS.Version,
Password: config.ShadowTLS.Password,
Users: common.Map(config.ShadowTLS.Users, func(it LC.ShadowTLSUser) shadowtls.User {
return shadowtls.User{Name: it.Name, Password: it.Password}
}),
Handshake: buildHandshake(config.ShadowTLS.Handshake),
HandshakeForServerName: handshakeForServerName,
StrictMode: config.ShadowTLS.StrictMode,
WildcardSNI: wildcardSNI,
Handler: sing.FnHandler{
NewConnectionFn: func(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
l.handleConn(conn, tunnel, sing.AdditionsFromContext(ctx)...)
return nil
}},
Logger: log.SingLogger,
})
shadowTLSBuilder, err = shadowtls.New(config.ShadowTLS, tunnel)
if err != nil {
return nil, err
}
}
var restlsBuilder *restls.Builder
if config.ResTLS.Enable {
restlsBuilder = restls.New(config.ResTLS, tunnel)
}
var jlsBuilder *jls.Builder
if config.JLSConfig.Enable {
var err error
jlsBuilder, err = jls.New(config.JLSConfig, tunnel)
if err != nil {
return nil, err
}
@@ -111,6 +97,13 @@ func New(config LC.SnellServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
_ = l.Close()
return nil, err
}
if shadowTLSBuilder != nil {
ln = shadowTLSBuilder.NewListener(ln)
} else if restlsBuilder != nil {
ln = restlsBuilder.NewListener(ln)
} else if jlsBuilder != nil {
ln = jlsBuilder.NewListener(ln)
}
l.listeners = append(l.listeners, ln)
go func(ln net.Listener) {
for {
@@ -152,19 +145,13 @@ func (l *Listener) AddrList() (addrList []net.Addr) {
func (l *Listener) HandleConn(rawConn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
defer rawConn.Close()
conn := rawConn
if l.shadowTLS != nil {
ctx := sing.WithAdditions(context.TODO(), additions...)
_ = l.shadowTLS.NewConnection(ctx, conn, M.Metadata{
Protocol: "snell",
Source: M.SocksaddrFromNet(conn.RemoteAddr()),
})
return
user, loaded := shadowtls.UserFromConn(rawConn)
if jlsUser, jlsLoaded := jls.UserFromConn(rawConn); jlsLoaded {
user, loaded = jlsUser, true
}
if loaded {
additions = append(append([]inbound.Addition(nil), additions...), inbound.WithInUser(user))
}
l.handleConn(rawConn, tunnel, additions...)
}
func (l *Listener) handleConn(rawConn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
conn := rawConn
switch l.config.ObfsMode {
case "http":
+7
View File
@@ -112,6 +112,7 @@ func (l *Listener) handleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbou
closeConns()
return
}
cConn = wrapSessionConn(cConn)
session, err := sudoku.ReadServerSession(cConn, meta)
if err != nil {
@@ -158,6 +159,12 @@ func (l *Listener) handleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbou
}
}
func wrapSessionConn(conn net.Conn) net.Conn {
// Sudoku uses framed reads. Keep mihomo's asynchronous peek deadlines from
// interrupting a partially consumed frame and desynchronizing the session.
return N.NewDeadlineConn(conn)
}
func (l *Listener) handleUoTSession(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
writer := sudoku.NewUoTPacketConn(conn)
remoteAddr := conn.RemoteAddr()
+51 -8
View File
@@ -15,7 +15,10 @@ import (
"github.com/metacubex/mihomo/component/ech"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/jls"
"github.com/metacubex/mihomo/listener/reality"
"github.com/metacubex/mihomo/listener/restls"
"github.com/metacubex/mihomo/listener/shadowtls"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/transport/gun"
@@ -80,6 +83,9 @@ func New(config LC.TrojanServer, lc C.InboundListenConfig, tunnel C.Tunnel, addi
Protocols: new(http.Protocols),
}
tlsConfig := &tls.Config{Time: ntp.Now}
var shadowTLSBuilder *shadowtls.Builder
var restlsBuilder *restls.Builder
var jlsBuilder *jls.Builder
var realityBuilder *reality.Builder
if config.Certificate != "" && config.PrivateKey != "" {
@@ -111,18 +117,49 @@ func New(config LC.TrojanServer, lc C.InboundListenConfig, tunnel C.Tunnel, addi
}
tlsConfig.ClientCAs = pool
}
if tlsConfig.ClientAuth != tls.NoClientCert && tlsConfig.GetCertificate == nil {
return nil, errors.New("client-auth requires certificate")
}
securityModes := make([]string, 0, 5)
if tlsConfig.GetCertificate != nil {
securityModes = append(securityModes, "certificate")
}
if config.RealityConfig.PrivateKey != "" {
securityModes = append(securityModes, "reality")
}
if config.ShadowTLS.Enable {
securityModes = append(securityModes, "shadow-tls")
}
if config.ResTLS.Enable {
securityModes = append(securityModes, "res-tls")
}
if config.JLSConfig.Enable {
securityModes = append(securityModes, "jls")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
if config.RealityConfig.PrivateKey != "" {
if tlsConfig.GetCertificate != nil {
return nil, errors.New("certificate is unavailable in reality")
}
if tlsConfig.ClientAuth != tls.NoClientCert {
return nil, errors.New("client-auth is unavailable in reality")
}
realityBuilder, err = config.RealityConfig.Build(tunnel)
if err != nil {
return nil, err
}
}
if config.ShadowTLS.Enable {
shadowTLSBuilder, err = shadowtls.New(config.ShadowTLS, tunnel)
if err != nil {
return nil, err
}
}
if config.ResTLS.Enable {
restlsBuilder = restls.New(config.ResTLS, tunnel)
}
if config.JLSConfig.Enable {
jlsBuilder, err = jls.New(config.JLSConfig, tunnel)
if err != nil {
return nil, err
}
}
if config.WsPath != "" {
httpMux := http.NewServeMux()
httpMux.HandleFunc(config.WsPath, func(w http.ResponseWriter, r *http.Request) {
@@ -165,12 +202,18 @@ func New(config LC.TrojanServer, lc C.InboundListenConfig, tunnel C.Tunnel, addi
if err != nil {
return nil, err
}
if realityBuilder != nil {
if shadowTLSBuilder != nil {
l = shadowTLSBuilder.NewListener(l)
} else if restlsBuilder != nil {
l = restlsBuilder.NewListener(l)
} else if jlsBuilder != nil {
l = jlsBuilder.NewListener(l)
} else if realityBuilder != nil {
l = realityBuilder.NewListener(l)
} else if tlsConfig.GetCertificate != nil {
l = tls.NewListener(l, tlsConfig)
} else if !config.TrojanSSOption.Enabled && !config.AllowInsecure {
return nil, errors.New("disallow using Trojan without both certificates/reality/ss/allow-insecure config")
return nil, errors.New("disallow using Trojan without any certificates/shadow-tls/res-tls/jls/reality/ss/allow-insecure config")
}
sl.listeners = append(sl.listeners, l)
+1 -1
View File
@@ -18,7 +18,7 @@ func (dw *DomainWildcard) RuleType() C.RuleType {
}
func (dw *DomainWildcard) Match(metadata *C.Metadata, _ C.RuleMatchHelper) (bool, string) {
return wildcard.Match(dw.pattern, metadata.Host), dw.adapter
return wildcard.Match(dw.pattern, metadata.RuleHost()), dw.adapter
}
func (dw *DomainWildcard) Adapter() string {
+1 -1
View File
@@ -47,7 +47,7 @@ func (is *IPSuffix) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool,
}
}
if (is.ipBytes[size-bits/8-1] << (8 - bits%8)) != (mIPBytes[size-bits/8-1] << (8 - bits%8)) {
if bits%8 != 0 && (is.ipBytes[size-bits/8-1] << (8 - bits%8)) != (mIPBytes[size-bits/8-1] << (8 - bits%8)) {
return false, ""
}
+2 -1
View File
@@ -22,6 +22,7 @@ type ClientConfig struct {
IdleSessionCheckInterval time.Duration
IdleSessionTimeout time.Duration
MinIdleSession int
DisableReuse bool
Server M.Socksaddr
Dialer N.Dialer
TLSConfig *vmess.TLSConfig
@@ -46,7 +47,7 @@ func NewClient(ctx context.Context, config ClientConfig) *Client {
}
// Initialize the padding state of this client
padding.UpdatePaddingScheme(padding.DefaultPaddingScheme, &c.padding)
c.sessionClient = session.NewClient(ctx, c.createOutboundTLSConnection, &c.padding, config.IdleSessionCheckInterval, config.IdleSessionTimeout, config.MinIdleSession)
c.sessionClient = session.NewClient(ctx, c.createOutboundTLSConnection, &c.padding, config.IdleSessionCheckInterval, config.IdleSessionTimeout, config.MinIdleSession, config.DisableReuse)
return c
}
+20 -7
View File
@@ -33,15 +33,17 @@ type Client struct {
idleSessionTimeout time.Duration
minIdleSession int
disableReuse bool
}
func NewClient(ctx context.Context, dialOut util.DialOutFunc, _padding *atomic.Pointer[padding.PaddingFactory], idleSessionCheckInterval, idleSessionTimeout time.Duration, minIdleSession int) *Client {
func NewClient(ctx context.Context, dialOut util.DialOutFunc, _padding *atomic.Pointer[padding.PaddingFactory], idleSessionCheckInterval, idleSessionTimeout time.Duration, minIdleSession int, disableReuse bool) *Client {
c := &Client{
sessions: make(map[uint64]*Session),
dialOut: dialOut,
padding: _padding,
idleSessionTimeout: idleSessionTimeout,
minIdleSession: minIdleSession,
disableReuse: disableReuse,
}
if idleSessionCheckInterval <= time.Second*5 {
idleSessionCheckInterval = time.Second * 30
@@ -51,7 +53,9 @@ func NewClient(ctx context.Context, dialOut util.DialOutFunc, _padding *atomic.P
}
c.die, c.dieCancel = context.WithCancel(ctx)
c.idleSession = skiplist.NewSkipList[uint64, *Session]()
util.StartRoutine(c.die, idleSessionCheckInterval, c.idleCleanup)
if !c.disableReuse {
util.StartRoutine(c.die, idleSessionCheckInterval, c.idleCleanup)
}
return c
}
@@ -66,7 +70,9 @@ func (c *Client) CreateStream(ctx context.Context) (net.Conn, error) {
var stream *Stream
var err error
session = c.getIdleSession()
if !c.disableReuse {
session = c.getIdleSession()
}
if session == nil {
session, err = c.createSession(ctx)
}
@@ -82,10 +88,15 @@ func (c *Client) CreateStream(ctx context.Context) (net.Conn, error) {
stream.dieHook = func() {
// If Session is not closed, put this Stream to pool
if !session.IsClosed() {
if c.disableReuse {
session.Close()
return
}
select {
case <-c.die.Done():
// Now client has been closed
go session.Close()
session.Close()
default:
c.idleSessionLock.Lock()
session.idleSince = time.Now()
@@ -118,9 +129,11 @@ func (c *Client) createSession(ctx context.Context) (*Session, error) {
session := NewClientSession(underlying, c.padding)
session.seq = c.sessionCounter.Add(1)
session.dieHook = func() {
c.idleSessionLock.Lock()
c.idleSession.Remove(math.MaxUint64 - session.seq)
c.idleSessionLock.Unlock()
if !c.disableReuse {
c.idleSessionLock.Lock()
c.idleSession.Remove(math.MaxUint64 - session.seq)
c.idleSessionLock.Unlock()
}
c.sessionsLock.Lock()
delete(c.sessions, session.seq)
+43 -10
View File
@@ -109,6 +109,7 @@ func (s *Session) IsClosed() bool {
func (s *Session) Close() error {
var once bool
s.dieOnce.Do(func() {
_ = s.conn.SetDeadline(time.Now())
close(s.die)
once = true
})
@@ -368,20 +369,52 @@ func (s *Session) streamClosed(sid uint32) error {
return err
}
// maxFrameDataLen is the maximum payload bytes per data frame. The wire
// format encodes payload length as a uint16, so a single frame cannot
// carry more than 65535 bytes. writeDataFrame splits larger writes into
// multiple frames and sends the whole frame sequence in one writeConn call.
// That keeps one Stream.Write contiguous relative to other stream/control
// frame writes.
const maxFrameDataLen = 0xFFFF
func (s *Session) writeDataFrame(sid uint32, data []byte) (int, error) {
dataLen := len(data)
buffer := buf.NewSize(dataLen + headerOverHeadSize)
buffer.WriteByte(cmdPSH)
binary.BigEndian.PutUint32(buffer.Extend(4), sid)
binary.BigEndian.PutUint16(buffer.Extend(2), uint16(dataLen))
buffer.Write(data)
_, err := s.writeConn(buffer.Bytes())
buffer.Release()
if err != nil {
return 0, err
if dataLen == 0 {
return 0, nil
}
if dataLen <= maxFrameDataLen {
buffer := buf.NewSize(dataLen + headerOverHeadSize)
buffer.WriteByte(cmdPSH)
binary.BigEndian.PutUint32(buffer.Extend(4), sid)
binary.BigEndian.PutUint16(buffer.Extend(2), uint16(dataLen))
buffer.Write(data)
_, err := s.writeConn(buffer.Bytes())
buffer.Release()
if err != nil {
return 0, err
}
return dataLen, nil
}
frameCount := (dataLen + maxFrameDataLen - 1) / maxFrameDataLen
buffer := buf.NewSize(dataLen + frameCount*headerOverHeadSize)
defer buffer.Release()
for written := 0; written < dataLen; {
chunk := dataLen - written
if chunk > maxFrameDataLen {
chunk = maxFrameDataLen
}
buffer.WriteByte(cmdPSH)
binary.BigEndian.PutUint32(buffer.Extend(4), sid)
binary.BigEndian.PutUint16(buffer.Extend(2), uint16(chunk))
buffer.Write(data[written : written+chunk])
written += chunk
}
if _, err := s.writeConn(buffer.Bytes()); err != nil {
return 0, err
}
return dataLen, nil
}
+2 -1
View File
@@ -89,11 +89,12 @@ func (s *Stream) closeWithError(err error) error {
once = true
})
if once {
err := s.sess.streamClosed(s.id)
if s.dieHook != nil {
s.dieHook()
s.dieHook = nil
}
return s.sess.streamClosed(s.id)
return err
} else {
return s.dieErr
}
+6 -18
View File
@@ -58,6 +58,7 @@ type RelayOption struct {
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -175,6 +176,7 @@ func (d *relayDialer) dialRelayServer(ctx context.Context, fallbackAddress strin
tlsConn, err := mihomoVMess.StreamTLSConn(ctx, conn, &mihomoVMess.TLSConfig{
Host: d.serverName(relayAddress),
SkipCertVerify: d.option.SkipCertVerify,
NameCertVerify: d.option.NameCertVerify,
FingerPrint: d.option.Fingerprint,
Certificate: d.option.Certificate,
PrivateKey: d.option.PrivateKey,
@@ -271,11 +273,11 @@ func writeRelayRequest(w io.Writer, command byte, address string, network uint16
byte(payloadLen >> 8),
byte(payloadLen),
}
if err := writeFull(w, header); err != nil {
if _, err := w.Write(header); err != nil {
return err
}
for _, feature := range features {
if err := writeFull(w, feature); err != nil {
if _, err := w.Write(feature); err != nil {
return err
}
}
@@ -320,10 +322,10 @@ func (c *relayPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) {
var header [2]byte
binary.BigEndian.PutUint16(header[:], uint16(len(p)))
if err := writeFull(c.conn, header[:]); err != nil {
if _, err := c.conn.Write(header[:]); err != nil {
return 0, err
}
if err := writeFull(c.conn, p); err != nil {
if _, err := c.conn.Write(p); err != nil {
return 0, err
}
return len(p), nil
@@ -349,20 +351,6 @@ func (c *relayPacketConn) SetWriteDeadline(t time.Time) error {
return c.conn.SetWriteDeadline(t)
}
func writeFull(w io.Writer, p []byte) error {
for len(p) > 0 {
n, err := w.Write(p)
if err != nil {
return err
}
if n == 0 {
return io.ErrShortWrite
}
p = p[n:]
}
return nil
}
func readRelayConnectResponse(r io.Reader) error {
var header [4]byte
if _, err := io.ReadFull(r, header[:]); err != nil {
+5 -3
View File
@@ -22,6 +22,7 @@ type Option struct {
TLS bool
ECHConfig *ech.Config
SkipCertVerify bool
NameCertVerify string
Fingerprint string
Certificate string
PrivateKey string
@@ -69,9 +70,10 @@ func NewGostWebsocket(ctx context.Context, conn net.Conn, option *Option) (net.C
InsecureSkipVerify: option.SkipCertVerify,
NextProtos: []string{"http/1.1"},
},
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
Fingerprint: option.Fingerprint,
NameCertVerify: option.NameCertVerify,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
})
if err != nil {
return nil, err
+1 -1
View File
@@ -279,7 +279,7 @@ func NewTransport(dialFn DialFn, tlsConfig *vmess.TLSConfig, gunCfg *Config) *Tr
return nil, err
}
if tlsConfig.Reality == nil && tlsConfig.TLSMirror == nil { // reality and tlsmirror don't return the negotiated ALPN
if tlsConfig.ShadowTLS == nil && tlsConfig.Restls == nil && tlsConfig.Reality == nil && tlsConfig.TLSMirror == nil { // shadowtls, restls, reality and tlsmirror don't return the negotiated ALPN
state := tlsC.GetTLSConnectionState(conn)
if p := state.NegotiatedProtocol; p != Http2NextProtoTLS {
_ = conn.Close()
+389
View File
@@ -0,0 +1,389 @@
package jls
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"sync"
"time"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/ntp"
tls "github.com/metacubex/jls-tls"
)
const (
Mode = "jls"
bitsPerByte = 8
rateLimitCycle = 10 * time.Millisecond
maxRateLimitBurstBytes = 64 * 1024
)
var (
DefaultALPN = []string{"h2", "http/1.1"}
ErrJLSAuthFailed = tls.ErrJLSAuthFailed
ErrFallbackCompleted = errors.New("jls: connection relayed to fallback")
)
type User = tls.JLSUser
type ClientConfig struct {
Config
ServerName string
ALPN []string
ClientFingerprint string
}
type Config struct {
User User
}
type ServerConfig struct {
TLSConfig *tls.Config
Dest string
RateLimit uint64
DialContext func(ctx context.Context, network, address string) (net.Conn, error)
}
func NewConfig(username, password string) (*Config, error) {
if username == "" {
return nil, errors.New("jls: username is required")
}
if password == "" {
return nil, errors.New("jls: password is required")
}
return &Config{User: User{Username: username, Password: password}}, nil
}
func NewClientConfig(serverName, username, password string, alpn []string) (*ClientConfig, error) {
if serverName == "" {
return nil, errors.New("jls: server name is required")
}
authConfig, err := NewConfig(username, password)
if err != nil {
return nil, err
}
config := &ClientConfig{
Config: *authConfig,
ServerName: serverName,
}
if alpn != nil {
config.ALPN = append([]string{}, alpn...)
}
return config, nil
}
func NewClient(ctx context.Context, conn net.Conn, config *ClientConfig) (net.Conn, error) {
if config == nil {
return nil, errors.New("jls: nil client config")
}
if config.ServerName == "" {
return nil, errors.New("jls: server name is required")
}
if config.User.Username == "" {
return nil, errors.New("jls: username is required")
}
if config.User.Password == "" {
return nil, errors.New("jls: password is required")
}
if client, ok, err := newUTLSClient(ctx, conn, config); ok {
return client, err
}
alpn := config.ALPN
if alpn == nil {
alpn = DefaultALPN
}
tlsConn := tls.Client(conn, &tls.Config{
ServerName: config.ServerName,
NextProtos: append([]string(nil), alpn...),
RootCAs: ca.GetCertPool(),
Time: ntp.Now,
JLSConfig: &tls.JLSConfig{
Enable: true,
User: config.User,
},
})
if err := tlsConn.HandshakeContext(ctx); err != nil {
return nil, err
}
if tlsConn.ConnectionState().JLS.Status != tls.JLSAuthenticated {
return nil, ErrJLSAuthFailed
}
return tlsConn, nil
}
func NewServerConfig(sni, dest string, users []User, alpn []string, rateLimit uint64, dialContext func(context.Context, string, string) (net.Conn, error)) (*ServerConfig, error) {
if dest == "" {
return nil, errors.New("jls: dest is required")
}
destHost, _, err := net.SplitHostPort(dest)
if err != nil {
return nil, fmt.Errorf("jls: invalid dest address: %w", err)
}
if sni == "" {
sni = destHost
}
if len(users) == 0 {
return nil, errors.New("jls: at least one user is required")
}
for _, user := range users {
if user.Username == "" {
return nil, errors.New("jls: username is required")
}
if user.Password == "" {
return nil, errors.New("jls: password is required")
}
}
if dialContext == nil {
return nil, errors.New("jls: dial context is required")
}
if alpn == nil {
alpn = DefaultALPN
}
// JLS authenticates the peer, so this generated certificate only carries the TLS handshake.
certificatePEM, privateKeyPEM, _, err := ca.NewRandomTLSKeyPair(ca.KeyPairTypeP256)
if err != nil {
return nil, fmt.Errorf("jls: generate TLS certificate: %w", err)
}
certificate, err := tls.X509KeyPair([]byte(certificatePEM), []byte(privateKeyPEM))
if err != nil {
return nil, fmt.Errorf("jls: parse TLS certificate: %w", err)
}
return &ServerConfig{
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{certificate},
NextProtos: append([]string(nil), alpn...),
MinVersion: tls.VersionTLS13,
Time: ntp.Now,
JLSConfig: &tls.JLSConfig{
Enable: true,
Users: append([]User(nil), users...),
ServerName: sni,
},
},
Dest: dest,
RateLimit: rateLimit,
DialContext: dialContext,
}, nil
}
func Server(ctx context.Context, conn net.Conn, config *ServerConfig) (net.Conn, error) {
if config == nil || config.TLSConfig == nil {
return nil, errors.New("jls: nil server config")
}
recorder := &handshakeRecorderConn{Conn: conn, recording: true}
tlsConn := tls.Server(recorder, config.TLSConfig.Clone())
if err := tlsConn.HandshakeContext(ctx); err != nil {
// A partial or complete server flight may have been written before a later
// client message or network error; forwarding would then mix two TLS handshakes.
if recorder.wroteToClient() {
recorder.discard()
return nil, err
}
return nil, relayFallback(ctx, conn, recorder.stop(), config)
}
recorder.discard()
// Defensively reject a successful TLS handshake if custom configuration bypassed JLS authentication.
if tlsConn.ConnectionState().JLS.Status != tls.JLSAuthenticated {
return nil, ErrJLSAuthFailed
}
return tlsConn, nil
}
func UserFromConn(conn net.Conn) (string, bool) {
tlsConn, ok := N.FindUpstream(conn, func(tlsConn *tls.Conn) bool {
return tlsConn.ConnectionState().JLS.Status != tls.JLSDisabled
})
if !ok {
return "", false
}
state := tlsConn.ConnectionState().JLS
if state.Status != tls.JLSAuthenticated || state.User == "" {
return "", false
}
return state.User, true
}
func relayFallback(ctx context.Context, inbound net.Conn, prefix []byte, config *ServerConfig) error {
upstream, err := config.DialContext(ctx, "tcp", config.Dest)
if err != nil {
return err
}
inbound = N.NewCachedConn(inbound, prefix)
upstream = newRateLimitedConn(upstream, config.RateLimit)
if err = N.RelayContext(ctx, inbound, upstream); err != nil {
return err
}
return ErrFallbackCompleted
}
type rateLimitedConn struct {
net.Conn
ctx context.Context
cancel context.CancelFunc
readLimiter *bitRateLimiter
writeLimiter *bitRateLimiter
burst int
}
func newRateLimitedConn(conn net.Conn, rateBps uint64) net.Conn {
if rateBps == 0 {
return conn
}
burst := rateBps / bitsPerByte / uint64(time.Second/rateLimitCycle)
if burst == 0 {
burst = 1
} else if burst > maxRateLimitBurstBytes {
burst = maxRateLimitBurstBytes
}
limitCtx, cancel := context.WithCancel(context.Background())
return &rateLimitedConn{
Conn: conn,
ctx: limitCtx,
cancel: cancel,
readLimiter: &bitRateLimiter{rateBps: rateBps},
writeLimiter: &bitRateLimiter{rateBps: rateBps},
burst: int(burst),
}
}
func (c *rateLimitedConn) Read(p []byte) (n int, err error) {
if len(p) > c.burst {
p = p[:c.burst]
}
n, err = c.Conn.Read(p)
if n > 0 {
if limitErr := c.readLimiter.WaitN(c.ctx, n); err == nil {
err = limitErr
}
}
return
}
func (c *rateLimitedConn) Write(p []byte) (n int, err error) {
for len(p) > 0 {
chunkSize := len(p)
if chunkSize > c.burst {
chunkSize = c.burst
}
if err = c.writeLimiter.WaitN(c.ctx, chunkSize); err != nil {
return n, err
}
var written int
written, err = c.Conn.Write(p[:chunkSize])
n += written
p = p[written:]
if err != nil {
return n, err
}
if written != chunkSize {
return n, io.ErrShortWrite
}
}
return n, nil
}
func (c *rateLimitedConn) Close() error {
c.cancel()
return c.Conn.Close()
}
func (c *rateLimitedConn) CloseWrite() error {
if conn, ok := c.Conn.(interface{ CloseWrite() error }); ok {
return conn.CloseWrite()
}
return c.Close()
}
type bitRateLimiter struct {
mu sync.Mutex
rateBps uint64
next time.Time
}
func (l *bitRateLimiter) WaitN(ctx context.Context, n int) error {
delay := l.reserveN(time.Now(), n)
if delay <= 0 {
return nil
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (l *bitRateLimiter) reserveN(now time.Time, n int) time.Duration {
interval := time.Duration(uint64(n) * bitsPerByte * uint64(time.Second) / l.rateBps)
l.mu.Lock()
ready := l.next
if ready.Before(now) {
ready = now
}
l.next = ready.Add(interval)
l.mu.Unlock()
return ready.Sub(now)
}
type handshakeRecorderConn struct {
net.Conn
buffer bytes.Buffer
recording bool
wrote bool
}
func (c *handshakeRecorderConn) Upstream() any {
return c.Conn
}
func (c *handshakeRecorderConn) ReaderReplaceable() bool {
return !c.recording
}
func (c *handshakeRecorderConn) WriterReplaceable() bool {
return !c.recording
}
func (c *handshakeRecorderConn) Read(p []byte) (int, error) {
n, err := c.Conn.Read(p)
if c.recording && n > 0 {
_, _ = c.buffer.Write(p[:n])
}
return n, err
}
func (c *handshakeRecorderConn) Write(p []byte) (int, error) {
n, err := c.Conn.Write(p)
if c.recording && n > 0 {
c.wrote = true
}
return n, err
}
func (c *handshakeRecorderConn) stop() []byte {
c.recording = false
data := c.buffer.Bytes()
// Transfer ownership of the backing slice to the fallback path. Recording is
// disabled before detaching, so the recorder cannot append to or reuse it.
c.buffer = bytes.Buffer{}
return data
}
func (c *handshakeRecorderConn) discard() {
c.recording = false
c.buffer = bytes.Buffer{}
}
func (c *handshakeRecorderConn) wroteToClient() bool {
return c.wrote
}
+529
View File
@@ -0,0 +1,529 @@
package jls
import (
"bytes"
"context"
"errors"
"io"
"net"
"sync/atomic"
"testing"
"time"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/http"
"github.com/metacubex/http/httptest"
tls "github.com/metacubex/jls-tls"
httpTLS "github.com/metacubex/tls"
)
func TestJLSClientServer(t *testing.T) {
for _, clientFingerprint := range []string{"", "chrome"} {
name := "Go"
if clientFingerprint != "" {
name = "uTLS"
}
t.Run(name, func(t *testing.T) {
testJLSClientServer(t, clientFingerprint)
})
}
}
func testJLSClientServer(t *testing.T, clientFingerprint string) {
user := User{Username: "test-user", Password: "test-password"}
serverConfig, err := NewServerConfig("camouflage.example", "camouflage.example:443", []User{user}, nil, 0, func(context.Context, string, string) (net.Conn, error) {
return nil, errors.New("authenticated JLS connection dialed fallback")
})
if err != nil {
t.Fatal(err)
}
clientConfig, err := NewClientConfig("camouflage.example", user.Username, user.Password, nil)
if err != nil {
t.Fatal(err)
}
clientConfig.ClientFingerprint = clientFingerprint
serverSide, clientSide := newLocalTCPPair(t)
serverDone := make(chan error, 1)
go func() {
conn, err := Server(context.Background(), serverSide, serverConfig)
if err != nil {
serverDone <- err
return
}
defer conn.Close()
state := conn.(*tls.Conn).ConnectionState()
if state.JLS.Status != tls.JLSAuthenticated || state.JLS.User != user.Username {
serverDone <- errors.New("server did not authenticate JLS user")
return
}
outerTLS := tls.Server(N.NewBufferedConn(N.NewCachedConn(conn, nil)), &tls.Config{})
if authenticatedUser, ok := UserFromConn(outerTLS); !ok || authenticatedUser != user.Username {
serverDone <- errors.New("server did not expose JLS user")
return
}
outerJLS := tls.Server(outerTLS, &tls.Config{JLSConfig: &tls.JLSConfig{Enable: true}})
if _, ok := UserFromConn(outerJLS); ok {
serverDone <- errors.New("server exposed an inner JLS user through an unauthenticated outer JLS connection")
return
}
_, err = io.Copy(conn, conn)
serverDone <- err
}()
client, err := NewClient(context.Background(), clientSide, clientConfig)
if err != nil {
t.Fatal(err)
}
payload := []byte("JLS over TCP")
if _, err = client.Write(payload); err != nil {
t.Fatal(err)
}
response := make([]byte, len(payload))
if _, err = io.ReadFull(client, response); err != nil {
t.Fatal(err)
}
if !bytes.Equal(response, payload) {
t.Fatalf("response = %q, want %q", response, payload)
}
_ = client.Close()
if err = <-serverDone; err != nil {
t.Fatal(err)
}
}
func TestJLSUTLSClientRejectsInvalidFallbackCertificate(t *testing.T) {
tlsConfig := newTestTLSServerConfig(t, tls.VersionTLS13)
serverSide, clientSide := newLocalTCPPair(t)
serverDone := make(chan error, 1)
go func() {
server := tls.Server(serverSide, tlsConfig)
serverDone <- server.Handshake()
_ = serverSide.Close()
}()
config, err := NewClientConfig("camouflage.example", "user", "password", nil)
if err != nil {
t.Fatal(err)
}
config.ClientFingerprint = "chrome"
if conn, clientErr := NewClient(context.Background(), clientSide, config); clientErr == nil || errors.Is(clientErr, ErrJLSAuthFailed) {
if conn != nil {
_ = conn.Close()
}
t.Fatalf("client error = %v, want fallback certificate verification error", clientErr)
}
<-serverDone
}
func TestJLSUTLSClientFallback(t *testing.T) {
for _, test := range []struct {
name string
protocol string
hrr bool
}{
{name: "HTTP/1.1", protocol: "http/1.1"},
{name: "HTTP/2", protocol: "h2"},
{name: "HelloRetryRequest", protocol: "http/1.1", hrr: true},
} {
t.Run(test.name, func(t *testing.T) {
requestProtocol := make(chan string, 1)
hrrObserved := make(chan bool, 1)
server := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
requestProtocol <- request.Proto
writer.WriteHeader(http.StatusNoContent)
}))
server.EnableHTTP2 = test.protocol == "h2"
if test.hrr {
server.TLS = &httpTLS.Config{
CurvePreferences: []httpTLS.CurveID{httpTLS.CurveP256},
VerifyConnection: func(state httpTLS.ConnectionState) error {
hrrObserved <- state.HelloRetryRequest
return nil
},
}
}
server.StartTLS()
defer func() {
server.CloseClientConnections()
server.Close()
}()
ca.GetCertPool().AddCert(server.Certificate())
clientSide, err := net.Dial("tcp", server.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
config, err := NewClientConfig("example.com", "user", "password", []string{test.protocol})
if err != nil {
t.Fatal(err)
}
config.ClientFingerprint = "chrome"
if conn, clientErr := NewClient(context.Background(), clientSide, config); !errors.Is(clientErr, ErrJLSAuthFailed) {
if conn != nil {
_ = conn.Close()
}
t.Fatalf("client error = %v, want %v", clientErr, ErrJLSAuthFailed)
}
wantProtocol := "HTTP/1.1"
if test.protocol == "h2" {
wantProtocol = "HTTP/2.0"
}
select {
case got := <-requestProtocol:
if got != wantProtocol {
t.Fatalf("fallback protocol = %q, want %q", got, wantProtocol)
}
default:
t.Fatal("fallback HTTP request was not sent")
}
if test.hrr && !<-hrrObserved {
t.Fatal("ordinary TLS fallback did not exercise HelloRetryRequest")
}
})
}
}
func TestJLSServerFallsBackBeforeServerFlight(t *testing.T) {
user := User{Username: "user", Password: "password"}
for _, test := range []struct {
name string
configure func(*ServerConfig, *ClientConfig)
}{
{
name: "HelloRetryRequest",
configure: func(serverConfig *ServerConfig, _ *ClientConfig) {
serverConfig.TLSConfig.CurvePreferences = []tls.CurveID{tls.CurveP256}
},
},
{
name: "missing certificate",
configure: func(serverConfig *ServerConfig, _ *ClientConfig) {
serverConfig.TLSConfig.Certificates = nil
},
},
{
name: "ALPN mismatch",
configure: func(serverConfig *ServerConfig, clientConfig *ClientConfig) {
serverConfig.TLSConfig.NextProtos = []string{"h3"}
clientConfig.ALPN = []string{"http/1.1"}
},
},
} {
t.Run(test.name, func(t *testing.T) {
testJLSServerFallsBackBeforeServerFlight(t, user, test.configure)
})
}
}
func testJLSServerFallsBackBeforeServerFlight(t *testing.T, user User, configure func(*ServerConfig, *ClientConfig)) {
t.Helper()
fallbackRequest := make(chan struct{}, 1)
fallback := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
fallbackRequest <- struct{}{}
writer.WriteHeader(http.StatusNoContent)
}))
fallback.StartTLS()
defer func() {
fallback.CloseClientConnections()
fallback.Close()
}()
ca.GetCertPool().AddCert(fallback.Certificate())
fallbackDialed := make(chan struct{}, 1)
serverConfig, err := NewServerConfig("example.com", fallback.Listener.Addr().String(), []User{user}, nil, 0, func(ctx context.Context, network, _ string) (net.Conn, error) {
fallbackDialed <- struct{}{}
return (&net.Dialer{}).DialContext(ctx, network, fallback.Listener.Addr().String())
})
if err != nil {
t.Fatal(err)
}
clientConfig, err := NewClientConfig("example.com", user.Username, user.Password, nil)
if err != nil {
t.Fatal(err)
}
clientConfig.ClientFingerprint = "chrome"
configure(serverConfig, clientConfig)
serverSide, clientSide := newLocalTCPPair(t)
serverDone := make(chan error, 1)
go func() {
defer serverSide.Close()
_, serverErr := Server(context.Background(), serverSide, serverConfig)
serverDone <- serverErr
}()
if conn, clientErr := NewClient(context.Background(), clientSide, clientConfig); !errors.Is(clientErr, ErrJLSAuthFailed) {
if conn != nil {
_ = conn.Close()
}
t.Fatalf("client error = %v, want %v", clientErr, ErrJLSAuthFailed)
}
_ = clientSide.Close()
if err = <-serverDone; !errors.Is(err, ErrFallbackCompleted) {
t.Fatalf("server error = %v, want %v", err, ErrFallbackCompleted)
}
select {
case <-fallbackDialed:
default:
t.Fatal("JLS server did not dial fallback")
}
select {
case <-fallbackRequest:
default:
t.Fatal("fallback HTTP request was not sent")
}
}
func TestNewServerConfigRequiresDialContext(t *testing.T) {
_, err := NewServerConfig(
"camouflage.example",
"camouflage.example:443",
[]User{{Username: "user", Password: "password"}},
nil,
0,
nil,
)
if err == nil || err.Error() != "jls: dial context is required" {
t.Fatalf("error = %v, want dial context required error", err)
}
}
func TestJLSServerFallback(t *testing.T) {
for _, version := range []uint16{tls.VersionTLS13, tls.VersionTLS12} {
t.Run(tls.VersionName(version), func(t *testing.T) {
testJLSServerFallback(t, version)
})
}
}
func testJLSServerFallback(t *testing.T, version uint16) {
upstreamConfig := newTestTLSServerConfig(t, version)
upstreamClient, upstreamServer := net.Pipe()
upstreamDone := make(chan error, 1)
go func() {
conn := tls.Server(upstreamServer, upstreamConfig)
if err := conn.Handshake(); err != nil {
upstreamDone <- err
return
}
_, err := io.Copy(conn, conn)
upstreamDone <- err
}()
serverConfig, err := NewServerConfig("camouflage.example", "camouflage.example:443", []User{{Username: "user", Password: "password"}}, nil, 0, func(context.Context, string, string) (net.Conn, error) {
return upstreamClient, nil
})
if err != nil {
t.Fatal(err)
}
serverSide, clientSide := net.Pipe()
serverDone := make(chan error, 1)
go func() {
_, err := Server(context.Background(), serverSide, serverConfig)
serverDone <- err
}()
client := tls.Client(clientSide, &tls.Config{
ServerName: "camouflage.example",
InsecureSkipVerify: true,
MinVersion: version,
MaxVersion: version,
})
if err = client.Handshake(); err != nil {
t.Fatal(err)
}
payload := []byte("ordinary TLS fallback")
if _, err = client.Write(payload); err != nil {
t.Fatal(err)
}
response := make([]byte, len(payload))
if _, err = io.ReadFull(client, response); err != nil {
t.Fatal(err)
}
if !bytes.Equal(response, payload) {
t.Fatalf("response = %q, want %q", response, payload)
}
_ = client.Close()
if err = <-serverDone; !errors.Is(err, ErrFallbackCompleted) {
t.Fatalf("server error = %v, want %v", err, ErrFallbackCompleted)
}
if err = <-upstreamDone; err != nil {
t.Fatal(err)
}
}
func TestJLSServerDoesNotFallbackAfterServerFlight(t *testing.T) {
user := User{Username: "user", Password: "password"}
fallbackDialed := false
serverConfig, err := NewServerConfig("camouflage.example", "camouflage.example:443", []User{user}, nil, 0, func(context.Context, string, string) (net.Conn, error) {
fallbackDialed = true
return nil, errors.New("fallback dialed")
})
if err != nil {
t.Fatal(err)
}
clientConfig, err := NewClientConfig("camouflage.example", user.Username, user.Password, nil)
if err != nil {
t.Fatal(err)
}
serverSide, clientSide := net.Pipe()
serverDone := make(chan error, 1)
go func() {
_, err := Server(context.Background(), serverSide, serverConfig)
serverDone <- err
}()
client, clientErr := NewClient(context.Background(), &failWritesAfterReadConn{Conn: clientSide}, clientConfig)
if client != nil {
_ = client.Close()
}
_ = clientSide.Close()
if clientErr == nil {
t.Fatal("client handshake unexpectedly succeeded")
}
if serverErr := <-serverDone; serverErr == nil {
t.Fatal("server handshake unexpectedly succeeded")
}
if fallbackDialed {
t.Fatal("post-flight handshake failure dialed fallback")
}
}
type failWritesAfterReadConn struct {
net.Conn
read atomic.Bool
}
func (c *failWritesAfterReadConn) Read(p []byte) (int, error) {
n, err := c.Conn.Read(p)
if n > 0 {
c.read.Store(true)
}
return n, err
}
func (c *failWritesAfterReadConn) Write(p []byte) (int, error) {
if c.read.Load() {
return 0, errors.New("test client write failed after reading server flight")
}
return c.Conn.Write(p)
}
func TestJLSServerFallbackReplaysRejectedTLS(t *testing.T) {
request := []byte{23, 3, 3, 0, 1, 0} // Application data before ClientHello.
response := []byte("camouflage response")
upstreamClient, upstreamServer := net.Pipe()
upstreamDone := make(chan error, 1)
go func() {
defer upstreamServer.Close()
got := make([]byte, len(request))
if _, err := io.ReadFull(upstreamServer, got); err != nil {
upstreamDone <- err
return
}
if !bytes.Equal(got, request) {
upstreamDone <- errors.New("fallback received modified handshake bytes")
return
}
_, err := upstreamServer.Write(response)
upstreamDone <- err
}()
serverConfig, err := NewServerConfig("camouflage.example", "camouflage.example:443", []User{{Username: "user", Password: "password"}}, nil, 0, func(context.Context, string, string) (net.Conn, error) {
return upstreamClient, nil
})
if err != nil {
t.Fatal(err)
}
serverSide, clientSide := net.Pipe()
serverDone := make(chan error, 1)
go func() {
_, err := Server(context.Background(), serverSide, serverConfig)
serverDone <- err
}()
if _, err = clientSide.Write(request); err != nil {
t.Fatal(err)
}
got := make([]byte, len(response))
if _, err = io.ReadFull(clientSide, got); err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, response) {
t.Fatalf("fallback response = %q, want %q", got, response)
}
_ = clientSide.Close()
if err = <-serverDone; !errors.Is(err, ErrFallbackCompleted) {
t.Fatalf("server error = %v, want %v", err, ErrFallbackCompleted)
}
if err = <-upstreamDone; err != nil {
t.Fatal(err)
}
}
func TestBitRateLimiterReservations(t *testing.T) {
limiter := &bitRateLimiter{rateBps: 800}
now := time.Unix(0, 0)
if delay := limiter.reserveN(now, 1); delay != 0 {
t.Fatalf("initial reservation delay = %s, want 0", delay)
}
if delay := limiter.reserveN(now, 1); delay != 10*time.Millisecond {
t.Fatalf("second reservation delay = %s, want 10ms", delay)
}
}
func newTestTLSServerConfig(t *testing.T, version uint16) *tls.Config {
t.Helper()
certificatePEM, privateKeyPEM, _, err := ca.NewRandomTLSKeyPair(ca.KeyPairTypeP256)
if err != nil {
t.Fatal(err)
}
certificate, err := tls.X509KeyPair([]byte(certificatePEM), []byte(privateKeyPEM))
if err != nil {
t.Fatal(err)
}
return &tls.Config{
Certificates: []tls.Certificate{certificate},
MinVersion: version,
MaxVersion: version,
}
}
// newLocalTCPPair mirrors crypto/tls's test helper. A real TCP connection has
// enough buffering to avoid net.Pipe deadlocks when TLS handshake writes cross,
// such as a server ticket flight and the client's Finished message.
func newLocalTCPPair(t *testing.T) (server, client net.Conn) {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
accepted := make(chan struct {
conn net.Conn
err error
}, 1)
go func() {
conn, acceptErr := listener.Accept()
accepted <- struct {
conn net.Conn
err error
}{conn: conn, err: acceptErr}
}()
client, err = net.Dial("tcp", listener.Addr().String())
if err != nil {
t.Fatal(err)
}
result := <-accepted
if result.err != nil {
_ = client.Close()
t.Fatal(result.err)
}
return result.conn, client
}
+311
View File
@@ -0,0 +1,311 @@
package jls
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"crypto/x509"
"errors"
"net"
"strings"
"github.com/metacubex/mihomo/component/ca"
tlsC "github.com/metacubex/mihomo/component/tls"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/http"
"github.com/metacubex/randv2"
utls "github.com/metacubex/utls"
)
const (
jlsClientHelloType = 1
jlsServerHelloType = 2
jlsHandshakeHeaderLen = 4
jlsHelloLegacyVersionLen = 2
jlsHelloRandomLen = 32
jlsHelloRandomOffset = jlsHandshakeHeaderLen + jlsHelloLegacyVersionLen
jlsRandomSeedLen = jlsHelloRandomLen / 2
)
func newUTLSClient(ctx context.Context, conn net.Conn, config *ClientConfig) (net.Conn, bool, error) {
fingerprint, ok := tlsC.GetFingerprint(config.ClientFingerprint)
if !ok {
return nil, false, nil
}
verifier := &utlsJLSVerifier{
user: config.User,
serverName: config.ServerName,
}
alpn := config.ALPN
if alpn == nil {
alpn = DefaultALPN
}
// Resumption would require recalculating PSK binders after replacing the
// ClientHello random. uTLS does not expose a hook for that operation, so this
// client deliberately disables session tickets and 0-RTT.
uConn := utls.UClient(conn, &utls.Config{
ServerName: config.ServerName,
NextProtos: append([]string(nil), alpn...),
// JLS authenticates the server in VerifyConnection. TLS still verifies
// CertificateVerify against the camouflage certificate's public key.
InsecureSkipVerify: true,
SessionTicketsDisabled: true,
Time: ntp.Now,
VerifyConnection: verifier.VerifyConnection,
}, fingerprint)
verifier.UConn = uConn
// uTLS has no hook for JLS, so first let it build the complete fingerprint.
// JLS authenticates the exact serialized ClientHello with random zeroed;
// changing the random before the fingerprint is finalized would authenticate
// bytes that can differ from the ClientHello sent on the wire.
if err := uConn.BuildHandshakeState(); err != nil {
return nil, true, err
}
if config.ALPN != nil {
overrideUTLSALPN(uConn, config.ALPN)
if err := uConn.BuildHandshakeState(); err != nil {
return nil, true, err
}
}
hello := uConn.HandshakeState.Hello
if !utlsClientHelloSupportsTLS13(hello) {
return nil, true, errors.New("jls: uTLS fingerprint does not support TLS 1.3")
}
authData, err := jlsClientHelloAuthData(hello.Raw)
if err != nil {
return nil, true, err
}
if len(hello.Random) != jlsHelloRandomLen {
return nil, true, errors.New("jls: invalid uTLS client random")
}
fakeRandom, err := jlsBuildFakeRandom(config.User, hello.Random[:jlsRandomSeedLen], authData)
if err != nil {
return nil, true, err
}
if err = uConn.SetClientRandom(fakeRandom); err != nil {
return nil, true, err
}
if err = uConn.BuildHandshakeState(); err != nil {
return nil, true, err
}
verifier.clientHello = append([]byte(nil), uConn.HandshakeState.Hello.Raw...)
if err = uConn.HandshakeContext(ctx); err != nil {
return nil, true, err
}
if !verifier.authenticated {
// The fallback certificate is valid, so finish with a plausible HTTP
// request before returning the JLS authentication error. This is
// synchronous because the Shadowsocks caller closes conn on return.
jlsClientHTTPFallback(ctx, uConn, config.ServerName, fingerprint)
return nil, true, ErrJLSAuthFailed
}
if uConn.ConnectionState().Version != utls.VersionTLS13 {
_ = uConn.Close()
return nil, true, ErrJLSAuthFailed
}
return uConn, true, nil
}
func jlsClientHTTPFallback(ctx context.Context, uConn net.Conn, serverName string, fingerprint utls.ClientHelloID) {
defer uConn.Close()
// The TLS layer is already established, so HTTP/2 must use h2c mode to avoid
// another TLS handshake. Otherwise use HTTP/1 as negotiated by the server.
protocols := new(http.Protocols)
if conn, ok := uConn.(interface{ ConnectionState() utls.ConnectionState }); ok && conn.ConnectionState().NegotiatedProtocol == "h2" {
protocols.SetUnencryptedHTTP2(true)
} else {
protocols.SetHTTP1(true)
}
client := http.Client{
Transport: &http.Transport{
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return uConn, nil
},
Protocols: protocols,
},
}
request, err := http.NewRequestWithContext(ctx, "GET", "https://"+serverName, nil)
if err != nil {
return
}
request.Header.Set("User-Agent", fingerprint.Client)
request.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", randv2.IntN(32)+30)})
response, err := client.Do(request)
if err != nil {
return
}
response.Body.Close()
client.CloseIdleConnections()
}
func utlsClientHelloSupportsTLS13(hello *utls.PubClientHelloMsg) bool {
for _, version := range hello.SupportedVersions {
if version == utls.VersionTLS13 {
return true
}
}
return false
}
type utlsJLSVerifier struct {
*utls.UConn
user User
serverName string
clientHello []byte
authenticated bool
}
func (v *utlsJLSVerifier) VerifyConnection(state utls.ConnectionState) error {
// JLS v3 does not permit HelloRetryRequest at any stage. uTLS replaces
// HandshakeState.Hello when it sends the second ClientHello.
if !bytes.Equal(v.clientHello, v.HandshakeState.Hello.Raw) {
return verifyUTLSCertificate(state, v.serverName)
}
serverHello := v.HandshakeState.ServerHello
if serverHello == nil {
return errors.New("jls: uTLS server hello is unavailable")
}
authData, err := jlsServerHelloAuthData(serverHello.Raw)
if err != nil {
return err
}
if !jlsCheckFakeRandom(v.user, serverHello.Random, authData) {
return verifyUTLSCertificate(state, v.serverName)
}
v.authenticated = true
return nil
}
func verifyUTLSCertificate(state utls.ConnectionState, serverName string) error {
certificates := state.PeerCertificates
if len(certificates) == 0 {
return errors.New("jls: fallback server sent no certificates")
}
opts := x509.VerifyOptions{
Roots: ca.GetCertPool(),
DNSName: serverName,
Intermediates: x509.NewCertPool(),
CurrentTime: ntp.Now(),
}
for _, certificate := range certificates[1:] {
opts.Intermediates.AddCert(certificate)
}
_, err := certificates[0].Verify(opts)
return err
}
// overrideUTLSALPN keeps ALPS only when h2 remains advertised.
func overrideUTLSALPN(conn *utls.UConn, protocols []string) {
hasH2 := false
for _, protocol := range protocols {
if protocol == "h2" {
hasH2 = true
break
}
}
hasALPN := false
extensions := conn.Extensions[:0]
for _, extension := range conn.Extensions {
switch extension := extension.(type) {
case *utls.ALPNExtension:
if len(protocols) == 0 {
continue
}
extension.AlpnProtocols = append([]string(nil), protocols...)
hasALPN = true
case *utls.ApplicationSettingsExtension, *utls.ApplicationSettingsExtensionNew:
if !hasH2 {
continue
}
}
extensions = append(extensions, extension)
}
if !hasALPN && len(protocols) > 0 {
extensions = append(extensions, &utls.ALPNExtension{
AlpnProtocols: append([]string(nil), protocols...),
})
}
conn.Extensions = extensions
}
func jlsClientHelloAuthData(raw []byte) ([]byte, error) {
msg, err := cloneJLSHello(raw, jlsClientHelloType)
if err != nil {
return nil, err
}
zeroJLSBytes(msg[jlsHelloRandomOffset : jlsHelloRandomOffset+jlsHelloRandomLen])
return msg, nil
}
func jlsServerHelloAuthData(raw []byte) ([]byte, error) {
msg, err := cloneJLSHello(raw, jlsServerHelloType)
if err != nil {
return nil, err
}
zeroJLSBytes(msg[jlsHelloRandomOffset : jlsHelloRandomOffset+jlsHelloRandomLen])
return msg, nil
}
func cloneJLSHello(raw []byte, messageType byte) ([]byte, error) {
if len(raw) < jlsHelloRandomOffset+jlsHelloRandomLen ||
raw[0] != messageType ||
int(raw[1])<<16|int(raw[2])<<8|int(raw[3]) != len(raw)-jlsHandshakeHeaderLen {
return nil, errors.New("jls: invalid uTLS hello")
}
return append([]byte(nil), raw...), nil
}
func jlsBuildFakeRandom(user User, random16, authData []byte) ([]byte, error) {
if len(random16) != jlsRandomSeedLen {
return nil, errors.New("jls: random seed must be 16 bytes")
}
aead, nonce, err := newJLSAEAD(user, authData)
if err != nil {
return nil, err
}
return aead.Seal(nil, nonce[:], random16, nil), nil
}
func jlsCheckFakeRandom(user User, fakeRandom, authData []byte) bool {
if len(fakeRandom) != jlsHelloRandomLen {
return false
}
aead, nonce, err := newJLSAEAD(user, authData)
if err != nil {
return false
}
plain, err := aead.Open(nil, nonce[:], fakeRandom, nil)
return err == nil && len(plain) == jlsRandomSeedLen
}
func newJLSAEAD(user User, authData []byte) (cipher.AEAD, [sha256.Size]byte, error) {
nonce := jlsHash(user.Username, authData)
key := jlsHash(user.Password, authData)
block, err := aes.NewCipher(key[:])
if err != nil {
return nil, nonce, err
}
aead, err := cipher.NewGCMWithNonceSize(block, len(nonce))
return aead, nonce, err
}
func jlsHash(value string, authData []byte) (sum [sha256.Size]byte) {
hash := sha256.New()
_, _ = hash.Write([]byte(value))
_, _ = hash.Write(authData)
hash.Sum(sum[:0])
return sum
}
func zeroJLSBytes(data []byte) {
for i := range data {
data[i] = 0
}
}
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more