rule_action.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. package rule
  2. import (
  3. "context"
  4. "errors"
  5. "net/netip"
  6. "strings"
  7. "sync"
  8. "syscall"
  9. "time"
  10. "github.com/sagernet/sing-box/adapter"
  11. "github.com/sagernet/sing-box/common/dialer"
  12. "github.com/sagernet/sing-box/common/sniff"
  13. C "github.com/sagernet/sing-box/constant"
  14. "github.com/sagernet/sing-box/option"
  15. "github.com/sagernet/sing-tun"
  16. "github.com/sagernet/sing/common"
  17. E "github.com/sagernet/sing/common/exceptions"
  18. F "github.com/sagernet/sing/common/format"
  19. "github.com/sagernet/sing/common/logger"
  20. M "github.com/sagernet/sing/common/metadata"
  21. N "github.com/sagernet/sing/common/network"
  22. "github.com/miekg/dns"
  23. )
  24. func NewRuleAction(ctx context.Context, logger logger.ContextLogger, action option.RuleAction) (adapter.RuleAction, error) {
  25. switch action.Action {
  26. case "":
  27. return nil, nil
  28. case C.RuleActionTypeRoute:
  29. return &RuleActionRoute{
  30. Outbound: action.RouteOptions.Outbound,
  31. RuleActionRouteOptions: RuleActionRouteOptions{
  32. OverrideAddress: M.ParseSocksaddrHostPort(action.RouteOptions.OverrideAddress, 0),
  33. OverridePort: action.RouteOptions.OverridePort,
  34. NetworkStrategy: (*C.NetworkStrategy)(action.RouteOptions.NetworkStrategy),
  35. FallbackDelay: time.Duration(action.RouteOptions.FallbackDelay),
  36. UDPDisableDomainUnmapping: action.RouteOptions.UDPDisableDomainUnmapping,
  37. UDPConnect: action.RouteOptions.UDPConnect,
  38. TLSFragment: action.RouteOptions.TLSFragment,
  39. TLSFragmentFallbackDelay: time.Duration(action.RouteOptions.TLSFragmentFallbackDelay),
  40. },
  41. }, nil
  42. case C.RuleActionTypeRouteOptions:
  43. return &RuleActionRouteOptions{
  44. OverrideAddress: M.ParseSocksaddrHostPort(action.RouteOptionsOptions.OverrideAddress, 0),
  45. OverridePort: action.RouteOptionsOptions.OverridePort,
  46. NetworkStrategy: (*C.NetworkStrategy)(action.RouteOptionsOptions.NetworkStrategy),
  47. FallbackDelay: time.Duration(action.RouteOptionsOptions.FallbackDelay),
  48. UDPDisableDomainUnmapping: action.RouteOptionsOptions.UDPDisableDomainUnmapping,
  49. UDPConnect: action.RouteOptionsOptions.UDPConnect,
  50. UDPTimeout: time.Duration(action.RouteOptionsOptions.UDPTimeout),
  51. TLSFragment: action.RouteOptionsOptions.TLSFragment,
  52. TLSFragmentFallbackDelay: time.Duration(action.RouteOptionsOptions.TLSFragmentFallbackDelay),
  53. }, nil
  54. case C.RuleActionTypeDirect:
  55. directDialer, err := dialer.New(ctx, option.DialerOptions(action.DirectOptions), false)
  56. if err != nil {
  57. return nil, err
  58. }
  59. var description string
  60. descriptions := action.DirectOptions.Descriptions()
  61. switch len(descriptions) {
  62. case 0:
  63. case 1:
  64. description = F.ToString("(", descriptions[0], ")")
  65. case 2:
  66. description = F.ToString("(", descriptions[0], ",", descriptions[1], ")")
  67. default:
  68. description = F.ToString("(", descriptions[0], ",", descriptions[1], ",...)")
  69. }
  70. return &RuleActionDirect{
  71. Dialer: directDialer,
  72. description: description,
  73. }, nil
  74. case C.RuleActionTypeReject:
  75. return &RuleActionReject{
  76. Method: action.RejectOptions.Method,
  77. NoDrop: action.RejectOptions.NoDrop,
  78. logger: logger,
  79. }, nil
  80. case C.RuleActionTypeHijackDNS:
  81. return &RuleActionHijackDNS{}, nil
  82. case C.RuleActionTypeSniff:
  83. sniffAction := &RuleActionSniff{
  84. snifferNames: action.SniffOptions.Sniffer,
  85. Timeout: time.Duration(action.SniffOptions.Timeout),
  86. }
  87. return sniffAction, sniffAction.build()
  88. case C.RuleActionTypeResolve:
  89. return &RuleActionResolve{
  90. Server: action.ResolveOptions.Server,
  91. Strategy: C.DomainStrategy(action.ResolveOptions.Strategy),
  92. DisableCache: action.ResolveOptions.DisableCache,
  93. RewriteTTL: action.ResolveOptions.RewriteTTL,
  94. ClientSubnet: action.ResolveOptions.ClientSubnet.Build(netip.Prefix{}),
  95. }, nil
  96. default:
  97. panic(F.ToString("unknown rule action: ", action.Action))
  98. }
  99. }
  100. func NewDNSRuleAction(logger logger.ContextLogger, action option.DNSRuleAction) adapter.RuleAction {
  101. switch action.Action {
  102. case "":
  103. return nil
  104. case C.RuleActionTypeRoute:
  105. return &RuleActionDNSRoute{
  106. Server: action.RouteOptions.Server,
  107. RuleActionDNSRouteOptions: RuleActionDNSRouteOptions{
  108. Strategy: C.DomainStrategy(action.RouteOptions.Strategy),
  109. DisableCache: action.RouteOptions.DisableCache,
  110. RewriteTTL: action.RouteOptions.RewriteTTL,
  111. ClientSubnet: netip.Prefix(common.PtrValueOrDefault(action.RouteOptions.ClientSubnet)),
  112. },
  113. }
  114. case C.RuleActionTypeRouteOptions:
  115. return &RuleActionDNSRouteOptions{
  116. Strategy: C.DomainStrategy(action.RouteOptionsOptions.Strategy),
  117. DisableCache: action.RouteOptionsOptions.DisableCache,
  118. RewriteTTL: action.RouteOptionsOptions.RewriteTTL,
  119. ClientSubnet: netip.Prefix(common.PtrValueOrDefault(action.RouteOptionsOptions.ClientSubnet)),
  120. }
  121. case C.RuleActionTypeReject:
  122. return &RuleActionReject{
  123. Method: action.RejectOptions.Method,
  124. NoDrop: action.RejectOptions.NoDrop,
  125. logger: logger,
  126. }
  127. case C.RuleActionTypePredefined:
  128. return &RuleActionPredefined{
  129. Rcode: action.PredefinedOptions.Rcode.Build(),
  130. Answer: common.Map(action.PredefinedOptions.Answer, option.DNSRecordOptions.Build),
  131. Ns: common.Map(action.PredefinedOptions.Ns, option.DNSRecordOptions.Build),
  132. Extra: common.Map(action.PredefinedOptions.Extra, option.DNSRecordOptions.Build),
  133. }
  134. default:
  135. panic(F.ToString("unknown rule action: ", action.Action))
  136. }
  137. }
  138. type RuleActionRoute struct {
  139. Outbound string
  140. RuleActionRouteOptions
  141. }
  142. func (r *RuleActionRoute) Type() string {
  143. return C.RuleActionTypeRoute
  144. }
  145. func (r *RuleActionRoute) String() string {
  146. var descriptions []string
  147. descriptions = append(descriptions, r.Outbound)
  148. if r.UDPDisableDomainUnmapping {
  149. descriptions = append(descriptions, "udp-disable-domain-unmapping")
  150. }
  151. if r.UDPConnect {
  152. descriptions = append(descriptions, "udp-connect")
  153. }
  154. if r.TLSFragment {
  155. descriptions = append(descriptions, "tls-fragment")
  156. }
  157. return F.ToString("route(", strings.Join(descriptions, ","), ")")
  158. }
  159. type RuleActionRouteOptions struct {
  160. OverrideAddress M.Socksaddr
  161. OverridePort uint16
  162. NetworkStrategy *C.NetworkStrategy
  163. NetworkType []C.InterfaceType
  164. FallbackNetworkType []C.InterfaceType
  165. FallbackDelay time.Duration
  166. UDPDisableDomainUnmapping bool
  167. UDPConnect bool
  168. UDPTimeout time.Duration
  169. TLSFragment bool
  170. TLSFragmentFallbackDelay time.Duration
  171. }
  172. func (r *RuleActionRouteOptions) Type() string {
  173. return C.RuleActionTypeRouteOptions
  174. }
  175. func (r *RuleActionRouteOptions) String() string {
  176. var descriptions []string
  177. if r.OverrideAddress.IsValid() {
  178. descriptions = append(descriptions, F.ToString("override-address=", r.OverrideAddress.AddrString()))
  179. }
  180. if r.OverridePort > 0 {
  181. descriptions = append(descriptions, F.ToString("override-port=", r.OverridePort))
  182. }
  183. if r.NetworkStrategy != nil {
  184. descriptions = append(descriptions, F.ToString("network-strategy=", r.NetworkStrategy))
  185. }
  186. if r.NetworkType != nil {
  187. descriptions = append(descriptions, F.ToString("network-type=", strings.Join(common.Map(r.NetworkType, C.InterfaceType.String), ",")))
  188. }
  189. if r.FallbackNetworkType != nil {
  190. descriptions = append(descriptions, F.ToString("fallback-network-type="+strings.Join(common.Map(r.NetworkType, C.InterfaceType.String), ",")))
  191. }
  192. if r.FallbackDelay > 0 {
  193. descriptions = append(descriptions, F.ToString("fallback-delay=", r.FallbackDelay.String()))
  194. }
  195. if r.UDPDisableDomainUnmapping {
  196. descriptions = append(descriptions, "udp-disable-domain-unmapping")
  197. }
  198. if r.UDPConnect {
  199. descriptions = append(descriptions, "udp-connect")
  200. }
  201. if r.UDPTimeout > 0 {
  202. descriptions = append(descriptions, "udp-timeout")
  203. }
  204. return F.ToString("route-options(", strings.Join(descriptions, ","), ")")
  205. }
  206. type RuleActionDNSRoute struct {
  207. Server string
  208. RuleActionDNSRouteOptions
  209. }
  210. func (r *RuleActionDNSRoute) Type() string {
  211. return C.RuleActionTypeRoute
  212. }
  213. func (r *RuleActionDNSRoute) String() string {
  214. var descriptions []string
  215. descriptions = append(descriptions, r.Server)
  216. if r.DisableCache {
  217. descriptions = append(descriptions, "disable-cache")
  218. }
  219. if r.RewriteTTL != nil {
  220. descriptions = append(descriptions, F.ToString("rewrite-ttl=", *r.RewriteTTL))
  221. }
  222. if r.ClientSubnet.IsValid() {
  223. descriptions = append(descriptions, F.ToString("client-subnet=", r.ClientSubnet))
  224. }
  225. return F.ToString("route(", strings.Join(descriptions, ","), ")")
  226. }
  227. type RuleActionDNSRouteOptions struct {
  228. Strategy C.DomainStrategy
  229. DisableCache bool
  230. RewriteTTL *uint32
  231. ClientSubnet netip.Prefix
  232. }
  233. func (r *RuleActionDNSRouteOptions) Type() string {
  234. return C.RuleActionTypeRouteOptions
  235. }
  236. func (r *RuleActionDNSRouteOptions) String() string {
  237. var descriptions []string
  238. if r.DisableCache {
  239. descriptions = append(descriptions, "disable-cache")
  240. }
  241. if r.RewriteTTL != nil {
  242. descriptions = append(descriptions, F.ToString("rewrite-ttl=", *r.RewriteTTL))
  243. }
  244. if r.ClientSubnet.IsValid() {
  245. descriptions = append(descriptions, F.ToString("client-subnet=", r.ClientSubnet))
  246. }
  247. return F.ToString("route-options(", strings.Join(descriptions, ","), ")")
  248. }
  249. type RuleActionDirect struct {
  250. Dialer N.Dialer
  251. description string
  252. }
  253. func (r *RuleActionDirect) Type() string {
  254. return C.RuleActionTypeDirect
  255. }
  256. func (r *RuleActionDirect) String() string {
  257. return "direct" + r.description
  258. }
  259. type RejectedError struct {
  260. Cause error
  261. }
  262. func (r *RejectedError) Error() string {
  263. return "rejected"
  264. }
  265. func (r *RejectedError) Unwrap() error {
  266. return r.Cause
  267. }
  268. func IsRejected(err error) bool {
  269. var rejected *RejectedError
  270. return errors.As(err, &rejected)
  271. }
  272. type RuleActionReject struct {
  273. Method string
  274. NoDrop bool
  275. logger logger.ContextLogger
  276. dropAccess sync.Mutex
  277. dropCounter []time.Time
  278. }
  279. func (r *RuleActionReject) Type() string {
  280. return C.RuleActionTypeReject
  281. }
  282. func (r *RuleActionReject) String() string {
  283. if r.Method == C.RuleActionRejectMethodDefault {
  284. return "reject"
  285. }
  286. return F.ToString("reject(", r.Method, ")")
  287. }
  288. func (r *RuleActionReject) Error(ctx context.Context) error {
  289. var returnErr error
  290. switch r.Method {
  291. case C.RuleActionRejectMethodDefault:
  292. returnErr = &RejectedError{syscall.ECONNREFUSED}
  293. case C.RuleActionRejectMethodDrop:
  294. return &RejectedError{tun.ErrDrop}
  295. default:
  296. panic(F.ToString("unknown reject method: ", r.Method))
  297. }
  298. if r.NoDrop {
  299. return returnErr
  300. }
  301. r.dropAccess.Lock()
  302. defer r.dropAccess.Unlock()
  303. timeNow := time.Now()
  304. r.dropCounter = common.Filter(r.dropCounter, func(t time.Time) bool {
  305. return timeNow.Sub(t) <= 30*time.Second
  306. })
  307. r.dropCounter = append(r.dropCounter, timeNow)
  308. if len(r.dropCounter) > 50 {
  309. if ctx != nil {
  310. r.logger.DebugContext(ctx, "dropped due to flooding")
  311. }
  312. return &RejectedError{tun.ErrDrop}
  313. }
  314. return returnErr
  315. }
  316. type RuleActionHijackDNS struct{}
  317. func (r *RuleActionHijackDNS) Type() string {
  318. return C.RuleActionTypeHijackDNS
  319. }
  320. func (r *RuleActionHijackDNS) String() string {
  321. return "hijack-dns"
  322. }
  323. type RuleActionSniff struct {
  324. snifferNames []string
  325. StreamSniffers []sniff.StreamSniffer
  326. PacketSniffers []sniff.PacketSniffer
  327. Timeout time.Duration
  328. // Deprecated
  329. OverrideDestination bool
  330. }
  331. func (r *RuleActionSniff) Type() string {
  332. return C.RuleActionTypeSniff
  333. }
  334. func (r *RuleActionSniff) build() error {
  335. for _, name := range r.snifferNames {
  336. switch name {
  337. case C.ProtocolTLS:
  338. r.StreamSniffers = append(r.StreamSniffers, sniff.TLSClientHello)
  339. case C.ProtocolHTTP:
  340. r.StreamSniffers = append(r.StreamSniffers, sniff.HTTPHost)
  341. case C.ProtocolQUIC:
  342. r.PacketSniffers = append(r.PacketSniffers, sniff.QUICClientHello)
  343. case C.ProtocolDNS:
  344. r.StreamSniffers = append(r.StreamSniffers, sniff.StreamDomainNameQuery)
  345. r.PacketSniffers = append(r.PacketSniffers, sniff.DomainNameQuery)
  346. case C.ProtocolSTUN:
  347. r.PacketSniffers = append(r.PacketSniffers, sniff.STUNMessage)
  348. case C.ProtocolBitTorrent:
  349. r.StreamSniffers = append(r.StreamSniffers, sniff.BitTorrent)
  350. r.PacketSniffers = append(r.PacketSniffers, sniff.UTP)
  351. r.PacketSniffers = append(r.PacketSniffers, sniff.UDPTracker)
  352. case C.ProtocolDTLS:
  353. r.PacketSniffers = append(r.PacketSniffers, sniff.DTLSRecord)
  354. case C.ProtocolSSH:
  355. r.StreamSniffers = append(r.StreamSniffers, sniff.SSH)
  356. case C.ProtocolRDP:
  357. r.StreamSniffers = append(r.StreamSniffers, sniff.RDP)
  358. case C.ProtocolNTP:
  359. r.PacketSniffers = append(r.PacketSniffers, sniff.NTP)
  360. default:
  361. return E.New("unknown sniffer: ", name)
  362. }
  363. }
  364. return nil
  365. }
  366. func (r *RuleActionSniff) String() string {
  367. if len(r.snifferNames) == 0 && r.Timeout == 0 {
  368. return "sniff"
  369. } else if len(r.snifferNames) > 0 && r.Timeout == 0 {
  370. return F.ToString("sniff(", strings.Join(r.snifferNames, ","), ")")
  371. } else if len(r.snifferNames) == 0 && r.Timeout > 0 {
  372. return F.ToString("sniff(", r.Timeout.String(), ")")
  373. } else {
  374. return F.ToString("sniff(", strings.Join(r.snifferNames, ","), ",", r.Timeout.String(), ")")
  375. }
  376. }
  377. type RuleActionResolve struct {
  378. Server string
  379. Strategy C.DomainStrategy
  380. DisableCache bool
  381. RewriteTTL *uint32
  382. ClientSubnet netip.Prefix
  383. }
  384. func (r *RuleActionResolve) Type() string {
  385. return C.RuleActionTypeResolve
  386. }
  387. func (r *RuleActionResolve) String() string {
  388. var options []string
  389. if r.Server != "" {
  390. options = append(options, r.Server)
  391. }
  392. if r.Strategy != C.DomainStrategyAsIS {
  393. options = append(options, F.ToString(option.DomainStrategy(r.Strategy)))
  394. }
  395. if r.DisableCache {
  396. options = append(options, "disable_cache")
  397. }
  398. if r.RewriteTTL != nil {
  399. options = append(options, F.ToString("rewrite_ttl=", *r.RewriteTTL))
  400. }
  401. if r.ClientSubnet.IsValid() {
  402. options = append(options, F.ToString("client_subnet=", r.ClientSubnet))
  403. }
  404. if len(options) == 0 {
  405. return "resolve"
  406. } else {
  407. return F.ToString("resolve(", strings.Join(options, ","), ")")
  408. }
  409. }
  410. type RuleActionPredefined struct {
  411. Rcode int
  412. Answer []dns.RR
  413. Ns []dns.RR
  414. Extra []dns.RR
  415. }
  416. func (r *RuleActionPredefined) Type() string {
  417. return C.RuleActionTypePredefined
  418. }
  419. func (r *RuleActionPredefined) String() string {
  420. var options []string
  421. options = append(options, dns.RcodeToString[r.Rcode])
  422. options = append(options, common.Map(r.Answer, dns.RR.String)...)
  423. options = append(options, common.Map(r.Ns, dns.RR.String)...)
  424. options = append(options, common.Map(r.Extra, dns.RR.String)...)
  425. return F.ToString("predefined(", strings.Join(options, ","), ")")
  426. }
  427. func (r *RuleActionPredefined) Response(request *dns.Msg) *dns.Msg {
  428. return &dns.Msg{
  429. MsgHdr: dns.MsgHdr{
  430. Id: request.Id,
  431. Response: true,
  432. Authoritative: true,
  433. RecursionDesired: true,
  434. RecursionAvailable: true,
  435. Rcode: r.Rcode,
  436. },
  437. Question: request.Question,
  438. Answer: rewriteRecords(r.Answer, request.Question[0]),
  439. Ns: rewriteRecords(r.Ns, request.Question[0]),
  440. Extra: rewriteRecords(r.Extra, request.Question[0]),
  441. }
  442. }
  443. func rewriteRecords(records []dns.RR, question dns.Question) []dns.RR {
  444. return common.Map(records, func(it dns.RR) dns.RR {
  445. if strings.HasPrefix(it.Header().Name, "*") {
  446. if strings.HasSuffix(question.Name, it.Header().Name[1:]) {
  447. it = dns.Copy(it)
  448. it.Header().Name = question.Name
  449. }
  450. }
  451. return it
  452. })
  453. }