shadowtls.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. package inbound
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/sha1"
  7. "encoding/binary"
  8. "encoding/hex"
  9. "io"
  10. "net"
  11. "os"
  12. "github.com/sagernet/sing-box/adapter"
  13. "github.com/sagernet/sing-box/common/dialer"
  14. C "github.com/sagernet/sing-box/constant"
  15. "github.com/sagernet/sing-box/log"
  16. "github.com/sagernet/sing-box/option"
  17. "github.com/sagernet/sing-box/transport/shadowtls"
  18. "github.com/sagernet/sing/common"
  19. "github.com/sagernet/sing/common/buf"
  20. "github.com/sagernet/sing/common/bufio"
  21. E "github.com/sagernet/sing/common/exceptions"
  22. M "github.com/sagernet/sing/common/metadata"
  23. N "github.com/sagernet/sing/common/network"
  24. "github.com/sagernet/sing/common/task"
  25. )
  26. type ShadowTLS struct {
  27. myInboundAdapter
  28. handshakeDialer N.Dialer
  29. handshakeAddr M.Socksaddr
  30. version int
  31. password string
  32. fallbackAfter int
  33. }
  34. func NewShadowTLS(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.ShadowTLSInboundOptions) (*ShadowTLS, error) {
  35. inbound := &ShadowTLS{
  36. myInboundAdapter: myInboundAdapter{
  37. protocol: C.TypeShadowTLS,
  38. network: []string{N.NetworkTCP},
  39. ctx: ctx,
  40. router: router,
  41. logger: logger,
  42. tag: tag,
  43. listenOptions: options.ListenOptions,
  44. },
  45. handshakeDialer: dialer.New(router, options.Handshake.DialerOptions),
  46. handshakeAddr: options.Handshake.ServerOptions.Build(),
  47. password: options.Password,
  48. }
  49. inbound.version = options.Version
  50. switch options.Version {
  51. case 0:
  52. fallthrough
  53. case 1:
  54. case 2:
  55. if options.FallbackAfter == nil {
  56. inbound.fallbackAfter = 2
  57. } else {
  58. inbound.fallbackAfter = *options.FallbackAfter
  59. }
  60. case 3:
  61. default:
  62. return nil, E.New("unknown shadowtls protocol version: ", options.Version)
  63. }
  64. inbound.connHandler = inbound
  65. return inbound, nil
  66. }
  67. func (s *ShadowTLS) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  68. handshakeConn, err := s.handshakeDialer.DialContext(ctx, N.NetworkTCP, s.handshakeAddr)
  69. if err != nil {
  70. return err
  71. }
  72. switch s.version {
  73. case 1:
  74. var handshake task.Group
  75. handshake.Append("client handshake", func(ctx context.Context) error {
  76. return s.copyUntilHandshakeFinished(handshakeConn, conn)
  77. })
  78. handshake.Append("server handshake", func(ctx context.Context) error {
  79. return s.copyUntilHandshakeFinished(conn, handshakeConn)
  80. })
  81. handshake.FastFail()
  82. handshake.Cleanup(func() {
  83. handshakeConn.Close()
  84. })
  85. err = handshake.Run(ctx)
  86. if err != nil {
  87. return err
  88. }
  89. return s.newConnection(ctx, conn, metadata)
  90. case 2:
  91. hashConn := shadowtls.NewHashWriteConn(conn, s.password)
  92. go bufio.Copy(hashConn, handshakeConn)
  93. var request *buf.Buffer
  94. request, err = s.copyUntilHandshakeFinishedV2(ctx, handshakeConn, conn, hashConn, s.fallbackAfter)
  95. if err == nil {
  96. handshakeConn.Close()
  97. return s.newConnection(ctx, bufio.NewCachedConn(shadowtls.NewConn(conn), request), metadata)
  98. } else if err == os.ErrPermission {
  99. s.logger.WarnContext(ctx, "fallback connection")
  100. hashConn.Fallback()
  101. return common.Error(bufio.Copy(handshakeConn, conn))
  102. } else {
  103. return err
  104. }
  105. default:
  106. fallthrough
  107. case 3:
  108. var clientHelloFrame *buf.Buffer
  109. clientHelloFrame, err = shadowtls.ExtractFrame(conn)
  110. if err != nil {
  111. return E.Cause(err, "read client handshake")
  112. }
  113. _, err = handshakeConn.Write(clientHelloFrame.Bytes())
  114. if err != nil {
  115. clientHelloFrame.Release()
  116. return E.Cause(err, "write client handshake")
  117. }
  118. err = shadowtls.VerifyClientHello(clientHelloFrame.Bytes(), s.password)
  119. if err != nil {
  120. s.logger.WarnContext(ctx, E.Cause(err, "client hello verify failed"))
  121. return bufio.CopyConn(ctx, conn, handshakeConn)
  122. }
  123. s.logger.TraceContext(ctx, "client hello verify success")
  124. clientHelloFrame.Release()
  125. var serverHelloFrame *buf.Buffer
  126. serverHelloFrame, err = shadowtls.ExtractFrame(handshakeConn)
  127. if err != nil {
  128. return E.Cause(err, "read server handshake")
  129. }
  130. _, err = conn.Write(serverHelloFrame.Bytes())
  131. if err != nil {
  132. serverHelloFrame.Release()
  133. return E.Cause(err, "write server handshake")
  134. }
  135. serverRandom := shadowtls.ExtractServerRandom(serverHelloFrame.Bytes())
  136. if serverRandom == nil {
  137. s.logger.WarnContext(ctx, "server random extract failed, will copy bidirectional")
  138. return bufio.CopyConn(ctx, conn, handshakeConn)
  139. }
  140. if !shadowtls.IsServerHelloSupportTLS13(serverHelloFrame.Bytes()) {
  141. s.logger.WarnContext(ctx, "TLS 1.3 is not supported, will copy bidirectional")
  142. return bufio.CopyConn(ctx, conn, handshakeConn)
  143. }
  144. serverHelloFrame.Release()
  145. s.logger.TraceContext(ctx, "client authenticated. server random extracted: ", hex.EncodeToString(serverRandom))
  146. hmacWrite := hmac.New(sha1.New, []byte(s.password))
  147. hmacWrite.Write(serverRandom)
  148. hmacAdd := hmac.New(sha1.New, []byte(s.password))
  149. hmacAdd.Write(serverRandom)
  150. hmacAdd.Write([]byte("S"))
  151. hmacVerify := hmac.New(sha1.New, []byte(s.password))
  152. hmacVerifyReset := func() {
  153. hmacVerify.Reset()
  154. hmacVerify.Write(serverRandom)
  155. hmacVerify.Write([]byte("C"))
  156. }
  157. var clientFirstFrame *buf.Buffer
  158. var group task.Group
  159. var handshakeFinished bool
  160. group.Append("client handshake relay", func(ctx context.Context) error {
  161. clientFrame, cErr := shadowtls.CopyByFrameUntilHMACMatches(conn, handshakeConn, hmacVerify, hmacVerifyReset)
  162. if cErr == nil {
  163. clientFirstFrame = clientFrame
  164. handshakeFinished = true
  165. handshakeConn.Close()
  166. }
  167. return cErr
  168. })
  169. group.Append("server handshake relay", func(ctx context.Context) error {
  170. cErr := shadowtls.CopyByFrameWithModification(handshakeConn, conn, s.password, serverRandom, hmacWrite)
  171. if E.IsClosedOrCanceled(cErr) && handshakeFinished {
  172. return nil
  173. }
  174. return cErr
  175. })
  176. group.Cleanup(func() {
  177. handshakeConn.Close()
  178. })
  179. err = group.Run(ctx)
  180. if err != nil {
  181. return E.Cause(err, "handshake relay")
  182. }
  183. s.logger.TraceContext(ctx, "handshake relay finished")
  184. return s.newConnection(ctx, bufio.NewCachedConn(shadowtls.NewVerifiedConn(conn, hmacAdd, hmacVerify, nil), clientFirstFrame), metadata)
  185. }
  186. }
  187. func (s *ShadowTLS) copyUntilHandshakeFinished(dst io.Writer, src io.Reader) error {
  188. const handshake = 0x16
  189. const changeCipherSpec = 0x14
  190. var hasSeenChangeCipherSpec bool
  191. var tlsHdr [5]byte
  192. for {
  193. _, err := io.ReadFull(src, tlsHdr[:])
  194. if err != nil {
  195. return err
  196. }
  197. length := binary.BigEndian.Uint16(tlsHdr[3:])
  198. _, err = io.Copy(dst, io.MultiReader(bytes.NewReader(tlsHdr[:]), io.LimitReader(src, int64(length))))
  199. if err != nil {
  200. return err
  201. }
  202. if tlsHdr[0] != handshake {
  203. if tlsHdr[0] != changeCipherSpec {
  204. return E.New("unexpected tls frame type: ", tlsHdr[0])
  205. }
  206. if !hasSeenChangeCipherSpec {
  207. hasSeenChangeCipherSpec = true
  208. continue
  209. }
  210. }
  211. if hasSeenChangeCipherSpec {
  212. return nil
  213. }
  214. }
  215. }
  216. func (s *ShadowTLS) copyUntilHandshakeFinishedV2(ctx context.Context, dst net.Conn, src io.Reader, hash *shadowtls.HashWriteConn, fallbackAfter int) (*buf.Buffer, error) {
  217. const applicationData = 0x17
  218. var tlsHdr [5]byte
  219. var applicationDataCount int
  220. for {
  221. _, err := io.ReadFull(src, tlsHdr[:])
  222. if err != nil {
  223. return nil, err
  224. }
  225. length := binary.BigEndian.Uint16(tlsHdr[3:])
  226. if tlsHdr[0] == applicationData {
  227. data := buf.NewSize(int(length))
  228. _, err = data.ReadFullFrom(src, int(length))
  229. if err != nil {
  230. data.Release()
  231. return nil, err
  232. }
  233. if hash.HasContent() && length >= 8 {
  234. checksum := hash.Sum()
  235. if bytes.Equal(data.To(8), checksum) {
  236. s.logger.TraceContext(ctx, "match current hashcode")
  237. data.Advance(8)
  238. return data, nil
  239. } else if hash.LastSum() != nil && bytes.Equal(data.To(8), hash.LastSum()) {
  240. s.logger.TraceContext(ctx, "match last hashcode")
  241. data.Advance(8)
  242. return data, nil
  243. }
  244. }
  245. _, err = io.Copy(dst, io.MultiReader(bytes.NewReader(tlsHdr[:]), data))
  246. data.Release()
  247. applicationDataCount++
  248. } else {
  249. _, err = io.Copy(dst, io.MultiReader(bytes.NewReader(tlsHdr[:]), io.LimitReader(src, int64(length))))
  250. }
  251. if err != nil {
  252. return nil, err
  253. }
  254. if applicationDataCount > fallbackAfter {
  255. return nil, os.ErrPermission
  256. }
  257. }
  258. }