Compare commits

..

9 Commits

Author SHA1 Message Date
世界
05ed88aba8 Update documentation 2022-11-25 22:59:30 +08:00
世界
9f5cc0442b Fix dockerfile 2022-11-25 22:59:30 +08:00
世界
2641a43ad8 Remove test on pull request 2022-11-25 21:12:45 +08:00
世界
4a6ab5e9fd Fix cancel on start 2022-11-25 21:12:45 +08:00
世界
d1fe17a4db Fix listen packet on address 2022-11-25 21:12:45 +08:00
世界
7c910165ef Cleanup code 2022-11-24 12:37:29 +08:00
世界
8c1fddcf8d Remove connect packet conn 2022-11-24 12:01:25 +08:00
Hellojack
01b4769852 Cleanup gun conn code 2022-11-23 14:56:31 +08:00
世界
a401828ed5 Fix shadowtls server detection 2022-11-22 22:15:38 +08:00
22 changed files with 104 additions and 154 deletions

View File

@@ -1,34 +0,0 @@
name: Test build
on:
pull_request:
branches:
- main
- dev
- dev-next
jobs:
build:
name: Debug build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Get latest go version
id: version
run: |
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
- name: Setup Go
uses: actions/setup-go@v2
with:
go-version: ${{ steps.version.outputs.go_version }}
- name: Cache go module
uses: actions/cache@v2
with:
path: |
~/go/pkg/mod
key: go-${{ hashFiles('**/go.sum') }}
- name: Run Test
run: make test

View File

@@ -14,7 +14,6 @@ RUN set -ex \
./cmd/sing-box
FROM alpine AS dist
LABEL maintainer="nekohasekai <contact-git@sekai.icu>"
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
RUN set -ex \
&& apk upgrade \
&& apk add bash tzdata ca-certificates \

View File

@@ -69,6 +69,20 @@ func create() (*box.Box, context.CancelFunc, error) {
cancel()
return nil, nil, E.Cause(err, "create service")
}
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
defer func() {
signal.Stop(osSignals)
close(osSignals)
}()
go func() {
_, loaded := <-osSignals
if loaded {
cancel()
}
}()
err = instance.Start()
if err != nil {
cancel()
@@ -80,6 +94,7 @@ func create() (*box.Box, context.CancelFunc, error) {
func run() error {
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
defer signal.Stop(osSignals)
for {
instance, cancel, err := create()
if err != nil {

View File

@@ -175,9 +175,13 @@ func (d *DefaultDialer) DialContext(ctx context.Context, network string, address
}
func (d *DefaultDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
if !destination.IsIPv6() {
return d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr4)
var destinationString string
if destination.IsValid() && !destination.Addr.IsUnspecified() {
destinationString = destination.String()
} else if !destination.IsIPv6() {
destinationString = d.udpAddr4
} else {
return d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr6)
destinationString = d.udpAddr6
}
return d.udpListener.ListenPacket(ctx, N.NetworkUDP, destinationString)
}

View File

@@ -1,3 +1,3 @@
package constant
var Version = "1.1-beta17"
var Version = "1.1-beta18"

View File

@@ -1,10 +1,18 @@
#### 1.1-beta18
* Enhance defense against active probe **1**
**1**:
The `fallback_after` option has been removed.
#### 1.1-beta17
* Fix shadowtls server **1**
*1*:
Added [fallback_after](/configuration/inbound/shadowtls#fallback_after) options.
Added [fallback_after](/configuration/inbound/shadowtls#fallback_after) option.
#### 1.0.7

View File

@@ -9,7 +9,6 @@
"version": 2,
"password": "fuck me till the daylight",
"fallback_after": 2,
"handshake": {
"server": "google.com",
"server_port": 443,
@@ -40,15 +39,6 @@ Set password.
Only available in the ShadowTLS v2 protocol.
#### fallback_after
Packet count before perform fallback.
Default is 2.
Lowering this may prevent TLS 1.3 connections, but reduces the risk of being actively probed.
#### handshake
==Required==

View File

@@ -9,7 +9,6 @@
"version": 2,
"password": "fuck me till the daylight",
"fallback_after": 2,
"handshake": {
"server": "google.com",
"server_port": 443,
@@ -40,14 +39,6 @@ ShadowTLS 协议版本。
仅在 ShadowTLS v2 协议中可用。
#### fallback_after
在执行回退之前的包计数。
默认值为 2。
降低此值可能会阻止 TLS 1.3 连接,但会降低被主动探测的风险。
#### handshake
==必填==

View File

@@ -43,7 +43,6 @@ type Server struct {
trafficManager *trafficontrol.Manager
urlTestHistory *urltest.HistoryStorage
tcpListener net.Listener
directIO bool
mode string
storeSelected bool
cacheFile adapter.ClashCacheFile
@@ -61,7 +60,6 @@ func NewServer(router adapter.Router, logFactory log.ObservableFactory, options
},
trafficManager: trafficManager,
urlTestHistory: urltest.NewHistoryStorage(),
directIO: options.DirectIO,
mode: strings.ToLower(options.DefaultMode),
}
if server.mode == "" {
@@ -156,7 +154,7 @@ func (s *Server) HistoryStorage() *urltest.HistoryStorage {
}
func (s *Server) RoutedConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, matchedRule adapter.Rule) (net.Conn, adapter.Tracker) {
tracker := trafficontrol.NewTCPTracker(conn, s.trafficManager, castMetadata(metadata), s.router, matchedRule, s.directIO)
tracker := trafficontrol.NewTCPTracker(conn, s.trafficManager, castMetadata(metadata), s.router, matchedRule)
return tracker, tracker
}

View File

@@ -74,7 +74,7 @@ func (tt *tcpTracker) WriterReplaceable() bool {
return true
}
func NewTCPTracker(conn net.Conn, manager *Manager, metadata Metadata, router adapter.Router, rule adapter.Rule, directIO bool) *tcpTracker {
func NewTCPTracker(conn net.Conn, manager *Manager, metadata Metadata, router adapter.Router, rule adapter.Rule) *tcpTracker {
uuid, _ := uuid.NewV4()
var chain []string
@@ -107,7 +107,7 @@ func NewTCPTracker(conn net.Conn, manager *Manager, metadata Metadata, router ad
}, func(n int64) {
download.Add(n)
manager.PushDownloaded(n)
}, directIO),
}),
manager: manager,
trackerInfo: &trackerInfo{
UUID: uuid,

View File

@@ -10,11 +10,11 @@ import (
"go.uber.org/atomic"
)
func New(conn net.Conn, readCounter []*atomic.Int64, writeCounter []*atomic.Int64, direct bool) *Conn {
func New(conn net.Conn, readCounter []*atomic.Int64, writeCounter []*atomic.Int64) *Conn {
return &Conn{bufio.NewExtendedConn(conn), readCounter, writeCounter}
}
func NewHook(conn net.Conn, readCounter func(n int64), writeCounter func(n int64), direct bool) *HookConn {
func NewHook(conn net.Conn, readCounter func(n int64), writeCounter func(n int64)) *HookConn {
return &HookConn{bufio.NewExtendedConn(conn), readCounter, writeCounter}
}

View File

@@ -29,7 +29,6 @@ var (
type StatsService struct {
createdAt time.Time
directIO bool
inbounds map[string]bool
outbounds map[string]bool
access sync.Mutex
@@ -50,7 +49,6 @@ func NewStatsService(options option.V2RayStatsServiceOptions) *StatsService {
}
return &StatsService{
createdAt: time.Now(),
directIO: options.DirectIO,
inbounds: inbounds,
outbounds: outbounds,
counters: make(map[string]*atomic.Int64),
@@ -75,7 +73,7 @@ func (s *StatsService) RoutedConnection(inbound string, outbound string, conn ne
writeCounter = append(writeCounter, s.loadOrCreateCounter("outbound>>>"+outbound+">>>traffic>>>downlink"))
}
s.access.Unlock()
return trackerconn.New(conn, readCounter, writeCounter, s.directIO)
return trackerconn.New(conn, readCounter, writeCounter)
}
func (s *StatsService) RoutedPacketConnection(inbound string, outbound string, conn N.PacketConn) N.PacketConn {

2
go.mod
View File

@@ -25,7 +25,7 @@ require (
github.com/sagernet/quic-go v0.0.0-20221108053023-645bcc4f9b15
github.com/sagernet/sing v0.0.0-20221008120626-60a9910eefe4
github.com/sagernet/sing-dns v0.0.0-20221113031420-c6aaf2ea4b10
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6
github.com/sagernet/sing-shadowsocks v0.0.0-20221115140728-028358027bfa
github.com/sagernet/sing-tun v0.0.0-20221104121441-66c48a57776f
github.com/sagernet/sing-vmess v0.0.0-20221109021549-b446d5bdddf0
github.com/sagernet/smux v0.0.0-20220831015742-e0f1988e3195

4
go.sum
View File

@@ -136,8 +136,8 @@ github.com/sagernet/sing v0.0.0-20221008120626-60a9910eefe4 h1:LO7xMvMGhYmjQg2vj
github.com/sagernet/sing v0.0.0-20221008120626-60a9910eefe4/go.mod h1:zvgDYKI+vCAW9RyfyrKTgleI+DOa8lzHMPC7VZo3OL4=
github.com/sagernet/sing-dns v0.0.0-20221113031420-c6aaf2ea4b10 h1:K84AY2TxNX37ePYXVO6QTD/kgn9kDo4oGpTIn9PF5bo=
github.com/sagernet/sing-dns v0.0.0-20221113031420-c6aaf2ea4b10/go.mod h1:VAvOT1pyryBIthTGRryFLXAsR1VRQZ05wolMYeQrr/E=
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6 h1:JJfDeYYhWunvtxsU/mOVNTmFQmnzGx9dY034qG6G3g4=
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6/go.mod h1:EX3RbZvrwAkPI2nuGa78T2iQXmrkT+/VQtskjou42xM=
github.com/sagernet/sing-shadowsocks v0.0.0-20221115140728-028358027bfa h1:L8x5xAykEs9jcEYVLDAOYSkERLfKOkU8TCKlWBOF91c=
github.com/sagernet/sing-shadowsocks v0.0.0-20221115140728-028358027bfa/go.mod h1:16sNARQbsFbYIzAuPySszQA6Wfgzk7GWSzh1a6kDrUU=
github.com/sagernet/sing-tun v0.0.0-20221104121441-66c48a57776f h1:CXF+nErOb9f7qiHingSgTa2/lJAgmEFtAQ47oVwdRGU=
github.com/sagernet/sing-tun v0.0.0-20221104121441-66c48a57776f/go.mod h1:1u3pjXA9HmH7kRiBJqM3C/zPxrxnCLd3svmqtub/RFU=
github.com/sagernet/sing-vmess v0.0.0-20221109021549-b446d5bdddf0 h1:z3kuD3hPNdEq7/wVy5lwE21f+8ZTazBtR81qswxJoCc=

View File

@@ -91,7 +91,7 @@ func (s *ShadowTLS) NewConnection(ctx context.Context, conn net.Conn, metadata a
hashConn := shadowtls.NewHashWriteConn(conn, s.password)
go bufio.Copy(hashConn, handshakeConn)
var request *buf.Buffer
request, err = s.copyUntilHandshakeFinishedV2(handshakeConn, conn, hashConn, s.fallbackAfter)
request, err = s.copyUntilHandshakeFinishedV2(ctx, handshakeConn, conn, hashConn, s.fallbackAfter)
if err == nil {
handshakeConn.Close()
return s.newConnection(ctx, bufio.NewCachedConn(shadowtls.NewConn(conn), request), metadata)
@@ -135,7 +135,7 @@ func (s *ShadowTLS) copyUntilHandshakeFinished(dst io.Writer, src io.Reader) err
}
}
func (s *ShadowTLS) copyUntilHandshakeFinishedV2(dst net.Conn, src io.Reader, hash *shadowtls.HashWriteConn, fallbackAfter int) (*buf.Buffer, error) {
func (s *ShadowTLS) copyUntilHandshakeFinishedV2(ctx context.Context, dst net.Conn, src io.Reader, hash *shadowtls.HashWriteConn, fallbackAfter int) (*buf.Buffer, error) {
const applicationData = 0x17
var tlsHdr [5]byte
var applicationDataCount int
@@ -152,9 +152,17 @@ func (s *ShadowTLS) copyUntilHandshakeFinishedV2(dst net.Conn, src io.Reader, ha
data.Release()
return nil, err
}
if length >= 8 && bytes.Equal(data.To(8), hash.Sum()) {
data.Advance(8)
return data, nil
if hash.HasContent() && length >= 8 {
checksum := hash.Sum()
if bytes.Equal(data.To(8), checksum) {
s.logger.TraceContext(ctx, "match current hashcode")
data.Advance(8)
return data, nil
} else if hash.LastSum() != nil && bytes.Equal(data.To(8), hash.LastSum()) {
s.logger.TraceContext(ctx, "match last hashcode")
data.Advance(8)
return data, nil
}
}
_, err = io.Copy(dst, io.MultiReader(bytes.NewReader(tlsHdr[:]), data))
data.Release()

View File

@@ -4,7 +4,6 @@ type ClashAPIOptions struct {
ExternalController string `json:"external_controller,omitempty"`
ExternalUI string `json:"external_ui,omitempty"`
Secret string `json:"secret,omitempty"`
DirectIO bool `json:"direct_io,omitempty"`
DefaultMode string `json:"default_mode,omitempty"`
StoreSelected bool `json:"store_selected,omitempty"`
CacheFile string `json:"cache_file,omitempty"`

View File

@@ -2,12 +2,11 @@ package option
type ShadowsocksInboundOptions struct {
ListenOptions
Network NetworkList `json:"network,omitempty"`
Method string `json:"method"`
Password string `json:"password"`
ControlPassword string `json:"control_password,omitempty"`
Users []ShadowsocksUser `json:"users,omitempty"`
Destinations []ShadowsocksDestination `json:"destinations,omitempty"`
Network NetworkList `json:"network,omitempty"`
Method string `json:"method"`
Password string `json:"password"`
Users []ShadowsocksUser `json:"users,omitempty"`
Destinations []ShadowsocksDestination `json:"destinations,omitempty"`
}
type ShadowsocksUser struct {

View File

@@ -7,7 +7,6 @@ type V2RayAPIOptions struct {
type V2RayStatsServiceOptions struct {
Enabled bool `json:"enabled,omitempty"`
DirectIO bool `json:"direct_io,omitempty"`
Inbounds []string `json:"inbounds,omitempty"`
Outbounds []string `json:"outbounds,omitempty"`
}

View File

@@ -78,12 +78,6 @@ func NewEarlyConnection(ctx context.Context, this N.Dialer, conn net.Conn, metad
}
func NewPacketConnection(ctx context.Context, this N.Dialer, conn N.PacketConn, metadata adapter.InboundContext) error {
switch metadata.Protocol {
case C.ProtocolQUIC, C.ProtocolDNS:
if !metadata.Destination.Addr.IsUnspecified() {
return connectPacketConnection(ctx, this, conn, metadata)
}
}
ctx = adapter.WithContext(ctx, &metadata)
var outConn net.PacketConn
var err error
@@ -98,29 +92,12 @@ func NewPacketConnection(ctx context.Context, this N.Dialer, conn N.PacketConn,
switch metadata.Protocol {
case C.ProtocolSTUN:
ctx, conn = canceler.NewPacketConn(ctx, conn, C.STUNTimeout)
}
return bufio.CopyPacketConn(ctx, conn, bufio.NewPacketConn(outConn))
}
func connectPacketConnection(ctx context.Context, this N.Dialer, conn N.PacketConn, metadata adapter.InboundContext) error {
ctx = adapter.WithContext(ctx, &metadata)
var outConn net.Conn
var err error
if len(metadata.DestinationAddresses) > 0 {
outConn, err = N.DialSerial(ctx, this, N.NetworkUDP, metadata.Destination, metadata.DestinationAddresses)
} else {
outConn, err = this.DialContext(ctx, N.NetworkUDP, metadata.Destination)
}
if err != nil {
return N.HandshakeFailure(conn, err)
}
switch metadata.Protocol {
case C.ProtocolQUIC:
ctx, conn = canceler.NewPacketConn(ctx, conn, C.QUICTimeout)
case C.ProtocolDNS:
ctx, conn = canceler.NewPacketConn(ctx, conn, C.DNSTimeout)
}
return bufio.CopyPacketConn(ctx, conn, bufio.NewUnbindPacketConn(outConn))
return bufio.CopyPacketConn(ctx, conn, bufio.NewPacketConn(outConn))
}
func CopyEarlyConn(ctx context.Context, conn net.Conn, serverConn net.Conn) error {

View File

@@ -34,19 +34,25 @@ func (c *HashReadConn) Sum() []byte {
type HashWriteConn struct {
net.Conn
hmac hash.Hash
hmac hash.Hash
hasContent bool
lastSum []byte
}
func NewHashWriteConn(conn net.Conn, password string) *HashWriteConn {
return &HashWriteConn{
conn,
hmac.New(sha1.New, []byte(password)),
Conn: conn,
hmac: hmac.New(sha1.New, []byte(password)),
}
}
func (c *HashWriteConn) Write(p []byte) (n int, err error) {
if c.hmac != nil {
if c.hasContent {
c.lastSum = c.Sum()
}
c.hmac.Write(p)
c.hasContent = true
}
return c.Conn.Write(p)
}
@@ -55,6 +61,14 @@ func (c *HashWriteConn) Sum() []byte {
return c.hmac.Sum(nil)[:8]
}
func (c *HashWriteConn) LastSum() []byte {
return c.lastSum
}
func (c *HashWriteConn) Fallback() {
c.hmac = nil
}
func (c *HashWriteConn) HasContent() bool {
return c.hasContent
}

View File

@@ -106,31 +106,22 @@ func (c *GunConn) Write(b []byte) (n int, err error) {
_, err = bufio.Copy(c.writer, io.MultiReader(bytes.NewReader(grpcHeader), bytes.NewReader(protobufHeader[:varuintLen+1]), bytes.NewReader(b)))
c.writeAccess.Unlock()
buf.Put(grpcHeader)
if c.flusher != nil {
if err == nil && c.flusher != nil {
c.flusher.Flush()
}
return len(b), baderror.WrapH2(err)
}
func uLen(x uint64) int {
i := 0
for x >= 0x80 {
x >>= 7
i++
}
return i + 1
}
func (c *GunConn) WriteBuffer(buffer *buf.Buffer) error {
defer buffer.Release()
dataLen := buffer.Len()
varLen := uLen(uint64(dataLen))
varLen := rw.UVariantLen(uint64(dataLen))
header := buffer.ExtendHeader(6 + varLen)
binary.BigEndian.PutUint32(header[1:5], uint32(1+varLen+dataLen))
header[5] = 0x0A
binary.PutUvarint(header[6:], uint64(dataLen))
err := rw.WriteBytes(c.writer, buffer.Bytes())
if c.flusher != nil {
if err == nil && c.flusher != nil {
c.flusher.Flush()
}
return baderror.WrapH2(err)
@@ -153,31 +144,28 @@ func (c *GunConn) RemoteAddr() net.Addr {
}
func (c *GunConn) SetDeadline(t time.Time) error {
responseWriter, loaded := c.writer.(interface {
if responseWriter, loaded := c.writer.(interface {
SetWriteDeadline(time.Time) error
})
if !loaded {
return os.ErrInvalid
}); loaded {
return responseWriter.SetWriteDeadline(t)
}
return responseWriter.SetWriteDeadline(t)
return os.ErrInvalid
}
func (c *GunConn) SetReadDeadline(t time.Time) error {
responseWriter, loaded := c.writer.(interface {
if responseWriter, loaded := c.writer.(interface {
SetReadDeadline(time.Time) error
})
if !loaded {
return os.ErrInvalid
}); loaded {
return responseWriter.SetReadDeadline(t)
}
return responseWriter.SetReadDeadline(t)
return os.ErrInvalid
}
func (c *GunConn) SetWriteDeadline(t time.Time) error {
responseWriter, loaded := c.writer.(interface {
if responseWriter, loaded := c.writer.(interface {
SetWriteDeadline(time.Time) error
})
if !loaded {
return os.ErrInvalid
}); loaded {
return responseWriter.SetWriteDeadline(t)
}
return responseWriter.SetWriteDeadline(t)
return os.ErrInvalid
}

View File

@@ -67,33 +67,30 @@ func (c *HTTPConn) RemoteAddr() net.Addr {
}
func (c *HTTPConn) SetDeadline(t time.Time) error {
responseWriter, loaded := c.writer.(interface {
if responseWriter, loaded := c.writer.(interface {
SetWriteDeadline(time.Time) error
})
if !loaded {
return os.ErrInvalid
}); loaded {
return responseWriter.SetWriteDeadline(t)
}
return responseWriter.SetWriteDeadline(t)
return os.ErrInvalid
}
func (c *HTTPConn) SetReadDeadline(t time.Time) error {
responseWriter, loaded := c.writer.(interface {
if responseWriter, loaded := c.writer.(interface {
SetReadDeadline(time.Time) error
})
if !loaded {
return os.ErrInvalid
}); loaded {
return responseWriter.SetReadDeadline(t)
}
return responseWriter.SetReadDeadline(t)
return os.ErrInvalid
}
func (c *HTTPConn) SetWriteDeadline(t time.Time) error {
responseWriter, loaded := c.writer.(interface {
if responseWriter, loaded := c.writer.(interface {
SetWriteDeadline(time.Time) error
})
if !loaded {
return os.ErrInvalid
}); loaded {
return responseWriter.SetWriteDeadline(t)
}
return responseWriter.SetWriteDeadline(t)
return os.ErrInvalid
}
type ServerHTTPConn struct {