condition.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. package router
  2. import (
  3. "context"
  4. "os"
  5. "path/filepath"
  6. "regexp"
  7. "slices"
  8. "strings"
  9. "github.com/xtls/xray-core/common/errors"
  10. "github.com/xtls/xray-core/common/net"
  11. "github.com/xtls/xray-core/common/strmatcher"
  12. "github.com/xtls/xray-core/features/routing"
  13. )
  14. type Condition interface {
  15. Apply(ctx routing.Context) bool
  16. }
  17. type ConditionChan []Condition
  18. func NewConditionChan() *ConditionChan {
  19. var condChan ConditionChan = make([]Condition, 0, 8)
  20. return &condChan
  21. }
  22. func (v *ConditionChan) Add(cond Condition) *ConditionChan {
  23. *v = append(*v, cond)
  24. return v
  25. }
  26. // Apply applies all conditions registered in this chan.
  27. func (v *ConditionChan) Apply(ctx routing.Context) bool {
  28. for _, cond := range *v {
  29. if !cond.Apply(ctx) {
  30. return false
  31. }
  32. }
  33. return true
  34. }
  35. func (v *ConditionChan) Len() int {
  36. return len(*v)
  37. }
  38. var matcherTypeMap = map[Domain_Type]strmatcher.Type{
  39. Domain_Plain: strmatcher.Substr,
  40. Domain_Regex: strmatcher.Regex,
  41. Domain_Domain: strmatcher.Domain,
  42. Domain_Full: strmatcher.Full,
  43. }
  44. type DomainMatcher struct {
  45. matchers strmatcher.IndexMatcher
  46. }
  47. func NewMphMatcherGroup(domains []*Domain) (*DomainMatcher, error) {
  48. g := strmatcher.NewMphMatcherGroup()
  49. for _, d := range domains {
  50. matcherType, f := matcherTypeMap[d.Type]
  51. if !f {
  52. errors.LogError(context.Background(), "ignore unsupported domain type ", d.Type, " of rule ", d.Value)
  53. continue
  54. }
  55. _, err := g.AddPattern(d.Value, matcherType)
  56. if err != nil {
  57. errors.LogErrorInner(context.Background(), err, "ignore domain rule ", d.Type, " ", d.Value)
  58. continue
  59. }
  60. }
  61. g.Build()
  62. return &DomainMatcher{
  63. matchers: g,
  64. }, nil
  65. }
  66. func (m *DomainMatcher) ApplyDomain(domain string) bool {
  67. return len(m.matchers.Match(strings.ToLower(domain))) > 0
  68. }
  69. // Apply implements Condition.
  70. func (m *DomainMatcher) Apply(ctx routing.Context) bool {
  71. domain := ctx.GetTargetDomain()
  72. if len(domain) == 0 {
  73. return false
  74. }
  75. return m.ApplyDomain(domain)
  76. }
  77. type MatcherAsType byte
  78. const (
  79. MatcherAsType_Local MatcherAsType = iota
  80. MatcherAsType_Source
  81. MatcherAsType_Target
  82. MatcherAsType_VlessRoute // for port
  83. )
  84. type IPMatcher struct {
  85. matcher GeoIPMatcher
  86. asType MatcherAsType
  87. }
  88. func NewIPMatcher(geoips []*GeoIP, asType MatcherAsType) (*IPMatcher, error) {
  89. matcher, err := BuildOptimizedGeoIPMatcher(geoips...)
  90. if err != nil {
  91. return nil, err
  92. }
  93. return &IPMatcher{matcher: matcher, asType: asType}, nil
  94. }
  95. // Apply implements Condition.
  96. func (m *IPMatcher) Apply(ctx routing.Context) bool {
  97. var ips []net.IP
  98. switch m.asType {
  99. case MatcherAsType_Local:
  100. ips = ctx.GetLocalIPs()
  101. case MatcherAsType_Source:
  102. ips = ctx.GetSourceIPs()
  103. case MatcherAsType_Target:
  104. ips = ctx.GetTargetIPs()
  105. default:
  106. panic("unk asType")
  107. }
  108. return m.matcher.AnyMatch(ips)
  109. }
  110. type PortMatcher struct {
  111. port net.MemoryPortList
  112. asType MatcherAsType
  113. }
  114. // NewPortMatcher create a new port matcher that can match source or local or destination port
  115. func NewPortMatcher(list *net.PortList, asType MatcherAsType) *PortMatcher {
  116. return &PortMatcher{
  117. port: net.PortListFromProto(list),
  118. asType: asType,
  119. }
  120. }
  121. // Apply implements Condition.
  122. func (v *PortMatcher) Apply(ctx routing.Context) bool {
  123. switch v.asType {
  124. case MatcherAsType_Local:
  125. return v.port.Contains(ctx.GetLocalPort())
  126. case MatcherAsType_Source:
  127. return v.port.Contains(ctx.GetSourcePort())
  128. case MatcherAsType_Target:
  129. return v.port.Contains(ctx.GetTargetPort())
  130. case MatcherAsType_VlessRoute:
  131. return v.port.Contains(ctx.GetVlessRoute())
  132. default:
  133. panic("unk asType")
  134. }
  135. }
  136. type NetworkMatcher struct {
  137. list [8]bool
  138. }
  139. func NewNetworkMatcher(network []net.Network) NetworkMatcher {
  140. var matcher NetworkMatcher
  141. for _, n := range network {
  142. matcher.list[int(n)] = true
  143. }
  144. return matcher
  145. }
  146. // Apply implements Condition.
  147. func (v NetworkMatcher) Apply(ctx routing.Context) bool {
  148. return v.list[int(ctx.GetNetwork())]
  149. }
  150. type UserMatcher struct {
  151. user []string
  152. pattern []*regexp.Regexp
  153. }
  154. func NewUserMatcher(users []string) *UserMatcher {
  155. usersCopy := make([]string, 0, len(users))
  156. patternsCopy := make([]*regexp.Regexp, 0, len(users))
  157. for _, user := range users {
  158. if len(user) > 0 {
  159. if len(user) > 7 && strings.HasPrefix(user, "regexp:") {
  160. if re, err := regexp.Compile(user[7:]); err == nil {
  161. patternsCopy = append(patternsCopy, re)
  162. }
  163. // Items of users slice with an invalid regexp syntax are ignored.
  164. continue
  165. }
  166. usersCopy = append(usersCopy, user)
  167. }
  168. }
  169. return &UserMatcher{
  170. user: usersCopy,
  171. pattern: patternsCopy,
  172. }
  173. }
  174. // Apply implements Condition.
  175. func (v *UserMatcher) Apply(ctx routing.Context) bool {
  176. user := ctx.GetUser()
  177. if len(user) == 0 {
  178. return false
  179. }
  180. for _, u := range v.user {
  181. if u == user {
  182. return true
  183. }
  184. }
  185. for _, re := range v.pattern {
  186. if re.MatchString(user) {
  187. return true
  188. }
  189. }
  190. return false
  191. }
  192. type InboundTagMatcher struct {
  193. tags []string
  194. }
  195. func NewInboundTagMatcher(tags []string) *InboundTagMatcher {
  196. tagsCopy := make([]string, 0, len(tags))
  197. for _, tag := range tags {
  198. if len(tag) > 0 {
  199. tagsCopy = append(tagsCopy, tag)
  200. }
  201. }
  202. return &InboundTagMatcher{
  203. tags: tagsCopy,
  204. }
  205. }
  206. // Apply implements Condition.
  207. func (v *InboundTagMatcher) Apply(ctx routing.Context) bool {
  208. tag := ctx.GetInboundTag()
  209. if len(tag) == 0 {
  210. return false
  211. }
  212. for _, t := range v.tags {
  213. if t == tag {
  214. return true
  215. }
  216. }
  217. return false
  218. }
  219. type ProtocolMatcher struct {
  220. protocols []string
  221. }
  222. func NewProtocolMatcher(protocols []string) *ProtocolMatcher {
  223. pCopy := make([]string, 0, len(protocols))
  224. for _, p := range protocols {
  225. if len(p) > 0 {
  226. pCopy = append(pCopy, p)
  227. }
  228. }
  229. return &ProtocolMatcher{
  230. protocols: pCopy,
  231. }
  232. }
  233. // Apply implements Condition.
  234. func (m *ProtocolMatcher) Apply(ctx routing.Context) bool {
  235. protocol := ctx.GetProtocol()
  236. if len(protocol) == 0 {
  237. return false
  238. }
  239. for _, p := range m.protocols {
  240. if strings.HasPrefix(protocol, p) {
  241. return true
  242. }
  243. }
  244. return false
  245. }
  246. type AttributeMatcher struct {
  247. configuredKeys map[string]*regexp.Regexp
  248. }
  249. // Match implements attributes matching.
  250. func (m *AttributeMatcher) Match(attrs map[string]string) bool {
  251. // header keys are case insensitive most likely. So we do a convert
  252. httpHeaders := make(map[string]string)
  253. for key, value := range attrs {
  254. httpHeaders[strings.ToLower(key)] = value
  255. }
  256. for key, regex := range m.configuredKeys {
  257. if a, ok := httpHeaders[key]; !ok || !regex.MatchString(a) {
  258. return false
  259. }
  260. }
  261. return true
  262. }
  263. // Apply implements Condition.
  264. func (m *AttributeMatcher) Apply(ctx routing.Context) bool {
  265. attributes := ctx.GetAttributes()
  266. if attributes == nil {
  267. return false
  268. }
  269. return m.Match(attributes)
  270. }
  271. // Geo attribute
  272. type GeoAttributeMatcher interface {
  273. Match(*Domain) bool
  274. }
  275. type GeoBooleanMatcher string
  276. func (m GeoBooleanMatcher) Match(domain *Domain) bool {
  277. for _, attr := range domain.Attribute {
  278. if attr.Key == string(m) {
  279. return true
  280. }
  281. }
  282. return false
  283. }
  284. type GeoAttributeList struct {
  285. Matcher []GeoAttributeMatcher
  286. }
  287. func (al *GeoAttributeList) Match(domain *Domain) bool {
  288. for _, matcher := range al.Matcher {
  289. if !matcher.Match(domain) {
  290. return false
  291. }
  292. }
  293. return true
  294. }
  295. func (al *GeoAttributeList) IsEmpty() bool {
  296. return len(al.Matcher) == 0
  297. }
  298. func ParseAttrs(attrs []string) *GeoAttributeList {
  299. al := new(GeoAttributeList)
  300. for _, attr := range attrs {
  301. lc := strings.ToLower(attr)
  302. al.Matcher = append(al.Matcher, GeoBooleanMatcher(lc))
  303. }
  304. return al
  305. }
  306. type ProcessNameMatcher struct {
  307. ProcessNames []string
  308. AbsPaths []string
  309. Folders []string
  310. MatchXraySelf bool
  311. }
  312. func NewProcessNameMatcher(names []string) *ProcessNameMatcher {
  313. processNames := []string{}
  314. folders := []string{}
  315. absPaths := []string{}
  316. matchXraySelf := false
  317. for _, name := range names {
  318. if name == "self/" {
  319. matchXraySelf = true
  320. continue
  321. }
  322. // replace xray/ with self executable path
  323. if name == "xray/" {
  324. xrayPath, err := os.Executable()
  325. if err != nil {
  326. errors.LogError(context.Background(), "Failed to get xray executable path: ", err)
  327. continue
  328. }
  329. name = xrayPath
  330. }
  331. name := filepath.ToSlash(name)
  332. // /usr/bin/
  333. if strings.HasSuffix(name, "/") {
  334. folders = append(folders, name)
  335. continue
  336. }
  337. // /usr/bin/curl
  338. if strings.Contains(name, "/") {
  339. absPaths = append(absPaths, name)
  340. continue
  341. }
  342. // curl.exe or curl
  343. processNames = append(processNames, strings.TrimSuffix(name, ".exe"))
  344. }
  345. return &ProcessNameMatcher{
  346. ProcessNames: processNames,
  347. AbsPaths: absPaths,
  348. Folders: folders,
  349. MatchXraySelf: matchXraySelf,
  350. }
  351. }
  352. func (m *ProcessNameMatcher) Apply(ctx routing.Context) bool {
  353. srcPort := ctx.GetSourcePort().String()
  354. srcIP := ctx.GetSourceIPs()[0].String()
  355. var network string
  356. switch ctx.GetNetwork() {
  357. case net.Network_TCP:
  358. network = "tcp"
  359. case net.Network_UDP:
  360. network = "udp"
  361. default:
  362. return false
  363. }
  364. src, err := net.ParseDestination(strings.Join([]string{network, srcIP, srcPort}, ":"))
  365. if err != nil {
  366. return false
  367. }
  368. pid, name, absPath, err := net.FindProcess(src)
  369. if err != nil {
  370. if err != net.ErrNotLocal {
  371. errors.LogError(context.Background(), "Unables to find local process name: ", err)
  372. }
  373. return false
  374. }
  375. if m.MatchXraySelf {
  376. if pid == os.Getpid() {
  377. return true
  378. }
  379. }
  380. if slices.Contains(m.ProcessNames, name) {
  381. return true
  382. }
  383. if slices.Contains(m.AbsPaths, absPath) {
  384. return true
  385. }
  386. for _, f := range m.Folders {
  387. if strings.HasPrefix(absPath, f) {
  388. return true
  389. }
  390. }
  391. return false
  392. }