proxy.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. // Package proxy contains all proxies used by Xray.
  2. //
  3. // To implement an inbound or outbound proxy, one needs to do the following:
  4. // 1. Implement the interface(s) below.
  5. // 2. Register a config creator through common.RegisterConfig.
  6. package proxy
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/rand"
  11. "io"
  12. "math/big"
  13. "runtime"
  14. "strconv"
  15. "time"
  16. "github.com/pires/go-proxyproto"
  17. "github.com/xtls/xray-core/app/dispatcher"
  18. "github.com/xtls/xray-core/common/buf"
  19. "github.com/xtls/xray-core/common/errors"
  20. "github.com/xtls/xray-core/common/net"
  21. "github.com/xtls/xray-core/common/protocol"
  22. "github.com/xtls/xray-core/common/session"
  23. "github.com/xtls/xray-core/common/signal"
  24. "github.com/xtls/xray-core/features/routing"
  25. "github.com/xtls/xray-core/features/stats"
  26. "github.com/xtls/xray-core/proxy/vless/encryption"
  27. "github.com/xtls/xray-core/transport"
  28. "github.com/xtls/xray-core/transport/internet"
  29. "github.com/xtls/xray-core/transport/internet/finalmask"
  30. "github.com/xtls/xray-core/transport/internet/reality"
  31. "github.com/xtls/xray-core/transport/internet/stat"
  32. "github.com/xtls/xray-core/transport/internet/tls"
  33. )
  34. var (
  35. Tls13SupportedVersions = []byte{0x00, 0x2b, 0x00, 0x02, 0x03, 0x04}
  36. TlsClientHandShakeStart = []byte{0x16, 0x03}
  37. TlsServerHandShakeStart = []byte{0x16, 0x03, 0x03}
  38. TlsApplicationDataStart = []byte{0x17, 0x03, 0x03}
  39. Tls13CipherSuiteDic = map[uint16]string{
  40. 0x1301: "TLS_AES_128_GCM_SHA256",
  41. 0x1302: "TLS_AES_256_GCM_SHA384",
  42. 0x1303: "TLS_CHACHA20_POLY1305_SHA256",
  43. 0x1304: "TLS_AES_128_CCM_SHA256",
  44. 0x1305: "TLS_AES_128_CCM_8_SHA256",
  45. }
  46. )
  47. const (
  48. TlsHandshakeTypeClientHello byte = 0x01
  49. TlsHandshakeTypeServerHello byte = 0x02
  50. CommandPaddingContinue byte = 0x00
  51. CommandPaddingEnd byte = 0x01
  52. CommandPaddingDirect byte = 0x02
  53. )
  54. // An Inbound processes inbound connections.
  55. type Inbound interface {
  56. // Network returns a list of networks that this inbound supports. Connections with not-supported networks will not be passed into Process().
  57. Network() []net.Network
  58. // Process processes a connection of given network. If necessary, the Inbound can dispatch the connection to an Outbound.
  59. Process(context.Context, net.Network, stat.Connection, routing.Dispatcher) error
  60. }
  61. // An Outbound process outbound connections.
  62. type Outbound interface {
  63. // Process processes the given connection. The given dialer may be used to dial a system outbound connection.
  64. Process(context.Context, *transport.Link, internet.Dialer) error
  65. }
  66. // UserManager is the interface for Inbounds and Outbounds that can manage their users.
  67. type UserManager interface {
  68. // AddUser adds a new user.
  69. AddUser(context.Context, *protocol.MemoryUser) error
  70. // RemoveUser removes a user by email.
  71. RemoveUser(context.Context, string) error
  72. // Get user by email.
  73. GetUser(context.Context, string) *protocol.MemoryUser
  74. // Get all users.
  75. GetUsers(context.Context) []*protocol.MemoryUser
  76. // Get users count.
  77. GetUsersCount(context.Context) int64
  78. }
  79. type GetInbound interface {
  80. GetInbound() Inbound
  81. }
  82. type GetOutbound interface {
  83. GetOutbound() Outbound
  84. }
  85. // TrafficState is used to track uplink and downlink of one connection
  86. // It is used by XTLS to determine if switch to raw copy mode, It is used by Vision to calculate padding
  87. type TrafficState struct {
  88. UserUUID []byte
  89. NumberOfPacketToFilter int
  90. EnableXtls bool
  91. IsTLS12orAbove bool
  92. IsTLS bool
  93. Cipher uint16
  94. RemainingServerHello int32
  95. Inbound InboundState
  96. Outbound OutboundState
  97. }
  98. type InboundState struct {
  99. // reader link state
  100. WithinPaddingBuffers bool
  101. UplinkReaderDirectCopy bool
  102. RemainingCommand int32
  103. RemainingContent int32
  104. RemainingPadding int32
  105. CurrentCommand int
  106. // write link state
  107. IsPadding bool
  108. DownlinkWriterDirectCopy bool
  109. }
  110. type OutboundState struct {
  111. // reader link state
  112. WithinPaddingBuffers bool
  113. DownlinkReaderDirectCopy bool
  114. RemainingCommand int32
  115. RemainingContent int32
  116. RemainingPadding int32
  117. CurrentCommand int
  118. // write link state
  119. IsPadding bool
  120. UplinkWriterDirectCopy bool
  121. }
  122. func NewTrafficState(userUUID []byte) *TrafficState {
  123. return &TrafficState{
  124. UserUUID: userUUID,
  125. NumberOfPacketToFilter: 8,
  126. EnableXtls: false,
  127. IsTLS12orAbove: false,
  128. IsTLS: false,
  129. Cipher: 0,
  130. RemainingServerHello: -1,
  131. Inbound: InboundState{
  132. WithinPaddingBuffers: true,
  133. UplinkReaderDirectCopy: false,
  134. RemainingCommand: -1,
  135. RemainingContent: -1,
  136. RemainingPadding: -1,
  137. CurrentCommand: 0,
  138. IsPadding: true,
  139. DownlinkWriterDirectCopy: false,
  140. },
  141. Outbound: OutboundState{
  142. WithinPaddingBuffers: true,
  143. DownlinkReaderDirectCopy: false,
  144. RemainingCommand: -1,
  145. RemainingContent: -1,
  146. RemainingPadding: -1,
  147. CurrentCommand: 0,
  148. IsPadding: true,
  149. UplinkWriterDirectCopy: false,
  150. },
  151. }
  152. }
  153. // VisionReader is used to read xtls vision protocol
  154. // Note Vision probably only make sense as the inner most layer of reader, since it need assess traffic state from origin proxy traffic
  155. type VisionReader struct {
  156. buf.Reader
  157. trafficState *TrafficState
  158. ctx context.Context
  159. isUplink bool
  160. conn net.Conn
  161. input *bytes.Reader
  162. rawInput *bytes.Buffer
  163. ob *session.Outbound
  164. // internal
  165. directReadCounter stats.Counter
  166. }
  167. func NewVisionReader(reader buf.Reader, trafficState *TrafficState, isUplink bool, ctx context.Context, conn net.Conn, input *bytes.Reader, rawInput *bytes.Buffer, ob *session.Outbound) *VisionReader {
  168. return &VisionReader{
  169. Reader: reader,
  170. trafficState: trafficState,
  171. ctx: ctx,
  172. isUplink: isUplink,
  173. conn: conn,
  174. input: input,
  175. rawInput: rawInput,
  176. ob: ob,
  177. }
  178. }
  179. func (w *VisionReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  180. buffer, err := w.Reader.ReadMultiBuffer()
  181. if buffer.IsEmpty() {
  182. return buffer, err
  183. }
  184. var withinPaddingBuffers *bool
  185. var remainingContent *int32
  186. var remainingPadding *int32
  187. var currentCommand *int
  188. var switchToDirectCopy *bool
  189. if w.isUplink {
  190. withinPaddingBuffers = &w.trafficState.Inbound.WithinPaddingBuffers
  191. remainingContent = &w.trafficState.Inbound.RemainingContent
  192. remainingPadding = &w.trafficState.Inbound.RemainingPadding
  193. currentCommand = &w.trafficState.Inbound.CurrentCommand
  194. switchToDirectCopy = &w.trafficState.Inbound.UplinkReaderDirectCopy
  195. } else {
  196. withinPaddingBuffers = &w.trafficState.Outbound.WithinPaddingBuffers
  197. remainingContent = &w.trafficState.Outbound.RemainingContent
  198. remainingPadding = &w.trafficState.Outbound.RemainingPadding
  199. currentCommand = &w.trafficState.Outbound.CurrentCommand
  200. switchToDirectCopy = &w.trafficState.Outbound.DownlinkReaderDirectCopy
  201. }
  202. if *switchToDirectCopy {
  203. if w.directReadCounter != nil {
  204. w.directReadCounter.Add(int64(buffer.Len()))
  205. }
  206. return buffer, err
  207. }
  208. if *withinPaddingBuffers || w.trafficState.NumberOfPacketToFilter > 0 {
  209. mb2 := make(buf.MultiBuffer, 0, len(buffer))
  210. for _, b := range buffer {
  211. newbuffer := XtlsUnpadding(b, w.trafficState, w.isUplink, w.ctx)
  212. if newbuffer.Len() > 0 {
  213. mb2 = append(mb2, newbuffer)
  214. }
  215. }
  216. buffer = mb2
  217. if *remainingContent > 0 || *remainingPadding > 0 || *currentCommand == 0 {
  218. *withinPaddingBuffers = true
  219. } else if *currentCommand == 1 {
  220. *withinPaddingBuffers = false
  221. } else if *currentCommand == 2 {
  222. *withinPaddingBuffers = false
  223. *switchToDirectCopy = true
  224. } else {
  225. errors.LogDebug(w.ctx, "XtlsRead unknown command ", *currentCommand, buffer.Len())
  226. }
  227. }
  228. if w.trafficState.NumberOfPacketToFilter > 0 {
  229. XtlsFilterTls(buffer, w.trafficState, w.ctx)
  230. }
  231. if *switchToDirectCopy {
  232. // XTLS Vision processes TLS-like conn's input and rawInput
  233. if inputBuffer, err := buf.ReadFrom(w.input); err == nil && !inputBuffer.IsEmpty() {
  234. buffer, _ = buf.MergeMulti(buffer, inputBuffer)
  235. }
  236. if rawInputBuffer, err := buf.ReadFrom(w.rawInput); err == nil && !rawInputBuffer.IsEmpty() {
  237. buffer, _ = buf.MergeMulti(buffer, rawInputBuffer)
  238. }
  239. *w.input = bytes.Reader{} // release memory
  240. w.input = nil
  241. *w.rawInput = bytes.Buffer{} // release memory
  242. w.rawInput = nil
  243. if inbound := session.InboundFromContext(w.ctx); inbound != nil && inbound.Conn != nil {
  244. // if w.isUplink && inbound.CanSpliceCopy == 2 { // TODO: enable uplink splice
  245. // inbound.CanSpliceCopy = 1
  246. // }
  247. if !w.isUplink && w.ob != nil && w.ob.CanSpliceCopy == 2 { // ob need to be passed in due to context can have more than one ob
  248. w.ob.CanSpliceCopy = 1
  249. }
  250. }
  251. readerConn, readCounter, _ := UnwrapRawConn(w.conn)
  252. w.directReadCounter = readCounter
  253. w.Reader = buf.NewReader(readerConn)
  254. }
  255. return buffer, err
  256. }
  257. // VisionWriter is used to write xtls vision protocol
  258. // Note Vision probably only make sense as the inner most layer of writer, since it need assess traffic state from origin proxy traffic
  259. type VisionWriter struct {
  260. buf.Writer
  261. trafficState *TrafficState
  262. ctx context.Context
  263. isUplink bool
  264. conn net.Conn
  265. ob *session.Outbound
  266. // internal
  267. writeOnceUserUUID []byte
  268. directWriteCounter stats.Counter
  269. testseed []uint32
  270. }
  271. func NewVisionWriter(writer buf.Writer, trafficState *TrafficState, isUplink bool, ctx context.Context, conn net.Conn, ob *session.Outbound, testseed []uint32) *VisionWriter {
  272. w := make([]byte, len(trafficState.UserUUID))
  273. copy(w, trafficState.UserUUID)
  274. if len(testseed) < 4 {
  275. testseed = []uint32{900, 500, 900, 256}
  276. }
  277. return &VisionWriter{
  278. Writer: writer,
  279. trafficState: trafficState,
  280. ctx: ctx,
  281. writeOnceUserUUID: w,
  282. isUplink: isUplink,
  283. conn: conn,
  284. ob: ob,
  285. testseed: testseed,
  286. }
  287. }
  288. func (w *VisionWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
  289. var isPadding *bool
  290. var switchToDirectCopy *bool
  291. var spliceReadyInbound *session.Inbound
  292. if w.isUplink {
  293. isPadding = &w.trafficState.Outbound.IsPadding
  294. switchToDirectCopy = &w.trafficState.Outbound.UplinkWriterDirectCopy
  295. } else {
  296. isPadding = &w.trafficState.Inbound.IsPadding
  297. switchToDirectCopy = &w.trafficState.Inbound.DownlinkWriterDirectCopy
  298. }
  299. if *switchToDirectCopy {
  300. if inbound := session.InboundFromContext(w.ctx); inbound != nil {
  301. if !w.isUplink && inbound.CanSpliceCopy == 2 {
  302. spliceReadyInbound = inbound
  303. }
  304. // if w.isUplink && w.ob != nil && w.ob.CanSpliceCopy == 2 { // TODO: enable uplink splice
  305. // w.ob.CanSpliceCopy = 1
  306. // }
  307. }
  308. rawConn, _, writerCounter := UnwrapRawConn(w.conn)
  309. w.Writer = buf.NewWriter(rawConn)
  310. w.directWriteCounter = writerCounter
  311. *switchToDirectCopy = false
  312. }
  313. if !mb.IsEmpty() && w.directWriteCounter != nil {
  314. w.directWriteCounter.Add(int64(mb.Len()))
  315. }
  316. if w.trafficState.NumberOfPacketToFilter > 0 {
  317. XtlsFilterTls(mb, w.trafficState, w.ctx)
  318. }
  319. if *isPadding {
  320. if len(mb) == 1 && mb[0] == nil {
  321. mb[0] = XtlsPadding(nil, CommandPaddingContinue, &w.writeOnceUserUUID, true, w.ctx, w.testseed) // we do a long padding to hide vless header
  322. } else {
  323. isComplete := IsCompleteRecord(mb)
  324. mb = ReshapeMultiBuffer(w.ctx, mb)
  325. longPadding := w.trafficState.IsTLS
  326. for i, b := range mb {
  327. if w.trafficState.IsTLS && b.Len() >= 6 && bytes.Equal(TlsApplicationDataStart, b.BytesTo(3)) && isComplete {
  328. if w.trafficState.EnableXtls {
  329. *switchToDirectCopy = true
  330. }
  331. var command byte = CommandPaddingContinue
  332. if i == len(mb)-1 {
  333. command = CommandPaddingEnd
  334. if w.trafficState.EnableXtls {
  335. command = CommandPaddingDirect
  336. }
  337. }
  338. mb[i] = XtlsPadding(b, command, &w.writeOnceUserUUID, true, w.ctx, w.testseed)
  339. *isPadding = false // padding going to end
  340. longPadding = false
  341. continue
  342. } else if !w.trafficState.IsTLS12orAbove && w.trafficState.NumberOfPacketToFilter <= 1 { // For compatibility with earlier vision receiver, we finish padding 1 packet early
  343. *isPadding = false
  344. mb[i] = XtlsPadding(b, CommandPaddingEnd, &w.writeOnceUserUUID, longPadding, w.ctx, w.testseed)
  345. break
  346. }
  347. var command byte = CommandPaddingContinue
  348. if i == len(mb)-1 && !*isPadding {
  349. command = CommandPaddingEnd
  350. if w.trafficState.EnableXtls {
  351. command = CommandPaddingDirect
  352. }
  353. }
  354. mb[i] = XtlsPadding(b, command, &w.writeOnceUserUUID, longPadding, w.ctx, w.testseed)
  355. }
  356. }
  357. }
  358. if err := w.Writer.WriteMultiBuffer(mb); err != nil {
  359. return err
  360. }
  361. if spliceReadyInbound != nil && spliceReadyInbound.CanSpliceCopy == 2 {
  362. // Enable splice only after this write has completed to avoid racing
  363. // concurrent direct writes to the same TCP connection.
  364. spliceReadyInbound.CanSpliceCopy = 1
  365. }
  366. return nil
  367. }
  368. // IsCompleteRecord Is complete tls data record
  369. func IsCompleteRecord(buffer buf.MultiBuffer) bool {
  370. b := make([]byte, buffer.Len())
  371. if buffer.Copy(b) != int(buffer.Len()) {
  372. panic("impossible bytes allocation")
  373. }
  374. var headerLen int = 5
  375. var recordLen int
  376. totalLen := len(b)
  377. i := 0
  378. for i < totalLen {
  379. // record header: 0x17 0x3 0x3 + 2 bytes length
  380. if headerLen > 0 {
  381. data := b[i]
  382. i++
  383. switch headerLen {
  384. case 5:
  385. if data != 0x17 {
  386. return false
  387. }
  388. case 4:
  389. if data != 0x03 {
  390. return false
  391. }
  392. case 3:
  393. if data != 0x03 {
  394. return false
  395. }
  396. case 2:
  397. recordLen = int(data) << 8
  398. case 1:
  399. recordLen = recordLen | int(data)
  400. }
  401. headerLen--
  402. } else if recordLen > 0 {
  403. remaining := totalLen - i
  404. if remaining < recordLen {
  405. return false
  406. } else {
  407. i += recordLen
  408. recordLen = 0
  409. headerLen = 5
  410. }
  411. } else {
  412. return false
  413. }
  414. }
  415. if headerLen == 5 && recordLen == 0 {
  416. return true
  417. }
  418. return false
  419. }
  420. // ReshapeMultiBuffer prepare multi buffer for padding structure (max 21 bytes)
  421. func ReshapeMultiBuffer(ctx context.Context, buffer buf.MultiBuffer) buf.MultiBuffer {
  422. needReshape := 0
  423. for _, b := range buffer {
  424. if b.Len() >= buf.Size-21 {
  425. needReshape += 1
  426. }
  427. }
  428. if needReshape == 0 {
  429. return buffer
  430. }
  431. mb2 := make(buf.MultiBuffer, 0, len(buffer)+needReshape)
  432. toPrint := ""
  433. for i, buffer1 := range buffer {
  434. if buffer1.Len() >= buf.Size-21 {
  435. index := int32(bytes.LastIndex(buffer1.Bytes(), TlsApplicationDataStart))
  436. if index < 21 || index > buf.Size-21 {
  437. index = buf.Size / 2
  438. }
  439. buffer2 := buf.New()
  440. buffer2.Write(buffer1.BytesFrom(index))
  441. buffer1.Resize(0, index)
  442. mb2 = append(mb2, buffer1, buffer2)
  443. toPrint += " " + strconv.Itoa(int(buffer1.Len())) + " " + strconv.Itoa(int(buffer2.Len()))
  444. } else {
  445. mb2 = append(mb2, buffer1)
  446. toPrint += " " + strconv.Itoa(int(buffer1.Len()))
  447. }
  448. buffer[i] = nil
  449. }
  450. buffer = buffer[:0]
  451. errors.LogDebug(ctx, "ReshapeMultiBuffer ", toPrint)
  452. return mb2
  453. }
  454. // XtlsPadding add padding to eliminate length signature during tls handshake
  455. func XtlsPadding(b *buf.Buffer, command byte, userUUID *[]byte, longPadding bool, ctx context.Context, testseed []uint32) *buf.Buffer {
  456. var contentLen int32 = 0
  457. var paddingLen int32 = 0
  458. if b != nil {
  459. contentLen = b.Len()
  460. }
  461. if contentLen < int32(testseed[0]) && longPadding {
  462. l, err := rand.Int(rand.Reader, big.NewInt(int64(testseed[1])))
  463. if err != nil {
  464. errors.LogDebugInner(ctx, err, "failed to generate padding")
  465. }
  466. paddingLen = int32(l.Int64()) + int32(testseed[2]) - contentLen
  467. } else {
  468. l, err := rand.Int(rand.Reader, big.NewInt(int64(testseed[3])))
  469. if err != nil {
  470. errors.LogDebugInner(ctx, err, "failed to generate padding")
  471. }
  472. paddingLen = int32(l.Int64())
  473. }
  474. if paddingLen > buf.Size-21-contentLen {
  475. paddingLen = buf.Size - 21 - contentLen
  476. }
  477. newbuffer := buf.New()
  478. if userUUID != nil {
  479. newbuffer.Write(*userUUID)
  480. *userUUID = nil
  481. }
  482. newbuffer.Write([]byte{command, byte(contentLen >> 8), byte(contentLen), byte(paddingLen >> 8), byte(paddingLen)})
  483. if b != nil {
  484. newbuffer.Write(b.Bytes())
  485. b.Release()
  486. b = nil
  487. }
  488. newbuffer.Extend(paddingLen)
  489. errors.LogDebug(ctx, "XtlsPadding ", contentLen, " ", paddingLen, " ", command)
  490. return newbuffer
  491. }
  492. // XtlsUnpadding remove padding and parse command
  493. func XtlsUnpadding(b *buf.Buffer, s *TrafficState, isUplink bool, ctx context.Context) *buf.Buffer {
  494. var remainingCommand *int32
  495. var remainingContent *int32
  496. var remainingPadding *int32
  497. var currentCommand *int
  498. if isUplink {
  499. remainingCommand = &s.Inbound.RemainingCommand
  500. remainingContent = &s.Inbound.RemainingContent
  501. remainingPadding = &s.Inbound.RemainingPadding
  502. currentCommand = &s.Inbound.CurrentCommand
  503. } else {
  504. remainingCommand = &s.Outbound.RemainingCommand
  505. remainingContent = &s.Outbound.RemainingContent
  506. remainingPadding = &s.Outbound.RemainingPadding
  507. currentCommand = &s.Outbound.CurrentCommand
  508. }
  509. if *remainingCommand == -1 && *remainingContent == -1 && *remainingPadding == -1 { // initial state
  510. if b.Len() >= 21 && bytes.Equal(s.UserUUID, b.BytesTo(16)) {
  511. b.Advance(16)
  512. *remainingCommand = 5
  513. } else {
  514. return b
  515. }
  516. }
  517. newbuffer := buf.New()
  518. for b.Len() > 0 {
  519. if *remainingCommand > 0 {
  520. data, err := b.ReadByte()
  521. if err != nil {
  522. return newbuffer
  523. }
  524. switch *remainingCommand {
  525. case 5:
  526. *currentCommand = int(data)
  527. case 4:
  528. *remainingContent = int32(data) << 8
  529. case 3:
  530. *remainingContent = *remainingContent | int32(data)
  531. case 2:
  532. *remainingPadding = int32(data) << 8
  533. case 1:
  534. *remainingPadding = *remainingPadding | int32(data)
  535. errors.LogDebug(ctx, "Xtls Unpadding new block, content ", *remainingContent, " padding ", *remainingPadding, " command ", *currentCommand)
  536. }
  537. *remainingCommand--
  538. } else if *remainingContent > 0 {
  539. len := *remainingContent
  540. if b.Len() < len {
  541. len = b.Len()
  542. }
  543. data, err := b.ReadBytes(len)
  544. if err != nil {
  545. return newbuffer
  546. }
  547. newbuffer.Write(data)
  548. *remainingContent -= len
  549. } else { // remainingPadding > 0
  550. len := *remainingPadding
  551. if b.Len() < len {
  552. len = b.Len()
  553. }
  554. b.Advance(len)
  555. *remainingPadding -= len
  556. }
  557. if *remainingCommand <= 0 && *remainingContent <= 0 && *remainingPadding <= 0 { // this block done
  558. if *currentCommand == 0 {
  559. *remainingCommand = 5
  560. } else {
  561. *remainingCommand = -1 // set to initial state
  562. *remainingContent = -1
  563. *remainingPadding = -1
  564. if b.Len() > 0 { // shouldn't happen
  565. newbuffer.Write(b.Bytes())
  566. }
  567. break
  568. }
  569. }
  570. }
  571. b.Release()
  572. b = nil
  573. return newbuffer
  574. }
  575. // XtlsFilterTls filter and recognize tls 1.3 and other info
  576. func XtlsFilterTls(buffer buf.MultiBuffer, trafficState *TrafficState, ctx context.Context) {
  577. for _, b := range buffer {
  578. if b == nil {
  579. continue
  580. }
  581. trafficState.NumberOfPacketToFilter--
  582. if b.Len() >= 6 {
  583. startsBytes := b.BytesTo(6)
  584. if bytes.Equal(TlsServerHandShakeStart, startsBytes[:3]) && startsBytes[5] == TlsHandshakeTypeServerHello {
  585. trafficState.RemainingServerHello = (int32(startsBytes[3])<<8 | int32(startsBytes[4])) + 5
  586. trafficState.IsTLS12orAbove = true
  587. trafficState.IsTLS = true
  588. if b.Len() >= 79 && trafficState.RemainingServerHello >= 79 {
  589. sessionIdLen := int32(b.Byte(43))
  590. cipherSuite := b.BytesRange(43+sessionIdLen+1, 43+sessionIdLen+3)
  591. trafficState.Cipher = uint16(cipherSuite[0])<<8 | uint16(cipherSuite[1])
  592. } else {
  593. errors.LogDebug(ctx, "XtlsFilterTls short server hello, tls 1.2 or older? ", b.Len(), " ", trafficState.RemainingServerHello)
  594. }
  595. } else if bytes.Equal(TlsClientHandShakeStart, startsBytes[:2]) && startsBytes[5] == TlsHandshakeTypeClientHello {
  596. trafficState.IsTLS = true
  597. errors.LogDebug(ctx, "XtlsFilterTls found tls client hello! ", buffer.Len())
  598. }
  599. }
  600. if trafficState.RemainingServerHello > 0 {
  601. end := trafficState.RemainingServerHello
  602. if end > b.Len() {
  603. end = b.Len()
  604. }
  605. trafficState.RemainingServerHello -= b.Len()
  606. if bytes.Contains(b.BytesTo(end), Tls13SupportedVersions) {
  607. v, ok := Tls13CipherSuiteDic[trafficState.Cipher]
  608. if !ok {
  609. v = "Old cipher: " + strconv.FormatUint(uint64(trafficState.Cipher), 16)
  610. } else if v != "TLS_AES_128_CCM_8_SHA256" {
  611. trafficState.EnableXtls = true
  612. }
  613. errors.LogDebug(ctx, "XtlsFilterTls found tls 1.3! ", b.Len(), " ", v)
  614. trafficState.NumberOfPacketToFilter = 0
  615. return
  616. } else if trafficState.RemainingServerHello <= 0 {
  617. errors.LogDebug(ctx, "XtlsFilterTls found tls 1.2! ", b.Len())
  618. trafficState.NumberOfPacketToFilter = 0
  619. return
  620. }
  621. errors.LogDebug(ctx, "XtlsFilterTls inconclusive server hello ", b.Len(), " ", trafficState.RemainingServerHello)
  622. }
  623. if trafficState.NumberOfPacketToFilter <= 0 {
  624. errors.LogDebug(ctx, "XtlsFilterTls stop filtering", buffer.Len())
  625. }
  626. }
  627. }
  628. // UnwrapRawConn support unwrap encryption, stats, mask wrappers, tls, utls, reality, proxyproto, uds-wrapper conn and get raw tcp/uds conn from it
  629. func UnwrapRawConn(conn net.Conn) (net.Conn, stats.Counter, stats.Counter) {
  630. var readCounter, writerCounter stats.Counter
  631. if conn != nil {
  632. isEncryption := false
  633. if commonConn, ok := conn.(*encryption.CommonConn); ok {
  634. conn = commonConn.Conn
  635. isEncryption = true
  636. }
  637. if xorConn, ok := conn.(*encryption.XorConn); ok {
  638. return xorConn, nil, nil // full-random xorConn should not be penetrated
  639. }
  640. if statConn, ok := conn.(*stat.CounterConnection); ok {
  641. conn = statConn.Connection
  642. readCounter = statConn.ReadCounter
  643. writerCounter = statConn.WriteCounter
  644. }
  645. if !isEncryption { // avoids double penetration
  646. if xc, ok := conn.(*tls.Conn); ok {
  647. conn = xc.NetConn()
  648. } else if utlsConn, ok := conn.(*tls.UConn); ok {
  649. conn = utlsConn.NetConn()
  650. } else if realityConn, ok := conn.(*reality.Conn); ok {
  651. conn = realityConn.NetConn()
  652. } else if realityUConn, ok := conn.(*reality.UConn); ok {
  653. conn = realityUConn.NetConn()
  654. }
  655. }
  656. conn = finalmask.UnwrapTcpMask(conn)
  657. if pc, ok := conn.(*proxyproto.Conn); ok {
  658. conn = pc.Raw()
  659. // 8192 > 4096, there is no need to process pc's bufReader
  660. }
  661. if uc, ok := conn.(*internet.UnixConnWrapper); ok {
  662. conn = uc.UnixConn
  663. }
  664. }
  665. return conn, readCounter, writerCounter
  666. }
  667. // CopyRawConnIfExist use the most efficient copy method.
  668. // - If caller don't want to turn on splice, do not pass in both reader conn and writer conn
  669. // - writer are from *transport.Link
  670. func CopyRawConnIfExist(ctx context.Context, readerConn net.Conn, writerConn net.Conn, writer buf.Writer, timer *signal.ActivityTimer, inTimer *signal.ActivityTimer) error {
  671. readerConn, readCounter, _ := UnwrapRawConn(readerConn)
  672. writerConn, _, writeCounter := UnwrapRawConn(writerConn)
  673. reader := buf.NewReader(readerConn)
  674. if runtime.GOOS != "linux" && runtime.GOOS != "android" {
  675. return readV(ctx, reader, writer, timer, readCounter)
  676. }
  677. tc, ok := writerConn.(*net.TCPConn)
  678. if !ok || readerConn == nil || writerConn == nil {
  679. return readV(ctx, reader, writer, timer, readCounter)
  680. }
  681. inbound := session.InboundFromContext(ctx)
  682. if inbound == nil || inbound.CanSpliceCopy == 3 {
  683. return readV(ctx, reader, writer, timer, readCounter)
  684. }
  685. outbounds := session.OutboundsFromContext(ctx)
  686. if len(outbounds) == 0 {
  687. return readV(ctx, reader, writer, timer, readCounter)
  688. }
  689. for _, ob := range outbounds {
  690. if ob.CanSpliceCopy == 3 {
  691. return readV(ctx, reader, writer, timer, readCounter)
  692. }
  693. }
  694. for {
  695. inbound := session.InboundFromContext(ctx)
  696. outbounds := session.OutboundsFromContext(ctx)
  697. var splice = inbound.CanSpliceCopy == 1
  698. for _, ob := range outbounds {
  699. if ob.CanSpliceCopy != 1 {
  700. splice = false
  701. }
  702. }
  703. if splice {
  704. errors.LogDebug(ctx, "CopyRawConn splice")
  705. statWriter, _ := writer.(*dispatcher.SizeStatWriter)
  706. //runtime.Gosched() // necessary
  707. timer.SetTimeout(24 * time.Hour) // prevent leak, just in case
  708. if inTimer != nil {
  709. inTimer.SetTimeout(24 * time.Hour)
  710. }
  711. w, err := tc.ReadFrom(readerConn)
  712. if readCounter != nil {
  713. readCounter.Add(w) // outbound stats
  714. }
  715. if writeCounter != nil {
  716. writeCounter.Add(w) // inbound stats
  717. }
  718. if statWriter != nil {
  719. statWriter.Counter.Add(w) // user stats
  720. }
  721. if err != nil && errors.Cause(err) != io.EOF {
  722. return err
  723. }
  724. return nil
  725. }
  726. buffer, err := reader.ReadMultiBuffer()
  727. if !buffer.IsEmpty() {
  728. if readCounter != nil {
  729. readCounter.Add(int64(buffer.Len()))
  730. }
  731. timer.Update()
  732. if werr := writer.WriteMultiBuffer(buffer); werr != nil {
  733. return werr
  734. }
  735. }
  736. if err != nil {
  737. if errors.Cause(err) == io.EOF {
  738. return nil
  739. }
  740. return err
  741. }
  742. }
  743. }
  744. func readV(ctx context.Context, reader buf.Reader, writer buf.Writer, timer signal.ActivityUpdater, readCounter stats.Counter) error {
  745. errors.LogDebug(ctx, "CopyRawConn (maybe) readv")
  746. if err := buf.Copy(reader, writer, buf.UpdateActivity(timer), buf.AddToStatCounter(readCounter)); err != nil {
  747. return errors.New("failed to process response").Base(err)
  748. }
  749. return nil
  750. }
  751. func IsRAWTransportWithoutSecurity(conn stat.Connection) bool {
  752. iConn := stat.TryUnwrapStatsConn(conn)
  753. iConn = finalmask.UnwrapTcpMask(iConn)
  754. _, ok1 := iConn.(*proxyproto.Conn)
  755. _, ok2 := iConn.(*net.TCPConn)
  756. _, ok3 := iConn.(*internet.UnixConnWrapper)
  757. return ok1 || ok2 || ok3
  758. }