proxy.go 23 KB

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