outbound.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package outbound
  2. import (
  3. "bytes"
  4. "context"
  5. gotls "crypto/tls"
  6. "encoding/base64"
  7. "reflect"
  8. "strings"
  9. "time"
  10. "unsafe"
  11. utls "github.com/refraction-networking/utls"
  12. "github.com/xtls/xray-core/common"
  13. "github.com/xtls/xray-core/common/buf"
  14. "github.com/xtls/xray-core/common/errors"
  15. "github.com/xtls/xray-core/common/net"
  16. "github.com/xtls/xray-core/common/protocol"
  17. "github.com/xtls/xray-core/common/retry"
  18. "github.com/xtls/xray-core/common/session"
  19. "github.com/xtls/xray-core/common/signal"
  20. "github.com/xtls/xray-core/common/task"
  21. "github.com/xtls/xray-core/common/xudp"
  22. "github.com/xtls/xray-core/core"
  23. "github.com/xtls/xray-core/features/policy"
  24. "github.com/xtls/xray-core/proxy"
  25. "github.com/xtls/xray-core/proxy/vless"
  26. "github.com/xtls/xray-core/proxy/vless/encoding"
  27. "github.com/xtls/xray-core/proxy/vless/encryption"
  28. "github.com/xtls/xray-core/transport"
  29. "github.com/xtls/xray-core/transport/internet"
  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. func init() {
  35. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  36. return New(ctx, config.(*Config))
  37. }))
  38. }
  39. // Handler is an outbound connection handler for VLess protocol.
  40. type Handler struct {
  41. serverList *protocol.ServerList
  42. serverPicker protocol.ServerPicker
  43. policyManager policy.Manager
  44. cone bool
  45. encryption *encryption.ClientInstance
  46. }
  47. // New creates a new VLess outbound handler.
  48. func New(ctx context.Context, config *Config) (*Handler, error) {
  49. serverList := protocol.NewServerList()
  50. for _, rec := range config.Vnext {
  51. s, err := protocol.NewServerSpecFromPB(rec)
  52. if err != nil {
  53. return nil, errors.New("failed to parse server spec").Base(err).AtError()
  54. }
  55. serverList.AddServer(s)
  56. }
  57. v := core.MustFromContext(ctx)
  58. handler := &Handler{
  59. serverList: serverList,
  60. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  61. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  62. cone: ctx.Value("cone").(bool),
  63. }
  64. a := handler.serverPicker.PickServer().PickUser().Account.(*vless.MemoryAccount)
  65. if a.Encryption != "" && a.Encryption != "none" {
  66. s := strings.Split(a.Encryption, ".")
  67. var nfsPKeysBytes [][]byte
  68. for _, r := range s {
  69. b, _ := base64.RawURLEncoding.DecodeString(r)
  70. nfsPKeysBytes = append(nfsPKeysBytes, b)
  71. }
  72. handler.encryption = &encryption.ClientInstance{}
  73. if err := handler.encryption.Init(nfsPKeysBytes, a.XorMode, a.Seconds, a.Padding); err != nil {
  74. return nil, errors.New("failed to use encryption").Base(err).AtError()
  75. }
  76. }
  77. return handler, nil
  78. }
  79. // Process implements proxy.Outbound.Process().
  80. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  81. outbounds := session.OutboundsFromContext(ctx)
  82. ob := outbounds[len(outbounds)-1]
  83. if !ob.Target.IsValid() {
  84. return errors.New("target not specified").AtError()
  85. }
  86. ob.Name = "vless"
  87. var rec *protocol.ServerSpec
  88. var conn stat.Connection
  89. if err := retry.ExponentialBackoff(5, 200).On(func() error {
  90. rec = h.serverPicker.PickServer()
  91. var err error
  92. conn, err = dialer.Dial(ctx, rec.Destination())
  93. if err != nil {
  94. return err
  95. }
  96. return nil
  97. }); err != nil {
  98. return errors.New("failed to find an available destination").Base(err).AtWarning()
  99. }
  100. defer conn.Close()
  101. iConn := conn
  102. if statConn, ok := iConn.(*stat.CounterConnection); ok {
  103. iConn = statConn.Connection
  104. }
  105. target := ob.Target
  106. errors.LogInfo(ctx, "tunneling request to ", target, " via ", rec.Destination().NetAddr())
  107. if h.encryption != nil {
  108. var err error
  109. if conn, err = h.encryption.Handshake(conn); err != nil {
  110. return errors.New("ML-KEM-768 handshake failed").Base(err).AtInfo()
  111. }
  112. }
  113. command := protocol.RequestCommandTCP
  114. if target.Network == net.Network_UDP {
  115. command = protocol.RequestCommandUDP
  116. }
  117. if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" {
  118. command = protocol.RequestCommandMux
  119. }
  120. request := &protocol.RequestHeader{
  121. Version: encoding.Version,
  122. User: rec.PickUser(),
  123. Command: command,
  124. Address: target.Address,
  125. Port: target.Port,
  126. }
  127. account := request.User.Account.(*vless.MemoryAccount)
  128. requestAddons := &proxy.Addons{
  129. Flow: account.Flow,
  130. }
  131. encoding.PopulateSeed(account.Seed, requestAddons)
  132. var input *bytes.Reader
  133. var rawInput *bytes.Buffer
  134. allowUDP443 := false
  135. switch requestAddons.Flow {
  136. case vless.XRV + "-udp443":
  137. allowUDP443 = true
  138. requestAddons.Flow = requestAddons.Flow[:16]
  139. fallthrough
  140. case vless.XRV:
  141. ob.CanSpliceCopy = 2
  142. switch request.Command {
  143. case protocol.RequestCommandUDP:
  144. if !allowUDP443 && request.Port == 443 {
  145. return errors.New("XTLS rejected UDP/443 traffic").AtInfo()
  146. }
  147. case protocol.RequestCommandMux:
  148. fallthrough // let server break Mux connections that contain TCP requests
  149. case protocol.RequestCommandTCP:
  150. var t reflect.Type
  151. var p uintptr
  152. if commonConn, ok := conn.(*encryption.CommonConn); ok {
  153. if _, ok := commonConn.Conn.(*encryption.XorConn); ok || !proxy.IsRAWTransportWithoutSecurity(iConn) {
  154. ob.CanSpliceCopy = 3 // full-random xorConn / non-RAW transport / another securityConn should not be penetrated
  155. }
  156. t = reflect.TypeOf(commonConn).Elem()
  157. p = uintptr(unsafe.Pointer(commonConn))
  158. } else if tlsConn, ok := iConn.(*tls.Conn); ok {
  159. t = reflect.TypeOf(tlsConn.Conn).Elem()
  160. p = uintptr(unsafe.Pointer(tlsConn.Conn))
  161. } else if utlsConn, ok := iConn.(*tls.UConn); ok {
  162. t = reflect.TypeOf(utlsConn.Conn).Elem()
  163. p = uintptr(unsafe.Pointer(utlsConn.Conn))
  164. } else if realityConn, ok := iConn.(*reality.UConn); ok {
  165. t = reflect.TypeOf(realityConn.Conn).Elem()
  166. p = uintptr(unsafe.Pointer(realityConn.Conn))
  167. } else {
  168. return errors.New("XTLS only supports TLS and REALITY directly for now.").AtWarning()
  169. }
  170. i, _ := t.FieldByName("input")
  171. r, _ := t.FieldByName("rawInput")
  172. input = (*bytes.Reader)(unsafe.Pointer(p + i.Offset))
  173. rawInput = (*bytes.Buffer)(unsafe.Pointer(p + r.Offset))
  174. }
  175. default:
  176. ob.CanSpliceCopy = 3
  177. }
  178. var newCtx context.Context
  179. var newCancel context.CancelFunc
  180. if session.TimeoutOnlyFromContext(ctx) {
  181. newCtx, newCancel = context.WithCancel(context.Background())
  182. }
  183. sessionPolicy := h.policyManager.ForLevel(request.User.Level)
  184. ctx, cancel := context.WithCancel(ctx)
  185. timer := signal.CancelAfterInactivity(ctx, func() {
  186. cancel()
  187. if newCancel != nil {
  188. newCancel()
  189. }
  190. }, sessionPolicy.Timeouts.ConnectionIdle)
  191. clientReader := link.Reader // .(*pipe.Reader)
  192. clientWriter := link.Writer // .(*pipe.Writer)
  193. trafficState := proxy.NewTrafficState(account.ID.Bytes(), account.Flow)
  194. if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (h.cone && request.Port != 53 && request.Port != 443)) {
  195. request.Command = protocol.RequestCommandMux
  196. request.Address = net.DomainAddress("v1.mux.cool")
  197. request.Port = net.Port(666)
  198. }
  199. postRequest := func() error {
  200. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  201. bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
  202. if err := encoding.EncodeRequestHeader(bufferWriter, request, requestAddons); err != nil {
  203. return errors.New("failed to encode request header").Base(err).AtWarning()
  204. }
  205. // default: serverWriter := bufferWriter
  206. serverWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons, trafficState, true, ctx, conn, ob)
  207. if request.Command == protocol.RequestCommandMux && request.Port == 666 {
  208. serverWriter = xudp.NewPacketWriter(serverWriter, target, xudp.GetGlobalID(ctx))
  209. }
  210. timeoutReader, ok := clientReader.(buf.TimeoutReader)
  211. if ok {
  212. multiBuffer, err1 := timeoutReader.ReadMultiBufferTimeout(time.Millisecond * 500)
  213. if err1 == nil {
  214. if err := serverWriter.WriteMultiBuffer(multiBuffer); err != nil {
  215. return err // ...
  216. }
  217. } else if err1 != buf.ErrReadTimeout {
  218. return err1
  219. } else if requestAddons.Flow == vless.XRV {
  220. mb := make(buf.MultiBuffer, 1)
  221. errors.LogInfo(ctx, "Insert padding with empty content to camouflage VLESS header ", mb.Len())
  222. if err := serverWriter.WriteMultiBuffer(mb); err != nil {
  223. return err // ...
  224. }
  225. }
  226. } else {
  227. errors.LogDebug(ctx, "Reader is not timeout reader, will send out vless header separately from first payload")
  228. }
  229. // Flush; bufferWriter.WriteMultiBuffer now is bufferWriter.writer.WriteMultiBuffer
  230. if err := bufferWriter.SetBuffered(false); err != nil {
  231. return errors.New("failed to write A request payload").Base(err).AtWarning()
  232. }
  233. if requestAddons.Flow == vless.XRV {
  234. if tlsConn, ok := iConn.(*tls.Conn); ok {
  235. if tlsConn.ConnectionState().Version != gotls.VersionTLS13 {
  236. return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, tlsConn.ConnectionState().Version).AtWarning()
  237. }
  238. } else if utlsConn, ok := iConn.(*tls.UConn); ok {
  239. if utlsConn.ConnectionState().Version != utls.VersionTLS13 {
  240. return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, utlsConn.ConnectionState().Version).AtWarning()
  241. }
  242. }
  243. }
  244. err := buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer))
  245. if err != nil {
  246. return errors.New("failed to transfer request payload").Base(err).AtInfo()
  247. }
  248. // Indicates the end of request payload.
  249. switch requestAddons.Flow {
  250. default:
  251. }
  252. return nil
  253. }
  254. getResponse := func() error {
  255. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  256. responseAddons, err := encoding.DecodeResponseHeader(conn, request)
  257. if err != nil {
  258. return errors.New("failed to decode response header").Base(err).AtInfo()
  259. }
  260. // default: serverReader := buf.NewReader(conn)
  261. serverReader := encoding.DecodeBodyAddons(conn, request, responseAddons, trafficState, false, ctx, conn, input, rawInput, ob)
  262. if request.Command == protocol.RequestCommandMux && request.Port == 666 {
  263. serverReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: serverReader})
  264. }
  265. if requestAddons.Flow == vless.XRV {
  266. err = encoding.XtlsRead(serverReader, clientWriter, timer, conn, trafficState, false, ctx)
  267. } else {
  268. // from serverReader.ReadMultiBuffer to clientWriter.WriteMultiBuffer
  269. err = buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer))
  270. }
  271. if err != nil {
  272. return errors.New("failed to transfer response payload").Base(err).AtInfo()
  273. }
  274. return nil
  275. }
  276. if newCtx != nil {
  277. ctx = newCtx
  278. }
  279. if err := task.Run(ctx, postRequest, task.OnSuccess(getResponse, task.Close(clientWriter))); err != nil {
  280. return errors.New("connection ends").Base(err).AtInfo()
  281. }
  282. return nil
  283. }