proxy.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. "github.com/pires/go-proxyproto"
  16. "github.com/xtls/xray-core/common/buf"
  17. "github.com/xtls/xray-core/common/errors"
  18. "github.com/xtls/xray-core/common/net"
  19. "github.com/xtls/xray-core/common/protocol"
  20. "github.com/xtls/xray-core/common/session"
  21. "github.com/xtls/xray-core/common/signal"
  22. "github.com/xtls/xray-core/features/routing"
  23. "github.com/xtls/xray-core/features/stats"
  24. "github.com/xtls/xray-core/transport"
  25. "github.com/xtls/xray-core/transport/internet"
  26. "github.com/xtls/xray-core/transport/internet/reality"
  27. "github.com/xtls/xray-core/transport/internet/stat"
  28. "github.com/xtls/xray-core/transport/internet/tls"
  29. )
  30. var (
  31. Tls13SupportedVersions = []byte{0x00, 0x2b, 0x00, 0x02, 0x03, 0x04}
  32. TlsClientHandShakeStart = []byte{0x16, 0x03}
  33. TlsServerHandShakeStart = []byte{0x16, 0x03, 0x03}
  34. TlsApplicationDataStart = []byte{0x17, 0x03, 0x03}
  35. Tls13CipherSuiteDic = map[uint16]string{
  36. 0x1301: "TLS_AES_128_GCM_SHA256",
  37. 0x1302: "TLS_AES_256_GCM_SHA384",
  38. 0x1303: "TLS_CHACHA20_POLY1305_SHA256",
  39. 0x1304: "TLS_AES_128_CCM_SHA256",
  40. 0x1305: "TLS_AES_128_CCM_8_SHA256",
  41. }
  42. )
  43. const (
  44. TlsHandshakeTypeClientHello byte = 0x01
  45. TlsHandshakeTypeServerHello byte = 0x02
  46. CommandPaddingContinue byte = 0x00
  47. CommandPaddingEnd byte = 0x01
  48. CommandPaddingDirect byte = 0x02
  49. )
  50. // An Inbound processes inbound connections.
  51. type Inbound interface {
  52. // Network returns a list of networks that this inbound supports. Connections with not-supported networks will not be passed into Process().
  53. Network() []net.Network
  54. // Process processes a connection of given network. If necessary, the Inbound can dispatch the connection to an Outbound.
  55. Process(context.Context, net.Network, stat.Connection, routing.Dispatcher) error
  56. }
  57. // An Outbound process outbound connections.
  58. type Outbound interface {
  59. // Process processes the given connection. The given dialer may be used to dial a system outbound connection.
  60. Process(context.Context, *transport.Link, internet.Dialer) error
  61. }
  62. // UserManager is the interface for Inbounds and Outbounds that can manage their users.
  63. type UserManager interface {
  64. // AddUser adds a new user.
  65. AddUser(context.Context, *protocol.MemoryUser) error
  66. // RemoveUser removes a user by email.
  67. RemoveUser(context.Context, string) error
  68. }
  69. type GetInbound interface {
  70. GetInbound() Inbound
  71. }
  72. type GetOutbound interface {
  73. GetOutbound() Outbound
  74. }
  75. // TrafficState is used to track uplink and downlink of one connection
  76. // It is used by XTLS to determine if switch to raw copy mode, It is used by Vision to calculate padding
  77. type TrafficState struct {
  78. UserUUID []byte
  79. NumberOfPacketToFilter int
  80. EnableXtls bool
  81. IsTLS12orAbove bool
  82. IsTLS bool
  83. Cipher uint16
  84. RemainingServerHello int32
  85. // reader link state
  86. WithinPaddingBuffers bool
  87. ReaderSwitchToDirectCopy bool
  88. RemainingCommand int32
  89. RemainingContent int32
  90. RemainingPadding int32
  91. CurrentCommand int
  92. // write link state
  93. IsPadding bool
  94. WriterSwitchToDirectCopy bool
  95. }
  96. func NewTrafficState(userUUID []byte) *TrafficState {
  97. return &TrafficState{
  98. UserUUID: userUUID,
  99. NumberOfPacketToFilter: 8,
  100. EnableXtls: false,
  101. IsTLS12orAbove: false,
  102. IsTLS: false,
  103. Cipher: 0,
  104. RemainingServerHello: -1,
  105. WithinPaddingBuffers: true,
  106. ReaderSwitchToDirectCopy: false,
  107. RemainingCommand: -1,
  108. RemainingContent: -1,
  109. RemainingPadding: -1,
  110. CurrentCommand: 0,
  111. IsPadding: true,
  112. WriterSwitchToDirectCopy: false,
  113. }
  114. }
  115. // VisionReader is used to read xtls vision protocol
  116. // Note Vision probably only make sense as the inner most layer of reader, since it need assess traffic state from origin proxy traffic
  117. type VisionReader struct {
  118. buf.Reader
  119. trafficState *TrafficState
  120. ctx context.Context
  121. }
  122. func NewVisionReader(reader buf.Reader, state *TrafficState, context context.Context) *VisionReader {
  123. return &VisionReader{
  124. Reader: reader,
  125. trafficState: state,
  126. ctx: context,
  127. }
  128. }
  129. func (w *VisionReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  130. buffer, err := w.Reader.ReadMultiBuffer()
  131. if !buffer.IsEmpty() {
  132. if w.trafficState.WithinPaddingBuffers || w.trafficState.NumberOfPacketToFilter > 0 {
  133. mb2 := make(buf.MultiBuffer, 0, len(buffer))
  134. for _, b := range buffer {
  135. newbuffer := XtlsUnpadding(b, w.trafficState, w.ctx)
  136. if newbuffer.Len() > 0 {
  137. mb2 = append(mb2, newbuffer)
  138. }
  139. }
  140. buffer = mb2
  141. if w.trafficState.RemainingContent > 0 || w.trafficState.RemainingPadding > 0 || w.trafficState.CurrentCommand == 0 {
  142. w.trafficState.WithinPaddingBuffers = true
  143. } else if w.trafficState.CurrentCommand == 1 {
  144. w.trafficState.WithinPaddingBuffers = false
  145. } else if w.trafficState.CurrentCommand == 2 {
  146. w.trafficState.WithinPaddingBuffers = false
  147. w.trafficState.ReaderSwitchToDirectCopy = true
  148. } else {
  149. newError("XtlsRead unknown command ", w.trafficState.CurrentCommand, buffer.Len()).WriteToLog(session.ExportIDToError(w.ctx))
  150. }
  151. }
  152. if w.trafficState.NumberOfPacketToFilter > 0 {
  153. XtlsFilterTls(buffer, w.trafficState, w.ctx)
  154. }
  155. }
  156. return buffer, err
  157. }
  158. // VisionWriter is used to write xtls vision protocol
  159. // Note Vision probably only make sense as the inner most layer of writer, since it need assess traffic state from origin proxy traffic
  160. type VisionWriter struct {
  161. buf.Writer
  162. trafficState *TrafficState
  163. ctx context.Context
  164. writeOnceUserUUID []byte
  165. }
  166. func NewVisionWriter(writer buf.Writer, state *TrafficState, context context.Context) *VisionWriter {
  167. w := make([]byte, len(state.UserUUID))
  168. copy(w, state.UserUUID)
  169. return &VisionWriter{
  170. Writer: writer,
  171. trafficState: state,
  172. ctx: context,
  173. writeOnceUserUUID: w,
  174. }
  175. }
  176. func (w *VisionWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
  177. if w.trafficState.NumberOfPacketToFilter > 0 {
  178. XtlsFilterTls(mb, w.trafficState, w.ctx)
  179. }
  180. if w.trafficState.IsPadding {
  181. if len(mb) == 1 && mb[0] == nil {
  182. mb[0] = XtlsPadding(nil, CommandPaddingContinue, &w.writeOnceUserUUID, true, w.ctx) // we do a long padding to hide vless header
  183. return w.Writer.WriteMultiBuffer(mb)
  184. }
  185. mb = ReshapeMultiBuffer(w.ctx, mb)
  186. longPadding := w.trafficState.IsTLS
  187. for i, b := range mb {
  188. if w.trafficState.IsTLS && b.Len() >= 6 && bytes.Equal(TlsApplicationDataStart, b.BytesTo(3)) {
  189. if w.trafficState.EnableXtls {
  190. w.trafficState.WriterSwitchToDirectCopy = true
  191. }
  192. var command byte = CommandPaddingContinue
  193. if i == len(mb) - 1 {
  194. command = CommandPaddingEnd
  195. if w.trafficState.EnableXtls {
  196. command = CommandPaddingDirect
  197. }
  198. }
  199. mb[i] = XtlsPadding(b, command, &w.writeOnceUserUUID, true, w.ctx)
  200. w.trafficState.IsPadding = false // padding going to end
  201. longPadding = false
  202. continue
  203. } else if !w.trafficState.IsTLS12orAbove && w.trafficState.NumberOfPacketToFilter <= 1 { // For compatibility with earlier vision receiver, we finish padding 1 packet early
  204. w.trafficState.IsPadding = false
  205. mb[i] = XtlsPadding(b, CommandPaddingEnd, &w.writeOnceUserUUID, longPadding, w.ctx)
  206. break
  207. }
  208. var command byte = CommandPaddingContinue
  209. if i == len(mb) - 1 && !w.trafficState.IsPadding {
  210. command = CommandPaddingEnd
  211. if w.trafficState.EnableXtls {
  212. command = CommandPaddingDirect
  213. }
  214. }
  215. mb[i] = XtlsPadding(b, command, &w.writeOnceUserUUID, longPadding, w.ctx)
  216. }
  217. }
  218. return w.Writer.WriteMultiBuffer(mb)
  219. }
  220. // ReshapeMultiBuffer prepare multi buffer for padding stucture (max 21 bytes)
  221. func ReshapeMultiBuffer(ctx context.Context, buffer buf.MultiBuffer) buf.MultiBuffer {
  222. needReshape := 0
  223. for _, b := range buffer {
  224. if b.Len() >= buf.Size-21 {
  225. needReshape += 1
  226. }
  227. }
  228. if needReshape == 0 {
  229. return buffer
  230. }
  231. mb2 := make(buf.MultiBuffer, 0, len(buffer)+needReshape)
  232. toPrint := ""
  233. for i, buffer1 := range buffer {
  234. if buffer1.Len() >= buf.Size-21 {
  235. index := int32(bytes.LastIndex(buffer1.Bytes(), TlsApplicationDataStart))
  236. if index < 21 || index > buf.Size-21 {
  237. index = buf.Size / 2
  238. }
  239. buffer2 := buf.New()
  240. buffer2.Write(buffer1.BytesFrom(index))
  241. buffer1.Resize(0, index)
  242. mb2 = append(mb2, buffer1, buffer2)
  243. toPrint += " " + strconv.Itoa(int(buffer1.Len())) + " " + strconv.Itoa(int(buffer2.Len()))
  244. } else {
  245. mb2 = append(mb2, buffer1)
  246. toPrint += " " + strconv.Itoa(int(buffer1.Len()))
  247. }
  248. buffer[i] = nil
  249. }
  250. buffer = buffer[:0]
  251. newError("ReshapeMultiBuffer ", toPrint).WriteToLog(session.ExportIDToError(ctx))
  252. return mb2
  253. }
  254. // XtlsPadding add padding to eliminate length siganature during tls handshake
  255. func XtlsPadding(b *buf.Buffer, command byte, userUUID *[]byte, longPadding bool, ctx context.Context) *buf.Buffer {
  256. var contentLen int32 = 0
  257. var paddingLen int32 = 0
  258. if b != nil {
  259. contentLen = b.Len()
  260. }
  261. if contentLen < 900 && longPadding {
  262. l, err := rand.Int(rand.Reader, big.NewInt(500))
  263. if err != nil {
  264. newError("failed to generate padding").Base(err).WriteToLog(session.ExportIDToError(ctx))
  265. }
  266. paddingLen = int32(l.Int64()) + 900 - contentLen
  267. } else {
  268. l, err := rand.Int(rand.Reader, big.NewInt(256))
  269. if err != nil {
  270. newError("failed to generate padding").Base(err).WriteToLog(session.ExportIDToError(ctx))
  271. }
  272. paddingLen = int32(l.Int64())
  273. }
  274. if paddingLen > buf.Size-21-contentLen {
  275. paddingLen = buf.Size - 21 - contentLen
  276. }
  277. newbuffer := buf.New()
  278. if userUUID != nil {
  279. newbuffer.Write(*userUUID)
  280. *userUUID = nil
  281. }
  282. newbuffer.Write([]byte{command, byte(contentLen >> 8), byte(contentLen), byte(paddingLen >> 8), byte(paddingLen)})
  283. if b != nil {
  284. newbuffer.Write(b.Bytes())
  285. b.Release()
  286. b = nil
  287. }
  288. newbuffer.Extend(paddingLen)
  289. newError("XtlsPadding ", contentLen, " ", paddingLen, " ", command).WriteToLog(session.ExportIDToError(ctx))
  290. return newbuffer
  291. }
  292. // XtlsUnpadding remove padding and parse command
  293. func XtlsUnpadding(b *buf.Buffer, s *TrafficState, ctx context.Context) *buf.Buffer {
  294. if s.RemainingCommand == -1 && s.RemainingContent == -1 && s.RemainingPadding == -1 { // inital state
  295. if b.Len() >= 21 && bytes.Equal(s.UserUUID, b.BytesTo(16)) {
  296. b.Advance(16)
  297. s.RemainingCommand = 5
  298. } else {
  299. return b
  300. }
  301. }
  302. newbuffer := buf.New()
  303. for b.Len() > 0 {
  304. if s.RemainingCommand > 0 {
  305. data, err := b.ReadByte()
  306. if err != nil {
  307. return newbuffer
  308. }
  309. switch s.RemainingCommand {
  310. case 5:
  311. s.CurrentCommand = int(data)
  312. case 4:
  313. s.RemainingContent = int32(data)<<8
  314. case 3:
  315. s.RemainingContent = s.RemainingContent | int32(data)
  316. case 2:
  317. s.RemainingPadding = int32(data)<<8
  318. case 1:
  319. s.RemainingPadding = s.RemainingPadding | int32(data)
  320. newError("Xtls Unpadding new block, content ", s.RemainingContent, " padding ", s.RemainingPadding, " command ", s.CurrentCommand).WriteToLog(session.ExportIDToError(ctx))
  321. }
  322. s.RemainingCommand--
  323. } else if s.RemainingContent > 0 {
  324. len := s.RemainingContent
  325. if b.Len() < len {
  326. len = b.Len()
  327. }
  328. data, err := b.ReadBytes(len)
  329. if err != nil {
  330. return newbuffer
  331. }
  332. newbuffer.Write(data)
  333. s.RemainingContent -= len
  334. } else { // remainingPadding > 0
  335. len := s.RemainingPadding
  336. if b.Len() < len {
  337. len = b.Len()
  338. }
  339. b.Advance(len)
  340. s.RemainingPadding -= len
  341. }
  342. if s.RemainingCommand <= 0 && s.RemainingContent <= 0 && s.RemainingPadding <= 0 { // this block done
  343. if s.CurrentCommand == 0 {
  344. s.RemainingCommand = 5
  345. } else {
  346. s.RemainingCommand = -1 // set to initial state
  347. s.RemainingContent = -1
  348. s.RemainingPadding = -1
  349. if b.Len() > 0 { // shouldn't happen
  350. newbuffer.Write(b.Bytes())
  351. }
  352. break
  353. }
  354. }
  355. }
  356. b.Release()
  357. b = nil
  358. return newbuffer
  359. }
  360. // XtlsFilterTls filter and recognize tls 1.3 and other info
  361. func XtlsFilterTls(buffer buf.MultiBuffer, trafficState *TrafficState, ctx context.Context) {
  362. for _, b := range buffer {
  363. if b == nil {
  364. continue
  365. }
  366. trafficState.NumberOfPacketToFilter--
  367. if b.Len() >= 6 {
  368. startsBytes := b.BytesTo(6)
  369. if bytes.Equal(TlsServerHandShakeStart, startsBytes[:3]) && startsBytes[5] == TlsHandshakeTypeServerHello {
  370. trafficState.RemainingServerHello = (int32(startsBytes[3])<<8 | int32(startsBytes[4])) + 5
  371. trafficState.IsTLS12orAbove = true
  372. trafficState.IsTLS = true
  373. if b.Len() >= 79 && trafficState.RemainingServerHello >= 79 {
  374. sessionIdLen := int32(b.Byte(43))
  375. cipherSuite := b.BytesRange(43+sessionIdLen+1, 43+sessionIdLen+3)
  376. trafficState.Cipher = uint16(cipherSuite[0])<<8 | uint16(cipherSuite[1])
  377. } else {
  378. newError("XtlsFilterTls short server hello, tls 1.2 or older? ", b.Len(), " ", trafficState.RemainingServerHello).WriteToLog(session.ExportIDToError(ctx))
  379. }
  380. } else if bytes.Equal(TlsClientHandShakeStart, startsBytes[:2]) && startsBytes[5] == TlsHandshakeTypeClientHello {
  381. trafficState.IsTLS = true
  382. newError("XtlsFilterTls found tls client hello! ", buffer.Len()).WriteToLog(session.ExportIDToError(ctx))
  383. }
  384. }
  385. if trafficState.RemainingServerHello > 0 {
  386. end := trafficState.RemainingServerHello
  387. if end > b.Len() {
  388. end = b.Len()
  389. }
  390. trafficState.RemainingServerHello -= b.Len()
  391. if bytes.Contains(b.BytesTo(end), Tls13SupportedVersions) {
  392. v, ok := Tls13CipherSuiteDic[trafficState.Cipher]
  393. if !ok {
  394. v = "Old cipher: " + strconv.FormatUint(uint64(trafficState.Cipher), 16)
  395. } else if v != "TLS_AES_128_CCM_8_SHA256" {
  396. trafficState.EnableXtls = true
  397. }
  398. newError("XtlsFilterTls found tls 1.3! ", b.Len(), " ", v).WriteToLog(session.ExportIDToError(ctx))
  399. trafficState.NumberOfPacketToFilter = 0
  400. return
  401. } else if trafficState.RemainingServerHello <= 0 {
  402. newError("XtlsFilterTls found tls 1.2! ", b.Len()).WriteToLog(session.ExportIDToError(ctx))
  403. trafficState.NumberOfPacketToFilter = 0
  404. return
  405. }
  406. newError("XtlsFilterTls inconclusive server hello ", b.Len(), " ", trafficState.RemainingServerHello).WriteToLog(session.ExportIDToError(ctx))
  407. }
  408. if trafficState.NumberOfPacketToFilter <= 0 {
  409. newError("XtlsFilterTls stop filtering", buffer.Len()).WriteToLog(session.ExportIDToError(ctx))
  410. }
  411. }
  412. }
  413. // UnwrapRawConn support unwrap stats, tls, utls, reality and proxyproto conn and get raw tcp conn from it
  414. func UnwrapRawConn(conn net.Conn) (net.Conn, stats.Counter, stats.Counter) {
  415. var readCounter, writerCounter stats.Counter
  416. if conn != nil {
  417. statConn, ok := conn.(*stat.CounterConnection)
  418. if ok {
  419. conn = statConn.Connection
  420. readCounter = statConn.ReadCounter
  421. writerCounter = statConn.WriteCounter
  422. }
  423. if xc, ok := conn.(*tls.Conn); ok {
  424. conn = xc.NetConn()
  425. } else if utlsConn, ok := conn.(*tls.UConn); ok {
  426. conn = utlsConn.NetConn()
  427. } else if realityConn, ok := conn.(*reality.Conn); ok {
  428. conn = realityConn.NetConn()
  429. } else if realityUConn, ok := conn.(*reality.UConn); ok {
  430. conn = realityUConn.NetConn()
  431. }
  432. if pc, ok := conn.(*proxyproto.Conn); ok {
  433. conn = pc.Raw()
  434. // 8192 > 4096, there is no need to process pc's bufReader
  435. }
  436. }
  437. return conn, readCounter, writerCounter
  438. }
  439. // CopyRawConnIfExist use the most efficient copy method.
  440. // - If caller don't want to turn on splice, do not pass in both reader conn and writer conn
  441. // - writer are from *transport.Link
  442. func CopyRawConnIfExist(ctx context.Context, readerConn net.Conn, writerConn net.Conn, writer buf.Writer, timer signal.ActivityUpdater) error {
  443. readerConn, readCounter, _ := UnwrapRawConn(readerConn)
  444. writerConn, _, writeCounter := UnwrapRawConn(writerConn)
  445. reader := buf.NewReader(readerConn)
  446. if inbound := session.InboundFromContext(ctx); inbound != nil {
  447. if tc, ok := writerConn.(*net.TCPConn); ok && readerConn != nil && writerConn != nil && (runtime.GOOS == "linux" || runtime.GOOS == "android") {
  448. for inbound.CanSpliceCopy != 3 {
  449. if inbound.CanSpliceCopy == 1 {
  450. newError("CopyRawConn splice").WriteToLog(session.ExportIDToError(ctx))
  451. runtime.Gosched() // necessary
  452. w, err := tc.ReadFrom(readerConn)
  453. if readCounter != nil {
  454. readCounter.Add(w)
  455. }
  456. if writeCounter != nil {
  457. writeCounter.Add(w)
  458. }
  459. if err != nil && errors.Cause(err) != io.EOF {
  460. return err
  461. }
  462. return nil
  463. }
  464. buffer, err := reader.ReadMultiBuffer()
  465. if !buffer.IsEmpty() {
  466. if readCounter != nil {
  467. readCounter.Add(int64(buffer.Len()))
  468. }
  469. timer.Update()
  470. if werr := writer.WriteMultiBuffer(buffer); werr != nil {
  471. return werr
  472. }
  473. }
  474. if err != nil {
  475. return err
  476. }
  477. }
  478. }
  479. }
  480. newError("CopyRawConn readv").WriteToLog(session.ExportIDToError(ctx))
  481. if err := buf.Copy(reader, writer, buf.UpdateActivity(timer), buf.AddToStatCounter(readCounter)); err != nil {
  482. return newError("failed to process response").Base(err)
  483. }
  484. return nil
  485. }